INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
For each string return a new string that is a substring of the original string.
def substring(self, start_index, end_index=None): """ For each string, return a new string that is a substring of the original string. If end_index is not specified, then the substring extends to the end of the original string. If the start_index is longer than the length of the string,...
Return a copy of the column with leading characters removed.
def lstrip(self, set=" "): """ Return a copy of the column with leading characters removed. The set argument is a string specifying the set of characters to be removed. If omitted, the set argument defaults to removing whitespace. :param character set: The set of characters to ...
For each string compute its Shannon entropy if the string is empty the entropy is 0.
def entropy(self): """ For each string compute its Shannon entropy, if the string is empty the entropy is 0. :returns: an H2OFrame of Shannon entropies. """ fr = H2OFrame._expr(expr=ExprNode("entropy", self)) fr._ex._cache.nrows = self.nrow fr._ex._cache.ncol = s...
For each string find the count of all possible substrings with 2 characters or more that are contained in the line - separated text file whose path is given.
def num_valid_substrings(self, path_to_words): """ For each string, find the count of all possible substrings with 2 characters or more that are contained in the line-separated text file whose path is given. :param str path_to_words: Path to file that contains a line-separated list of s...
Compute the counts of values appearing in a column or co - occurence counts between two columns.
def table(self, data2=None, dense=True): """ Compute the counts of values appearing in a column, or co-occurence counts between two columns. :param H2OFrame data2: An optional single column to aggregate counts by. :param bool dense: If True (default) then use dense representation, which...
Compute a histogram over a numeric column.
def hist(self, breaks="sturges", plot=True, **kwargs): """ Compute a histogram over a numeric column. :param breaks: Can be one of ``"sturges"``, ``"rice"``, ``"sqrt"``, ``"doane"``, ``"fd"``, ``"scott"``; or a single number for the number of breaks; or a list containing the split p...
Compute the iSAX index for DataFrame which is assumed to be numeric time series data.
def isax(self, num_words, max_cardinality, optimize_card=False, **kwargs): """ Compute the iSAX index for DataFrame which is assumed to be numeric time series data. References: - http://www.cs.ucr.edu/~eamonn/SAX.pdf - http://www.cs.ucr.edu/~eamonn/iSAX_2.0.pdf ...
This method requires that you import the following toolboxes: xgboost pandas numpy and scipy. sparse.
def convert_H2OFrame_2_DMatrix(self, predictors, yresp, h2oXGBoostModel): ''' This method requires that you import the following toolboxes: xgboost, pandas, numpy and scipy.sparse. This method will convert an H2OFrame to a DMatrix that can be used by native XGBoost. The H2OFrame contains ...
Pivot the frame designated by the three columns: index column and value. Index and column should be of type enum int or time. For cases of multiple indexes for a column label the aggregation method is to pick the first occurrence in the data frame
def pivot(self, index, column, value): """ Pivot the frame designated by the three columns: index, column, and value. Index and column should be of type enum, int, or time. For cases of multiple indexes for a column label, the aggregation method is to pick the first occurrence in the dat...
This function will add a new column rank where the ranking is produced as follows: 1. sorts the H2OFrame by columns sorted in by columns specified in group_by_cols and sort_cols in the directions specified by the ascending for the sort_cols. The sort directions for the group_by_cols are ascending only. 2. A new rank co...
def rank_within_group_by(self, group_by_cols, sort_cols, ascending=[], new_col_name="New_Rank_column", sort_cols_sorted=False): """ This function will add a new column rank where the ranking is produced as follows: 1. sorts the H2OFrame by columns sorted in by columns specified in group_by_cols...
Given a column name or one column index a percent N this function will return the top or bottom N% of the values of the column of a frame. The column must be a numerical column.: param column: a string for column name or an integer index: param nPercent: a top or bottom percentage of the column values to return: param ...
def topNBottomN(self, column=0, nPercent=10, grabTopN=-1): """ Given a column name or one column index, a percent N, this function will return the top or bottom N% of the values of the column of a frame. The column must be a numerical column. :param column: a string for column nam...
Substitute the first occurrence of pattern in a string with replacement.
def sub(self, pattern, replacement, ignore_case=False): """ Substitute the first occurrence of pattern in a string with replacement. :param str pattern: A regular expression. :param str replacement: A replacement string. :param bool ignore_case: If True then pattern will match c...
Categorical Interaction Feature Creation in H2O.
def interaction(self, factors, pairwise, max_factors, min_occurrence, destination_frame=None): """ Categorical Interaction Feature Creation in H2O. Creates a frame in H2O with n-th order interaction features between categorical columns, as specified by the user. :param factors:...
Translate characters from lower to upper case for a particular column.
def toupper(self): """ Translate characters from lower to upper case for a particular column. :returns: new H2OFrame with all strings in the current frame converted to the uppercase. """ return H2OFrame._expr(expr=ExprNode("toupper", self), cache=self._ex._cache)
Searches for matches to argument pattern within each element of a string column.
def grep(self,pattern, ignore_case = False, invert = False, output_logical = False): """ Searches for matches to argument `pattern` within each element of a string column. Default behavior is to return indices of the elements matching the pattern. Parameter `output_logical` can ...
Center and/ or scale the columns of the current frame.
def scale(self, center=True, scale=True): """ Center and/or scale the columns of the current frame. :param center: If True, then demean the data. If False, no shifting is done. If ``center`` is a list of numbers then shift each column by the corresponding amount. :param scal...
Round doubles/ floats to the given number of significant digits.
def signif(self, digits=6): """ Round doubles/floats to the given number of significant digits. :param int digits: Number of significant digits to retain. :returns: new H2OFrame with rounded values from the original frame. """ return H2OFrame._expr(expr=ExprNode("signif"...
Remove rows with NAs from the H2OFrame.
def na_omit(self): """ Remove rows with NAs from the H2OFrame. :returns: new H2OFrame with all rows from the original frame containing any NAs removed. """ fr = H2OFrame._expr(expr=ExprNode("na.omit", self), cache=self._ex._cache) fr._ex._cache.nrows = -1 return ...
Conduct a diff - 1 transform on a numeric frame column.
def difflag1(self): """ Conduct a diff-1 transform on a numeric frame column. :returns: an H2OFrame where each element is equal to the corresponding element in the source frame minus the previous-row element in the same frame. """ if self.ncols > 1: raise...
For each element in an H2OFrame determine if it is NA or not.
def isna(self): """ For each element in an H2OFrame, determine if it is NA or not. :returns: an H2OFrame of 1s and 0s, where 1s mean the values were NAs. """ fr = H2OFrame._expr(expr=ExprNode("is.na", self)) fr._ex._cache.nrows = self._ex._cache.nrows fr._ex._cac...
Extract the minute part from a date column.
def minute(self): """ Extract the "minute" part from a date column. :returns: a single-column H2OFrame containing the "minute" part from the source frame. """ fr = H2OFrame._expr(expr=ExprNode("minute", self), cache=self._ex._cache) if fr._ex._cache.types_valid(): ...
Generate a column of random numbers drawn from a uniform distribution [ 0 1 ) and having the same data layout as the source frame.
def runif(self, seed=None): """ Generate a column of random numbers drawn from a uniform distribution [0,1) and having the same data layout as the source frame. :param int seed: seed for the random number generator. :returns: Single-column H2OFrame filled with doubles sampled u...
Construct a column that can be used to perform a random stratified split.
def stratified_split(self, test_frac=0.2, seed=-1): """ Construct a column that can be used to perform a random stratified split. :param float test_frac: The fraction of rows that will belong to the "test". :param int seed: The seed for the random number generator. :returns: an...
Make a vector of the positions of ( first ) matches of its first argument in its second.
def match(self, table, nomatch=0): """ Make a vector of the positions of (first) matches of its first argument in its second. Only applicable to single-column categorical/string frames. :param List table: the list of items to match against :param int nomatch: value that should ...
Cut a numeric vector into categorical buckets.
def cut(self, breaks, labels=None, include_lowest=False, right=True, dig_lab=3): """ Cut a numeric vector into categorical "buckets". This method is only applicable to a single-column numeric frame. :param List[float] breaks: The cut points in the numeric vector. :param List[st...
Get the index of the max value in a column or row
def idxmax(self,skipna=True, axis=0): """ Get the index of the max value in a column or row :param bool skipna: If True (default), then NAs are ignored during the search. Otherwise presence of NAs renders the entire result NA. :param int axis: Direction of finding the max in...
Equivalent to [ y if t else n for t y n in zip ( self yes no ) ].
def ifelse(self, yes, no): """ Equivalent to ``[y if t else n for t,y,n in zip(self,yes,no)]``. Based on the booleans in the test vector, the output has the values of the yes and no vectors interleaved (or merged together). All Frames must have the same row count. Single colum...
Apply a lambda expression to an H2OFrame.
def apply(self, fun=None, axis=0): """ Apply a lambda expression to an H2OFrame. :param fun: a lambda expression to be applied per row or per column. :param axis: 0 = apply to each column; 1 = apply to each row :returns: a new H2OFrame with the results of applying ``fun`` to the...
Deprecated use: func: moment instead.
def mktime(year=1970, month=0, day=0, hour=0, minute=0, second=0, msec=0): """ Deprecated, use :func:`moment` instead. This function was left for backward-compatibility purposes only. It is not very stable, and counterintuitively uses 0-based months and days, so "January 4th, 20...
[ DEPRECATED ] Use constructor H2OFrame () instead.
def from_python(python_obj, destination_frame=None, header=0, separator=",", column_names=None, column_types=None, na_strings=None): """[DEPRECATED] Use constructor ``H2OFrame()`` instead.""" return H2OFrame(python_obj, destination_frame, header, separator, column_names, column_types...
Parse code from a string of text.
def parse_text(text): """Parse code from a string of text.""" assert isinstance(text, _str_type), "`text` parameter should be a string, got %r" % type(text) gen = iter(text.splitlines(True)) # True = keep newlines readline = gen.next if hasattr(gen, "next") else gen.__next__ return Code(_tokenize(r...
Parse the provided file and return Code object.
def parse_file(filename): """Parse the provided file, and return Code object.""" assert isinstance(filename, _str_type), "`filename` parameter should be a string, got %r" % type(filename) with open(filename, "rt", encoding="utf-8") as f: return Code(_tokenize(f.readline))
Parse any object accessible through a readline interface into a list of: class: Token s.
def _tokenize(readline): """ Parse any object accessible through a readline interface into a list of :class:`Token`s. This function is very similar to :func:`tokenize.generate_tokens`, with few differences. First, the returned list is a list of :class:`Token` objects instead of 5-tuples. This may be sl...
Move the token by drow rows and dcol columns.
def move(self, drow, dcol=0): """Move the token by `drow` rows and `dcol` columns.""" self._start_row += drow self._start_col += dcol self._end_row += drow self._end_col += dcol
Convert the parsed representation back into the source code.
def unparse(self): """Convert the parsed representation back into the source code.""" ut = Untokenizer(start_row=self._tokens[0].start_row) self._unparse(ut) return ut.result()
First stage of parsing the code ( stored as a raw stream of tokens ).
def _parse1(self): """ First stage of parsing the code (stored as a raw stream of tokens). This method will do the initial pass of the ``self._tokens`` list of tokens, and mark different section as belonging to one of the categories: comment, whitespace, docstring, import, code, decorat...
Second stage of parsing: convert fragments into the list of code objects.
def _parse2(self, fragments): """ Second stage of parsing: convert ``fragments`` into the list of code objects. This method in fact does more than simple conversion of fragments into objects. It also attempts to group certain fragments into one, if they in fact seem like a single piece....
Get the sizes of each cluster.
def size(self, train=False, valid=False, xval=False): """ Get the sizes of each cluster. 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 where the keys are "train", "valid", and "xval...
The centers for the KMeans model.
def centers(self): """The centers for the KMeans model.""" o = self._model_json["output"] cvals = o["centers"].cell_values centers = [list(cval[1:]) for cval in cvals] return centers
The standardized centers for the kmeans model.
def centers_std(self): """The standardized centers for the kmeans model.""" o = self._model_json["output"] cvals = o["centers_std"].cell_values centers_std = [list(cval[1:]) for cval in cvals] centers_std = [list(x) for x in zip(*centers_std)] return centers_std
Connect to an existing H2O server remote or local.
def connect(server=None, url=None, ip=None, port=None, https=None, verify_ssl_certificates=None, auth=None, proxy=None, cookies=None, verbose=True, config=None): """ Connect to an existing H2O server, remote or local. There are two ways to connect to a server: either pass a `server` parameter c...
Perform a REST API request to a previously connected server.
def api(endpoint, data=None, json=None, filename=None, save_to=None): """ Perform a REST API request to a previously connected server. This function is mostly for internal purposes, but may occasionally be useful for direct access to the backend H2O server. It has same parameters as :meth:`H2OConnectio...
Used to verify that h2o - python module and the H2O server are compatible with each other.
def version_check(): """Used to verify that h2o-python module and the H2O server are compatible with each other.""" from .__init__ import __version__ as ver_pkg ci = h2oconn.cluster if not ci: raise H2OConnectionError("Connection not initialized. Did you run h2o.connect()?") ver_h2o = ci.ver...
Attempt to connect to a local server or if not successful start a new server and connect to it.
def init(url=None, ip=None, port=None, name=None, https=None, insecure=None, username=None, password=None, cookies=None, proxy=None, start_h2o=True, nthreads=-1, ice_root=None, log_dir=None, log_level=None, enable_assertions=True, max_mem_size=None, min_mem_size=None, strict_version_check=None, ignore...
Import a single file or collection of files.
def lazy_import(path, pattern=None): """ Import a single file or collection of files. :param path: A path to a data file (remote or local). :param pattern: Character string containing a regular expression to match file(s) in the folder. :returns: either a :class:`H2OFrame` with the content of the p...
Upload a dataset from the provided local path to the H2O cluster.
def upload_file(path, destination_frame=None, header=0, sep=None, col_names=None, col_types=None, na_strings=None, skipped_columns=None): """ Upload a dataset from the provided local path to the H2O cluster. Does a single-threaded push to H2O. Also see :meth:`import_file`. :param path:...
Import a dataset that is already on the cluster.
def import_file(path=None, destination_frame=None, parse=True, header=0, sep=None, col_names=None, col_types=None, na_strings=None, pattern=None, skipped_columns=None, custom_non_data_line_markers = None): """ Import a dataset that is already on the cluster. The path to the data must be a v...
Import Hive table to H2OFrame in memory.
def import_hive_table(database=None, table=None, partitions=None, allow_multi_format=False): """ Import Hive table to H2OFrame in memory. Make sure to start H2O with Hive on classpath. Uses hive-site.xml on classpath to connect to Hive. :param database: Name of Hive database (default database will be ...
Import SQL table to H2OFrame in memory.
def import_sql_table(connection_url, table, username, password, columns=None, optimize=True, fetch_mode=None): """ Import SQL table to H2OFrame in memory. Assumes that the SQL table is not being updated and is stable. Runs multiple SELECT SQL queries concurrently for parallel ingestion. Be sure to ...
Import the SQL table that is the result of the specified SQL query to H2OFrame in memory.
def import_sql_select(connection_url, select_query, username, password, optimize=True, use_temp_table=None, temp_table_name=None, fetch_mode=None): """ Import the SQL table that is the result of the specified SQL query to H2OFrame in memory. Creates a temporary SQL table from the spe...
Retrieve H2O s best guess as to what the structure of the data file is.
def parse_setup(raw_frames, destination_frame=None, header=0, separator=None, column_names=None, column_types=None, na_strings=None, skipped_columns=None, custom_non_data_line_markers=None): """ Retrieve H2O's best guess as to what the structure of the data file is. During parse setup, the ...
Parse dataset using the parse setup structure.
def parse_raw(setup, id=None, first_line_is_header=0): """ Parse dataset using the parse setup structure. :param setup: Result of ``h2o.parse_setup()`` :param id: an id for the frame. :param first_line_is_header: -1, 0, 1 if the first line is to be used as the header :returns: an :class:`H2OFr...
( internal ) Assign new id to the frame.
def assign(data, xid): """ (internal) Assign new id to the frame. :param data: an H2OFrame whose id should be changed :param xid: new id for the frame. :returns: the passed frame. """ assert_is_type(data, H2OFrame) assert_is_type(xid, str) assert_satisfies(xid, xid != data.frame_id)...
Create a deep clone of the frame data.
def deep_copy(data, xid): """ Create a deep clone of the frame ``data``. :param data: an H2OFrame to be cloned :param xid: (internal) id to be assigned to the new frame. :returns: new :class:`H2OFrame` which is the clone of the passed frame. """ assert_is_type(data, H2OFrame) assert_is_...
Load a model from the server.
def get_model(model_id): """ Load a model from the server. :param model_id: The model identification in H2O :returns: Model object, a subclass of H2OEstimator """ assert_is_type(model_id, str) model_json = api("GET /3/Models/%s" % model_id)["models"][0] algo = model_json["algo"] if...
Return the specified grid.
def get_grid(grid_id): """ Return the specified grid. :param grid_id: The grid identification in h2o :returns: an :class:`H2OGridSearch` instance. """ assert_is_type(grid_id, str) grid_json = api("GET /99/Grids/%s" % grid_id) models = [get_model(key["name"]) for key in grid_json["model...
Obtain a handle to the frame in H2O with the frame_id key.
def get_frame(frame_id, **kwargs): """ Obtain a handle to the frame in H2O with the frame_id key. :param str frame_id: id of the frame to retrieve. :returns: an :class:`H2OFrame` object """ assert_is_type(frame_id, str) return H2OFrame.get_frame(frame_id, **kwargs)
Remove object ( s ) from H2O.
def remove(x): """ Remove object(s) from H2O. :param x: H2OFrame, H2OEstimator, or string, or a list of those things: the object(s) or unique id(s) pointing to the object(s) to be removed. """ item_type = U(str, H2OFrame, H2OEstimator) assert_is_type(x, item_type, [item_type]) if no...
Download the POJO for this model to the directory specified by path ; if path is then dump to screen.
def download_pojo(model, path="", get_jar=True, jar_name=""): """ Download the POJO for this model to the directory specified by path; if path is "", then dump to screen. :param model: the model whose scoring POJO should be retrieved. :param path: an absolute path to the directory where POJO should be ...
Download an H2O data set to a CSV file on the local disk.
def download_csv(data, filename): """ Download an H2O data set to a CSV file on the local disk. Warning: Files located on the H2O server may be very large! Make sure you have enough hard drive space to accommodate the entire file. :param data: an H2OFrame object to be downloaded. :param filena...
Download H2O log files to disk.
def download_all_logs(dirname=".", filename=None): """ Download H2O log files to disk. :param dirname: a character string indicating the directory that the log file should be saved in. :param filename: a string indicating the name that the CSV file should be. Note that the saved format is .zip, so the ...
Save an H2O Model object to disk. ( Note that ensemble binary models can now be saved using this method. )
def save_model(model, path="", force=False): """ Save an H2O Model object to disk. (Note that ensemble binary models can now be saved using this method.) :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 di...
Load a saved H2O model from disk. ( Note that ensemble binary models can now be loaded using this method. )
def load_model(path): """ Load a saved H2O model from disk. (Note that ensemble binary models can now be loaded using this method.) :param path: the full path of the H2O Model to be imported. :returns: an :class:`H2OEstimator` object :examples: >>> path = h2o.save_model(my_model, dir=my_p...
Export a given H2OFrame to a path on the machine this python session is currently connected to.
def export_file(frame, path, force=False, parts=1): """ Export a given H2OFrame to a path on the machine this python session is currently connected to. :param frame: the Frame to save to disk. :param path: the path to the save point on disk. :param force: if True, overwrite any preexisting file wit...
Create a new frame with random data.
def create_frame(frame_id=None, rows=10000, cols=10, randomize=True, real_fraction=None, categorical_fraction=None, integer_fraction=None, binary_fraction=None, time_fraction=None, string_fraction=None, value=0, real_range=100, factors=100, integer_range=100, ...
Categorical Interaction Feature Creation in H2O.
def interaction(data, factors, pairwise, max_factors, min_occurrence, destination_frame=None): """ Categorical Interaction Feature Creation in H2O. Creates a frame in H2O with n-th order interaction features between categorical columns, as specified by the user. :param data: the H2OFrame that hold...
Convert an H2O data object into a python - specific object.
def as_list(data, use_pandas=True, header=True): """ Convert an H2O data object into a python-specific object. WARNING! This will pull all data local! If Pandas is available (and use_pandas is True), then pandas will be used to parse the data frame. Otherwise, a list-of-lists populated by characte...
H2O built - in demo facility.
def demo(funcname, interactive=True, echo=True, test=False): """ H2O built-in demo facility. :param funcname: A string that identifies the h2o python function to demonstrate. :param interactive: If True, the user will be prompted to continue the demonstration after every segment. :param echo: If Tr...
Imports a data file within the h2o_data folder.
def load_dataset(relative_path): """Imports a data file within the 'h2o_data' folder.""" assert_is_type(relative_path, str) h2o_dir = os.path.split(__file__)[0] for possible_file in [os.path.join(h2o_dir, relative_path), os.path.join(h2o_dir, "h2o_data", relative_path), ...
Create Model Metrics from predicted and actual values in H2O.
def make_metrics(predicted, actual, domain=None, distribution=None): """ Create Model Metrics from predicted and actual values in H2O. :param H2OFrame predicted: an H2OFrame containing predictions. :param H2OFrame actuals: an H2OFrame containing actual values. :param domain: list of response factor...
Upload given file into DKV and save it under give key as raw object.
def _put_key(file_path, dest_key=None, overwrite=True): """ Upload given file into DKV and save it under give key as raw object. :param dest_key: name of destination key in DKV :param file_path: path to file to upload :return: key name if object was uploaded successfully """ ret = api("PO...
Upload given metrics function into H2O cluster.
def upload_custom_metric(func, func_file="metrics.py", func_name=None, class_name=None, source_provider=None): """ Upload given metrics function into H2O cluster. The metrics can have different representation: - class: needs to implement map(pred, act, weight, offset, model), reduce(l, r) and metric(...
Main program.
def main(argv): """ Main program. @return: none """ global g_log_base_dir global g_airline_java global g_milsongs_java global g_airline_python global g_milsongs_python if len(argv) < 2: print "python grabGLRMrunLogs logsBaseDirectory\n" sys.exit(1) else: #...
Main program.
def main(argv): """ Main program. @return: none """ global g_script_name global g_tmp_dir g_script_name = os.path.basename(argv[0]) # Override any defaults with the user's choices. parse_args(argv) # Create tmp dir and clean up on exit with a callback. g_tmp_dir = tempfil...
Check that the provided frame id is valid in Rapids language.
def check_frame_id(frame_id): """Check that the provided frame id is valid in Rapids language.""" if frame_id is None: return if frame_id.strip() == "": raise H2OValueError("Frame id cannot be an empty string: %r" % frame_id) for i, ch in enumerate(frame_id): # '$' character has ...
Search for a relative path and turn it into an absolute path. This is handy when hunting for data files to be passed into h2o and used by import file. Note: This function is for unit testing purposes only.
def _locate(path): """Search for a relative path and turn it into an absolute path. This is handy when hunting for data files to be passed into h2o and used by import file. Note: This function is for unit testing purposes only. Parameters ---------- path : str Path to search for :ret...
Convert given number of bytes into a human readable representation i. e. add prefix such as kb Mb Gb etc. The size argument must be a non - negative integer.
def get_human_readable_bytes(size): """ Convert given number of bytes into a human readable representation, i.e. add prefix such as kb, Mb, Gb, etc. The `size` argument must be a non-negative integer. :param size: integer representing byte size of something :return: string representation of the siz...
Convert given duration in milliseconds into a human - readable representation i. e. hours minutes seconds etc. More specifically the returned string may look like following: 1 day 3 hours 12 mins 3 days 0 hours 0 mins 8 hours 12 mins 34 mins 02 secs 13 secs 541 ms In particular the following rules are applied: * millis...
def get_human_readable_time(time_ms): """ Convert given duration in milliseconds into a human-readable representation, i.e. hours, minutes, seconds, etc. More specifically, the returned string may look like following: 1 day 3 hours 12 mins 3 days 0 hours 0 mins 8 hours 12 mins ...
This function exists here ONLY because Sphinx. ext. autodoc gets into a bad state when seeing the print () function. When in that state autodoc doesn t display any errors or warnings but instead completely ignores the bysource member - order option.
def print2(msg, flush=False, end="\n"): """ This function exists here ONLY because Sphinx.ext.autodoc gets into a bad state when seeing the print() function. When in that state, autodoc doesn't display any errors or warnings, but instead completely ignores the "bysource" member-order option. """ ...
Return a canonical version of slice s.
def normalize_slice(s, total): """ Return a "canonical" version of slice ``s``. :param slice s: the original slice expression :param total int: total number of elements in the collection sliced by ``s`` :return slice: a slice equivalent to ``s`` but not containing any negative indices or Nones. ...
Return True if slice s in normalized form.
def slice_is_normalized(s): """Return True if slice ``s`` in "normalized" form.""" return (s.start is not None and s.stop is not None and s.step is not None and s.start <= s.stop)
MOJO scoring function to take a Pandas frame and use MOJO model as zip file to score.
def mojo_predict_pandas(dataframe, mojo_zip_path, genmodel_jar_path=None, classpath=None, java_options=None, verbose=False): """ MOJO scoring function to take a Pandas frame and use MOJO model as zip file to score. :param dataframe: Pandas frame to score. :param mojo_zip_path: Path to MOJO zip download...
MOJO scoring function to take a CSV file and use MOJO model as zip file to score.
def mojo_predict_csv(input_csv_path, mojo_zip_path, output_csv_path=None, genmodel_jar_path=None, classpath=None, java_options=None, verbose=False): """ MOJO scoring function to take a CSV file and use MOJO model as zip file to score. :param input_csv_path: Path to input CSV file. :param mojo_zip_path:...
The decorator to mark deprecated functions.
def deprecated(message): """The decorator to mark deprecated functions.""" from traceback import extract_stack assert message, "`message` argument in @deprecated is required." def deprecated_decorator(fun): def decorator_invisible(*args, **kwargs): stack = extract_stack() ...
Wait until grid finishes computing.
def join(self): """Wait until grid finishes computing.""" self._future = False self._job.poll() self._job = None
Train the model synchronously ( i. e. do not return until the model finishes training ).
def train(self, x=None, y=None, training_frame=None, offset_column=None, fold_column=None, weights_column=None, validation_frame=None, **params): """ Train the model synchronously (i.e. do not return until the model finishes training). To train asynchronously call :meth:`start`. ...
( internal )
def build_model(self, algo_params): """(internal)""" if algo_params["training_frame"] is None: raise ValueError("Missing training_frame") x = algo_params.pop("x") y = algo_params.pop("y", None) training_frame = algo_params.pop("training_frame") validation_frame = algo_par...
Predict on a dataset.
def predict(self, test_data): """ Predict on a dataset. :param H2OFrame test_data: Data to be predicted on. :returns: H2OFrame filled with predictions. """ return {model.model_id: model.predict(test_data) for model in self.models}
Return a Model object.
def get_xval_models(self, key=None): """ Return a Model object. :param str key: If None, return all cross-validated models; otherwise return the model specified by the key. :returns: A model or a list of models. """ return {model.model_id: model.get_xval_mode...
Obtain a hidden layer s details on a dataset.
def deepfeatures(self, test_data, layer): """ Obtain a hidden layer's details on a dataset. :param test_data: Data to create a feature space on. :param int layer: Index of the hidden layer. :returns: A dictionary of hidden layer details for each model. """ return...
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 test_data: Data set for which model metrics shall be computed against. All three of train, valid and xval arguments are ignored if test_d...
Print a detailed summary of the explored models.
def summary(self, header=True): """Print a detailed summary of the explored models.""" table = [] for model in self.models: model_summary = model._model_json["output"]["model_summary"] r_values = list(model_summary.cell_values[0]) r_values[0] = model.model_id ...
Print models sorted by metric.
def show(self): """Print models sorted by metric.""" hyper_combos = itertools.product(*list(self.hyper_params.values())) if not self.models: c_values = [[idx + 1, list(val)] for idx, val in enumerate(hyper_combos)] print(H2OTwoDimTable( col_header=['Model'...
Pretty print the variable importances or return them in a list/ pandas DataFrame.
def varimp(self, use_pandas=False): """ Pretty print the variable importances, or return them in a list/pandas DataFrame. :param bool use_pandas: If True, then the variable importances will be returned as a pandas data frame. :returns: A dictionary of lists or Pandas DataFrame instance...
Pretty print the coefficents table ( includes normalized coefficients ).
def pprint_coef(self): """Pretty print the coefficents table (includes normalized coefficients).""" for i, model in enumerate(self.models): print('Model', i) model.pprint_coef() print()
Get the hyperparameters of a model explored by grid search.
def get_hyperparams(self, id, display=True): """ Get the hyperparameters of a model explored by grid search. :param str id: The model id of the model with hyperparameters of interest. :param bool display: Flag to indicate whether to display the hyperparameter names. :returns: A...
Derived and returned the model parameters used to train the particular grid search model.
def get_hyperparams_dict(self, id, display=True): """ Derived and returned the model parameters used to train the particular grid search model. :param str id: The model id of the model with hyperparameters of interest. :param bool display: Flag to indicate whether to display the hyperpa...
Retrieve an H2OGridSearch instance.
def get_grid(self, sort_by=None, decreasing=None): """ Retrieve an H2OGridSearch instance. Optionally specify a metric by which to sort models and a sort order. Note that if neither cross-validation nor a validation frame is used in the grid search, then the training metrics wil...