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_hyperparams(model_id, display=False) for model_id in c_values[0]])
if not increasing:
for col in c_values: col.reverse()
if metric[-2] == '(': metric = metric[:-2]
return H2OTwoDimTable(
col_header=['Model Id', 'Hyperparameters: [' + ', '.join(list(self.hyper_params.keys())) + ']', metric],
table_header='Grid Search Results for ' + self.model.__class__.__name__,
cell_values=[list(x) for x in zip(*c_values)])
|
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. Otherwise, return
the mean square error.
:returns: the reconstruction error.
"""
return {model.model_id: model.anomaly(test_data, per_feature) for model in self.models}
|
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 where
the keys are "train", "valid", and "xval".
:param List thresholds: If None, then the thresholds in this set of metrics will be used.
:param bool train: If True, return the F1 value for the training data.
:param bool valid: If True, return the F1 value for the validation data.
:param bool xval: If True, return the F1 value for each of the cross-validated splits.
:returns: Dictionary of model keys to F1 values
"""
return {model.model_id: model.F1(thresholds, train, valid, xval) for model in
self.models}
|
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 dictionary of metrics where the keys are "train",
"valid", and "xval".
:param metrics: A list of metrics or a single metric among ``"min_per_class_accuracy"``, ``"absolute_mcc"``,
``"tnr"``, ``"fnr"``, ``"fpr"``, ``"tpr"``, ``"precision"``, ``"accuracy"``, ``"f0point5"``, ``"f2"``,
``"f1"``.
:param thresholds: thresholds parameter must be a list (i.e. [0.01, 0.5, 0.99]). If None, then the thresholds
in this set of metrics will be used.
:param bool train: If train is True, then return the confusion matrix value for the training data.
:param bool valid: If valid is True, then return the confusion matrix value for the validation data.
:param bool xval: If xval is True, then return the confusion matrix value for the cross validation data.
:returns: The confusion matrix for this binomial model.
"""
return {model.model_id: model.confusion_matrix(metrics, thresholds, train, valid, xval) for model in
self.models}
|
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, then return a dictionary of metrics where the keys are "train",
"valid", and "xval".
:param float threshold: The threshold value to search for.
:param bool train: If train is True, then return the idx_by_threshold for the training data.
:param bool valid: If valid is True, then return the idx_by_threshold for the validation data.
:param bool xval: If xval is True, then return the idx_by_threshold for the cross validation data.
:returns: The idx_by_threshold for this binomial model.
"""
return {model.model_id: model.find_idx_by_threshold(threshold, train, valid, xval) for model in self.models}
|
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 = model["importance"].cell_values
header = model["importance"].col_header
if use_pandas and can_use_pandas():
import pandas
return pandas.DataFrame(vals, columns=header)
else:
return vals
else:
print("Warning: This model doesn't have importances of components.")
|
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 model-building
should be reversed on the projected archetypes.
:returns: model archetypes projected back into the original training data's feature space.
"""
if test_data is None or test_data.nrow == 0: raise ValueError("Must specify test data")
j = h2o.api("POST /3/Predictions/models/%s/frames/%s" % (self.model_id, test_data.frame_id),
data={"project_archetypes": True, "reverse_transform": reverse_transform})
return h2o.get_frame(j["model_metrics"][0]["predictions"]["frame_id"]["name"])
|
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")
if kwargs:
raise ValueError("Unknown arguments %s to screeplot()" % ", ".join(kwargs.keys()))
try:
import matplotlib
if is_server: matplotlib.use('Agg', warn=False)
import matplotlib.pyplot as plt
except ImportError:
print("matplotlib is required for this function!")
return
variances = [s ** 2 for s in self._model_json['output']['importance'].cell_values[0][1:]]
plt.xlabel('Components')
plt.ylabel('Variances')
plt.title('Scree Plot')
plt.xticks(list(range(1, len(variances) + 1)))
if type == "barplot":
plt.bar(list(range(1, len(variances) + 1)), variances)
elif type == "lines":
plt.plot(list(range(1, len(variances) + 1)), variances, 'b--')
if not is_server: plt.show()
|
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"
"_exclude_fields" => "_excludeFields" (retain initial/trailing underscores)
"__http_status__" => "__httpStatus__"
:param name: name to be converted
"""
parts = name.split("_")
i = 0
while parts[i] == "":
parts[i] = "_"
i += 1
parts[i] = parts[i].lower()
for j in range(i + 1, len(parts)):
parts[j] = parts[j].capitalize()
i = len(parts) - 1
while parts[i] == "":
parts[i] = "_"
i -= 1
return "".join(parts)
|
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 specified amount of indentation added.
"""
text2 = textwrap.dedent(text)
if ind == 0:
return text2
indent_str = " " * ind
return "\n".join(indent_str + line for line in text2.split("\n"))
|
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
has_inherited = False
for field in schema["fields"]:
if field["name"] == "__meta": continue
if field["is_inherited"]:
has_inherited = True
continue
if field["type"].startswith("Map"): has_map = True
if field["name"] == "can_build": is_model_builder = True
fields = []
for field in schema["fields"]:
if field["name"] == "__meta": continue
java_type = translate_type(field["type"], field["schema_name"])
java_value = get_java_value(field)
# hackery: we flatten the parameters up into the ModelBuilder schema, rather than nesting them in the
# parameters schema class...
if False and is_model_builder and field["name"] == "parameters":
fields.append(("parameters", "null", "ModelParameterSchemaV3[]", field["help"], field["is_inherited"]))
else:
fields.append((field["name"], java_value, java_type, field["help"], field["is_inherited"]))
class_decl = class_name
if "generics" in schema:
class_decl += "<" + ", ".join("%s extends %s" % (t, long_type) for t, long_type in schema["generics"]) + ">"
super_decl = superclass
if "super_generics" in schema:
super_decl += "<" + ", ".join(schema["super_generics"]) + ">"
yield "/*"
yield " * This file is auto-generated by h2o-3/h2o-bindings/bin/gen_java.py"
yield " * Copyright 2016 H2O.ai; Apache License Version 2.0 (see LICENSE for details)"
yield " */"
yield "package water.bindings.pojos;"
yield ""
yield "import com.google.gson.Gson;"
yield "import com.google.gson.annotations.*;"
yield "import java.util.Map;" if has_map else None
yield ""
yield ""
yield "public class %s extends %s {" % (class_decl, super_decl) if super_decl != "Object" else None
yield "public class %s {" % (class_decl) if super_decl == "Object" else None
yield ""
for name, value, ftype, fhelp, inherited in fields:
if inherited: continue
ccname = translate_name(name)
yield " /**"
yield bi.wrap(fhelp, indent=" * ")
yield " */"
yield " @SerializedName(\"%s\")" % name if name != ccname else None
yield " public %s %s;" % (ftype, ccname)
yield ""
if has_inherited:
yield ""
yield " /*" + ("-" * 114)
yield " //" + (" " * 50) + "INHERITED"
yield " //" + ("-" * 114)
yield ""
for name, value, ftype, fhelp, inherited in fields:
if not inherited: continue
yield bi.wrap(fhelp, " // ")
yield " public %s %s;" % (ftype, translate_name(name))
yield ""
yield " */"
yield ""
yield " /**"
yield " * Public constructor"
yield " */"
yield " public %s() {" % class_name
for name, value, _, _, _ in fields:
if name == "parameters": continue
if value == "null": continue
yield " %s = %s;" % (translate_name(name), value)
yield " }"
yield ""
yield " /**"
yield " * Return the contents of this object as a JSON String."
yield " */"
yield " @Override"
yield " public String toString() {"
yield " return new Gson().toJson(this);"
yield " }"
yield ""
yield "}"
|
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 the class
:param endpoints: list of endpoints served by this class
"""
# Replace path vars like (?<schemaname>.*) with {schemaname} for Retrofit's annotation
var_pattern = re.compile(r"\{(\w+)\}")
helper_class = []
found_key_array_parameter = False
yield "/*"
yield " * This file is auto-generated by h2o-3/h2o-bindings/bin/gen_java.py"
yield " * Copyright 2016 H2O.ai; Apache License Version 2.0 (see LICENSE for details)"
yield " */"
yield "package water.bindings.proxies.retrofit;"
yield ""
yield "import water.bindings.pojos.*;"
yield "import retrofit2.*;"
yield "import retrofit2.http.*;"
yield "import java.util.Map;" if classname == "Grid" or classname == "ModelBuilders" else None
yield ""
yield "public interface " + classname + " {"
yield ""
for e in endpoints:
method = e["handler_method"]
# should we always use e.api_name ?
if method == "exec":
method = e["api_name"]
param_strs = []
required_param_strs = []
for field in e["input_params"]:
fname = field["name"]
ftype = "Path" if field["is_path_param"] else "Field"
ptype = translate_type(field["type"], field["schema_name"])
if ptype.endswith("KeyV3") or ptype == "ColSpecifierV3": ptype = "String"
if ptype.endswith("KeyV3[]"): ptype = "String[]"
param_str = "@{ftype}(\"{fname}\") {ptype} {fname}".format(**locals())
param_strs.append(param_str)
if field["required"]:
required_param_strs.append(param_str)
if len(param_strs) == len(required_param_strs): required_param_strs = None
yield u" /** "
yield bi.wrap(e["summary"], indent=" * ")
for field in e["input_params"]:
s = " * @param %s " % field["name"]
yield s + bi.wrap(field["help"], indent=" *" + " " * (len(s) - 4), indent_first=False)
yield u" */"
# Create 2 versions of each call: first with all input parameters present, and then only with required params
for params in [param_strs, required_param_strs]:
if params is None: continue
yield u" @FormUrlEncoded" if e["http_method"] == "POST" else None
yield u" @{method}(\"{path}\")".format(method=e["http_method"], path=e["url_pattern"])
if len(params) <= 1:
args = params[0] if params else ""
yield " Call<{schema}> {method}({args});".format(schema=e["output_schema"], method=method, args=args)
else:
yield " Call<{schema}> {method}(".format(schema=e["output_schema"], method=method)
for arg in params:
yield " " + arg + ("" if arg == params[-1] else ",")
yield " );"
yield ""
# Make special static Helper class for Grid and ModelBuilders.
if "algo" in e:
# We make two train_ and validate_ methods. One (built here) takes the parameters schema, the other
# (built above) takes each parameter.
helper_class.append(" /**")
helper_class.append(bi.wrap(e["summary"], indent=" * "))
helper_class.append(" */")
helper_class.append(" public static Call<{oschema}> {method}({outer_class} z, {ischema} p) {{"
.format(ischema=e["input_schema"], oschema=e["output_schema"], method=method,
outer_class=classname))
helper_class.append(" return z.{method}(".format(method=method))
for field in e["input_params"]:
ptype = translate_type(field["type"], field["schema_name"])
pname = translate_name(field["name"])
if ptype.endswith("KeyV3"):
s = "(p.{parm} == null? null : p.{parm}.name)".format(parm=pname)
elif ptype.endswith("KeyV3[]"):
found_key_array_parameter = True
s = "(p.{parm} == null? null : keyArrayToStringArray(p.{parm}))".format(parm=pname)
elif ptype.startswith("ColSpecifier"):
s = "(p.{parm} == null? null : p.{parm}.columnName)".format(parm=pname)
else:
s = "p." + pname
if field != e["input_params"][-1]:
s += ","
helper_class.append(" " + s)
helper_class.append(" );")
helper_class.append(" }")
helper_class.append("")
if helper_class:
yield ""
yield " @SuppressWarnings(\"unused\")"
yield " class Helper {"
for line in helper_class:
yield line
if found_key_array_parameter:
yield " /**"
yield " * Return an array of Strings for an array of keys."
yield " */"
yield " public static String[] keyArrayToStringArray(KeyV3[] keys) {"
yield " if (keys == null) return null;"
yield " String[] ids = new String[keys.length];"
yield " int i = 0;"
yield " for (KeyV3 key : keys) ids[i++] = key.name;"
yield " return ids;"
yield " }"
yield " }"
yield ""
yield "}"
|
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_log_path)
d.parse()
d.emit_header()
for i in range(0, g_num_rows):
d.emit_one_row()
|
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.:", s)
if (match_groups is not None):
dataset_name = match_groups.group(1)
if (self.dataset_name is not None):
print("ERROR: Too many datasets found on file {} line {}".format(self.parse_log_path, line_num))
sys.exit(1)
self.dataset_name = dataset_name
num_rows = int(match_groups.group(2))
self.num_rows = num_rows
s = f.readline()
continue
# Check for numeric column.
match_groups = re.search(r"INFO WATER:" +
r"\s*C(\d+):" +
r"\s*numeric" +
r"\s*min\((\S*)\)" +
r"\s*max\((\S*).\)" +
r"\s*(na\((\S+)\))?" +
r"\s*(constant)?",
s)
if (match_groups is not None):
col_num = int(match_groups.group(1))
min_val = float(match_groups.group(2))
max_val = float(match_groups.group(3))
# four = match_groups.group(4)
na_count = match_groups.group(5)
if (na_count is None):
na_count = 0
else:
na_count = int(na_count)
constant_str = match_groups.group(6)
is_constant = constant_str is not None
if (is_constant):
if (min_val != max_val):
print("ERROR: is_constant mismatch on file {} line {}".format(self.parse_log_path, line_num))
sys.exit(1)
na_fraction = float(na_count) / float(self.num_rows)
is_min_integer = float(int(min_val)) == float(min_val)
is_max_integer = float(int(min_val)) == float(min_val)
is_integer = is_min_integer and is_max_integer
c = RealColumn(col_num, "C" + str(col_num), min_val, max_val, na_fraction, is_integer)
self.add_col(c)
s = f.readline()
continue
# Check for categorical column.
match_groups = re.search(r"INFO WATER:" +
r"\s*C(\d+):" +
r"\s*categorical" +
r"\s*min\((\S*)\)" +
r"\s*max\((\S*).\)" +
r"\s*(na\((\S+)\))?" +
r"\s*(constant)?" +
r"\s*cardinality\((\d+)\)",
s)
if (match_groups is not None):
col_num = int(match_groups.group(1))
min_val = float(match_groups.group(2))
max_val = float(match_groups.group(3))
# four = match_groups.group(4)
na_count = match_groups.group(5)
if (na_count is None):
na_count = 0
else:
na_count = int(na_count)
constant_str = match_groups.group(6)
is_constant = constant_str is not None
if (is_constant):
if (min_val != max_val):
print("ERROR: is_constant mismatch on file {} line {}".format(self.parse_log_path, line_num))
sys.exit(1)
num_levels = int(match_groups.group(7))
if (is_constant):
if (num_levels != 1):
print("ERROR: num_levels mismatch on file {} line {}".format(self.parse_log_path, line_num))
sys.exit(1)
na_fraction = float(na_count) / float(self.num_rows)
c = CategoricalColumn(col_num, "C" + str(col_num), num_levels, na_fraction)
self.add_col(c)
s = f.readline()
continue
print("ERROR: Unrecognized regexp pattern on file {} line {}".format(self.parse_log_path, line_num))
sys.exit(1)
|
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.
Otherwise, return the mean square error.
:returns: the reconstruction error.
"""
if test_data is None or test_data.nrow == 0: raise ValueError("Must specify test data")
j = h2o.api("POST /3/Predictions/models/%s/frames/%s" % (self.model_id, test_data.frame_id),
data={"reconstruction_error": True, "reconstruction_error_per_feature": per_feature})
return h2o.get_frame(j["model_metrics"][0]["predictions"]["frame_id"]["name"])
|
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_objective
global g_stepsize
global g_history
if os.path.isfile(javaLogText):
run_result = dict()
run_result["total time (ms)"] = []
run_result["initialXY (ms)"] = []
run_result["regularize Y (ms)"] = []
run_result["regularize X and objective (ms)"] = []
run_result["update X (ms)"] = []
run_result["update Y (ms)"] = []
run_result["objective (ms)"] = []
run_result["step size (ms)"] = []
run_result["update history (ms)"] = []
total_run_time = -1
val = 0.0
with open(javaLogText, 'r') as thefile: # go into tempfile and grab test run info
for each_line in thefile:
temp_string = each_line.split()
if len(temp_string) > 0:
val = temp_string[-1].replace('\\','')
if g_initialXY in each_line: # start of a new file
if total_run_time > 0: # update total run time
run_result["total time (ms)"].append(total_run_time)
total_run_time = 0.0
else:
total_run_time = 0.0
run_result["initialXY (ms)"].append(float(val))
total_run_time = total_run_time+float(val)
if g_reguarlize_Y in each_line:
run_result["regularize Y (ms)"].append(float(val))
total_run_time = total_run_time+float(val)
if g_regularize_X_objective in each_line:
run_result["regularize X and objective (ms)"].append(float(val))
total_run_time = total_run_time+float(val)
if g_updateX in each_line:
run_result["update X (ms)"].append(float(val))
total_run_time = total_run_time+float(val)
if g_updateY in each_line:
run_result["update Y (ms)"].append(float(val))
total_run_time = total_run_time+float(val)
if g_objective in each_line:
run_result["objective (ms)"].append(float(val))
total_run_time = total_run_time+float(val)
if g_stepsize in each_line:
run_result["step size (ms)"].append(float(val))
total_run_time = total_run_time+float(val)
if g_history in each_line:
run_result["update history (ms)"].append(float(val))
total_run_time = total_run_time+float(val)
run_result["total time (ms)"].append(total_run_time) # save the last one
print("Run result summary: \n {0}".format(run_result))
else:
print("Cannot find your java log file. Nothing is done.\n")
|
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 python extractGLRMRuntimeJavaLog.py javatextlog.\n")
sys.exit(1)
else: # we may be in business
javaLogText = argv[1] # filename while java log is stored
print("your java text is {0}".format(javaLogText))
extractRunInto(javaLogText)
|
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`' or 'name'"""
m = self._name_rgx.match(text)
if m:
g = m.groups()
if g[1] is None:
return g[3], None
else:
return g[2], g[1]
raise ValueError("%s is not a item name" % text)
def push_item(name, rest):
if not name:
return
name, role = parse_item_name(name)
items.append((name, list(rest), role))
del rest[:]
current_func = None
rest = []
for line in content:
if not line.strip(): continue
m = self._name_rgx.match(line)
if m and line[m.end():].strip().startswith(':'):
push_item(current_func, rest)
current_func, line = line[:m.end()], line[m.end():]
rest = [line.split(':', 1)[1].strip()]
if not rest[0]:
rest = []
elif not line.startswith(' '):
push_item(current_func, rest)
current_func = None
if ',' in line:
for func in line.split(','):
push_item(func, [])
elif line.strip():
current_func = line
elif current_func is not None:
rest.append(line.strip())
push_item(current_func, rest)
return items
|
.. 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['default'] = strip_each_in(section[1].split(','))[0]
for line in content:
line = line.split(':')
if len(line) > 2:
out[line[1]] = strip_each_in(line[2].split(','))
return out
|
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 unknown property name.
|
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 class filled with values from given dictionary
:raises H2OValueError: if input config contains unknown property name.
"""
for k,v in config.items():
if k in H2OConnectionConf.allowed_properties:
setattr(self, k, v)
else:
raise H2OValueError(message="Unsupported name of property: %s!" % k, var_name="config")
|
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 actually does is it attempts to connect to the
specified server, and checks that the server is healthy and responds to REST API requests. If the H2O server
cannot be reached, an :class:`H2OConnectionError` will be raised. On success this method returns a new
:class:`H2OConnection` object, and it is the only "official" way to create instances of this class.
There are 3 ways to specify the target to connect to (these settings are mutually exclusive):
* pass a ``server`` option,
* pass the full ``url`` for the connection,
* provide a triple of parameters ``ip``, ``port``, ``https``.
:param H2OLocalServer server: connect to the specified local server instance. There is a slight difference
between connecting to a local server by specifying its ip and address, and connecting through
an H2OLocalServer instance: if the server becomes unresponsive, then having access to its process handle
will allow us to query the server status through OS, and potentially provide snapshot of the server's
error log in the exception information.
:param url: full url of the server to connect to.
:param ip: target server's IP address or hostname (default "localhost").
:param port: H2O server's port (default 54321).
:param name: H2O cluster name.
:param https: if True then connect using https instead of http (default False).
:param verify_ssl_certificates: if False then SSL certificate checking will be disabled (default True). This
setting should rarely be disabled, as it makes your connection vulnerable to man-in-the-middle attacks. When
used, it will generate a warning from the requests library. Has no effect when ``https`` is False.
:param auth: authentication token for connecting to the remote server. This can be either a
(username, password) tuple, or an authenticator (AuthBase) object. Please refer to the documentation in
the ``requests.auth`` module.
:param proxy: url address of a proxy server. If you do not specify the proxy, then the requests module
will attempt to use a proxy specified in the environment (in HTTP_PROXY / HTTPS_PROXY variables). We
check for the presence of these variables and issue a warning if they are found. In order to suppress
that warning and use proxy from the environment, pass ``proxy="(default)"``.
:param cookies: Cookie (or list of) to add to requests
:param verbose: if True, then connection progress info will be printed to the stdout.
:param _msgs: custom messages to display during connection. This is a tuple (initial message, success message,
failure message).
:returns: A new :class:`H2OConnection` instance.
:raises H2OConnectionError: if the server cannot be reached.
:raises H2OServerError: if the server is in an unhealthy state (although this might be a recoverable error, the
client itself should decide whether it wants to retry or not).
"""
if server is not None:
assert_is_type(server, H2OLocalServer)
assert_is_type(ip, None, "`ip` should be None when `server` parameter is supplied")
assert_is_type(url, None, "`url` should be None when `server` parameter is supplied")
assert_is_type(name, None, "`name` should be None when `server` parameter is supplied")
if not server.is_running():
raise H2OConnectionError("Unable to connect to server because it is not running")
ip = server.ip
port = server.port
scheme = server.scheme
context_path = ''
elif url is not None:
assert_is_type(url, str)
assert_is_type(ip, None, "`ip` should be None when `url` parameter is supplied")
assert_is_type(name, str, None)
# We don't allow any Unicode characters in the URL. Maybe some day we will...
match = assert_matches(url, H2OConnection.url_pattern)
scheme = match.group(1)
ip = match.group(2)
port = int(match.group(3))
context_path = '' if match.group(4) is None else "%s" % (match.group(4))
else:
if ip is None: ip = str("localhost")
if port is None: port = 54321
if https is None: https = False
if is_type(port, str) and port.isdigit(): port = int(port)
assert_is_type(ip, str)
assert_is_type(port, int)
assert_is_type(name, str, None)
assert_is_type(https, bool)
assert_matches(ip, r"(?:[\w-]+\.)*[\w-]+")
assert_satisfies(port, 1 <= port <= 65535)
scheme = "https" if https else "http"
context_path = ''
if verify_ssl_certificates is None: verify_ssl_certificates = True
assert_is_type(verify_ssl_certificates, bool)
assert_is_type(proxy, str, None)
assert_is_type(auth, AuthBase, (str, str), None)
assert_is_type(cookies, str, [str], None)
assert_is_type(_msgs, None, (str, str, str))
conn = H2OConnection()
conn._verbose = bool(verbose)
conn._local_server = server
conn._base_url = "%s://%s:%d%s" % (scheme, ip, port, context_path)
conn._name = server.name if server else name
conn._verify_ssl_cert = bool(verify_ssl_certificates)
conn._auth = auth
conn._cookies = cookies
conn._proxies = None
if proxy and proxy != "(default)":
conn._proxies = {scheme: proxy}
elif not proxy:
# Give user a warning if there are any "*_proxy" variables in the environment. [PUBDEV-2504]
# To suppress the warning pass proxy = "(default)".
for name in os.environ:
if name.lower() == scheme + "_proxy":
warn("Proxy is defined in the environment: %s. "
"This may interfere with your H2O Connection." % name)
try:
retries = 20 if server else 5
conn._stage = 1
conn._timeout = 3.0
conn._cluster = conn._test_connection(retries, messages=_msgs)
# If a server is unable to respond within 1s, it should be considered a bug. However we disable this
# setting for now, for no good reason other than to ignore all those bugs :(
conn._timeout = None
# This is a good one! On the surface it registers a callback to be invoked when the script is about
# to finish, but it also has a side effect in that the reference to current connection will be held
# by the ``atexit`` service till the end -- which means it will never be garbage-collected.
atexit.register(lambda: conn.close())
except Exception:
# Reset _session_id so that we know the connection was not initialized properly.
conn._stage = 0
raise
return conn
|
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 should be a dictionary of simple
key/value pairs (values can also be arrays), which will be sent over in x-www-form-encoded format.
:param json: also data payload, but it will be sent as a JSON body. Cannot be used together with `data`.
:param filename: file to upload to the server. Cannot be used with `data` or `json`.
:param save_to: if provided, will write the response to that file (additionally, the response will be
streamed, so large files can be downloaded seamlessly). This parameter can be either a file name,
or a folder name. If the folder doesn't exist, it will be created automatically.
:returns: an H2OResponse object representing the server's response (unless ``save_to`` parameter is
provided, in which case the output file's name will be returned).
:raises H2OConnectionError: if the H2O server cannot be reached (or connection is not initialized)
:raises H2OServerError: if there was a server error (http 500), or server returned malformed JSON
:raises H2OResponseError: if the server returned an H2OErrorV3 response (e.g. if the parameters were invalid)
"""
if self._stage == 0: raise H2OConnectionError("Connection not initialized; run .connect() first.")
if self._stage == -1: raise H2OConnectionError("Connection was closed, and can no longer be used.")
# Prepare URL
assert_is_type(endpoint, str)
match = assert_matches(str(endpoint), r"^(GET|POST|PUT|DELETE|PATCH|HEAD) (/.*)$")
method = match.group(1)
urltail = match.group(2)
url = self._base_url + urltail
# Prepare data
if filename is not None:
assert_is_type(filename, str)
assert_is_type(json, None, "Argument `json` should be None when `filename` is used.")
assert_is_type(data, None, "Argument `data` should be None when `filename` is used.")
assert_satisfies(method, method == "POST",
"File uploads can only be done via POST method, got %s" % method)
elif data is not None:
assert_is_type(data, dict)
assert_is_type(json, None, "Argument `json` should be None when `data` is used.")
elif json is not None:
assert_is_type(json, dict)
data = self._prepare_data_payload(data)
files = self._prepare_file_payload(filename)
params = None
if method == "GET" and data:
params = data
data = None
stream = False
if save_to is not None:
assert_is_type(save_to, str)
stream = True
if self._cookies is not None and isinstance(self._cookies, list):
self._cookies = ";".join(self._cookies)
# Make the request
start_time = time.time()
try:
self._log_start_transaction(endpoint, data, json, files, params)
headers = {"User-Agent": "H2O Python client/" + sys.version.replace("\n", ""),
"X-Cluster": self._cluster_id,
"Cookie": self._cookies}
resp = requests.request(method=method, url=url, data=data, json=json, files=files, params=params,
headers=headers, timeout=self._timeout, stream=stream,
auth=self._auth, verify=self._verify_ssl_cert, proxies=self._proxies)
self._log_end_transaction(start_time, resp)
return self._process_response(resp, save_to)
except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as e:
if self._local_server and not self._local_server.is_running():
self._log_end_exception("Local server has died.")
raise H2OConnectionError("Local server has died unexpectedly. RIP.")
else:
self._log_end_exception(e)
raise H2OConnectionError("Unexpected HTTP error: %s" % e)
except requests.exceptions.Timeout as e:
self._log_end_exception(e)
elapsed_time = time.time() - start_time
raise H2OConnectionError("Timeout after %.3fs" % elapsed_time)
except H2OResponseError as e:
err = e.args[0]
err.endpoint = endpoint
err.payload = (data, json, files, params)
raise
|
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), however there is also
no good reason to make this method private.
"""
if self._session_id:
try:
# If the server gone bad, we don't want to wait forever...
if self._timeout is None: self._timeout = 1
self.request("DELETE /4/sessions/%s" % self._session_id)
self._print("H2O session %s closed." % self._session_id)
except Exception:
pass
self._session_id = None
self._stage = -1
|
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. Once
issued, the session id will stay the same until the connection is closed.
"""
if self._session_id is None:
req = self.request("POST /4/sessions")
self._session_id = req.get("session_key") or req.get("session_id")
return CallableString(self._session_id)
|
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_type(dest, None, str, type(sys.stdout))
if dest is None:
dest = os.path.join(tempfile.mkdtemp(), "h2o-connection.log")
self._print("Now logging all API requests to file %r" % dest)
self._is_logging = True
self._logging_dest = dest
|
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 such format.
"""
if not data: return None
res = {}
for key, value in viewitems(data):
if value is None: continue # don't send args set to None so backend defaults take precedence
if isinstance(value, list):
value = stringify_list(value)
elif isinstance(value, dict):
if "__meta" in value and value["__meta"]["schema_name"].endswith("KeyV3"):
value = value["name"]
else:
value = stringify_dict(value)
else:
value = str(value)
res[key] = value
return res
|
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)
if not os.path.exists(absfilename):
raise H2OValueError("File %s does not exist" % filename, skip_frames=1)
return {os.path.basename(absfilename): open(absfilename, "rb")}
|
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 until we find the request function
self._requests_counter += 1
if not self._is_logging: return
msg = "\n---- %d --------------------------------------------------------\n" % self._requests_counter
msg += "[%s] %s\n" % (time.strftime("%H:%M:%S"), endpoint)
if params is not None: msg += " params: {%s}\n" % ", ".join("%s:%s" % item for item in viewitems(params))
if data is not None: msg += " body: {%s}\n" % ", ".join("%s:%s" % item for item in viewitems(data))
if json is not None:
import json as j
msg += " json: %s\n" % j.dumps(json)
if files is not None: msg += " file: %s\n" % ", ".join(f.name for f in viewvalues(files))
self._log_message(msg + "\n")
|
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 "Content-Type" in response.headers:
msg += " Content-Type: %s\n" % response.headers["Content-Type"]
msg += response.text
self._log_message(msg + "\n\n")
|
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 there and do not
attempt to close it.
"""
if is_type(self._logging_dest, str):
with open(self._logging_dest, "at", encoding="utf-8") as f:
f.write(msg)
else:
self._logging_dest.write(msg)
|
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 that either parse the response as JSON or return as plain text.
"""
status_code = response.status_code
if status_code == 200 and save_to:
if save_to.startswith("~"): save_to = os.path.expanduser(save_to)
if os.path.isdir(save_to) or save_to.endswith(os.path.sep):
dirname = os.path.abspath(save_to)
filename = H2OConnection._find_file_name(response)
else:
dirname, filename = os.path.split(os.path.abspath(save_to))
fullname = os.path.join(dirname, filename)
try:
if not os.path.exists(dirname):
os.makedirs(dirname)
with open(fullname, "wb") as f:
for chunk in response.iter_content(chunk_size=65536):
if chunk: # Empty chunks may occasionally happen
f.write(chunk)
except OSError as e:
raise H2OValueError("Cannot write to file %s: %s" % (fullname, e))
return fullname
content_type = response.headers.get("Content-Type", "")
if ";" in content_type: # Remove a ";charset=..." part
content_type = content_type[:content_type.index(";")]
# Auto-detect response type by its content-type. Decode JSON, all other responses pass as-is.
if content_type == "application/json":
try:
data = response.json(object_pairs_hook=H2OResponse)
except (JSONDecodeError, requests.exceptions.ContentDecodingError) as e:
raise H2OServerError("Malformed JSON from server (%s):\n%s" % (str(e), response.text))
else:
data = response.text
# Success (200 = "Ok", 201 = "Created", 202 = "Accepted", 204 = "No Content")
if status_code in {200, 201, 202, 204}:
return data
# Client errors (400 = "Bad Request", 404 = "Not Found", 412 = "Precondition Failed")
if status_code in {400, 404, 412} and isinstance(data, (H2OErrorV3, H2OModelBuilderErrorV3)):
raise H2OResponseError(data)
# Server errors (notably 500 = "Server Error")
# Note that it is possible to receive valid H2OErrorV3 object in this case, however it merely means the server
# did not provide the correct status code.
raise H2OServerError("HTTP %d %s:\n%r" % (status_code, response.reason, data))
|
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
tol or relative error rel of x. You can disable either the absolute or
relative check by passing None as tol or rel (but not both).
For any other objects, x and y are checked in that order for a method
__approxEqual__, and the result of that is returned as a bool. Any
optional arguments are passed to the __approxEqual__ method.
__approxEqual__ can return NotImplemented to signal that it doesn't know
how to perform that specific comparison, in which case the other object is
checked instead. If neither object have the method, or both defer by
returning NotImplemented, approxEqual falls back on the same numeric
comparison used for floats.
>>> almost_equal(1.2345678, 1.2345677)
True
>>> almost_equal(1.234, 1.235)
False
"""
if not (type(x) is type(y) is float):
# Skip checking for __approxEqual__ in the common case of two floats.
methodname = '__approxEqual__'
# Allow the objects to specify what they consider "approximately equal",
# giving precedence to x. If either object has the appropriate method, we
# pass on any optional arguments untouched.
for a,b in ((x, y), (y, x)):
try:
method = getattr(a, methodname)
except AttributeError:
continue
else:
result = method(b, *args, **kwargs)
if result is NotImplemented:
print "WARNING: NotImplemented approxEqual for types"
continue
return bool(result)
# If we get here without returning, then neither x nor y knows how to do an
# approximate equal comparison (or are both floats). Fall back to a numeric
# comparison.
return _float_approxEqual(x, y, *args, **kwargs)
|
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_depth>max_depth:
return
if isinstance(obj, (bool, int, long, float, basestring)):
return obj
elif isinstance(obj, dict):
obj = obj.copy()
for key in obj:
obj[key] = serialize(obj[key], curr_depth+1)
return obj
elif isinstance(obj, list):
return [serialize(item, curr_depth+1) for item in obj]
elif isinstance(obj, tuple):
return tuple(serialize([item for item in obj], curr_depth+1))
elif hasattr(obj, '__dict__'):
return serialize(obj.__dict__, curr_depth+1)
else:
return repr(obj) # Don't know how to handle, convert to string
return (serialize(obj, curr_depth+1))
|
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 /99/AutoML/%s" % project_name)
project_name = automl_json["project_name"]
leaderboard_list = [key["name"] for key in automl_json['leaderboard']['models']]
if leaderboard_list is not None and len(leaderboard_list) > 0:
leader_id = leaderboard_list[0]
else:
leader_id = None
leader = h2o.get_model(leader_id)
# Intentionally mask the progress bar here since showing multiple progress bars is confusing to users.
# If any failure happens, revert back to user's original setting for progress and display the error message.
is_progress = H2OJob.__PROGRESS_BAR__
h2o.no_progress()
try:
# Parse leaderboard H2OTwoDimTable & return as an H2OFrame
leaderboard = h2o.H2OFrame(
automl_json["leaderboard_table"].cell_values,
column_names=automl_json["leaderboard_table"].col_header)
except Exception as ex:
raise ex
finally:
if is_progress is True:
h2o.show_progress()
leaderboard = leaderboard[1:]
automl_dict = {'project_name': project_name, "leader": leader, "leaderboard": leaderboard}
return automl_dict
|
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 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.
:param x: A list of column names or indices indicating the predictor columns.
:param y: An index or a column name indicating the response column.
:param fold_column: The name or index of the column in training_frame that holds per-row fold
assignments.
:param weights_column: The name or index of the column in training_frame that holds per-row weights.
:param training_frame: The H2OFrame having the columns indicated by x and y (as well as any
additional columns specified by fold_column or weights_column).
:param validation_frame: H2OFrame with validation data. This argument is ignored unless the user sets
nfolds = 0. If cross-validation is turned off, then a validation frame can be specified and used
for early stopping of individual models and early stopping of the grid searches. By default and
when nfolds > 1, cross-validation metrics will be used for early stopping and thus validation_frame will be ignored.
:param leaderboard_frame: H2OFrame with test data for scoring the leaderboard. This is optional and
if this is set to None (the default), then cross-validation metrics will be used to generate the leaderboard
rankings instead.
:param blending_frame: H2OFrame used to train the the metalearning algorithm in Stacked Ensembles (instead of relying on cross-validated predicted values).
This is optional, but when provided, it is also recommended to disable cross validation
by setting `nfolds=0` and to provide a leaderboard frame for scoring purposes.
:returns: An H2OAutoML object.
:examples:
>>> # Set up an H2OAutoML object
>>> aml = H2OAutoML(max_runtime_secs=30)
>>> # Launch an AutoML run
>>> aml.train(y=y, training_frame=train)
"""
ncols = training_frame.ncols
names = training_frame.names
#Set project name if None
if self.project_name is None:
self.project_name = "automl_" + training_frame.frame_id
self.build_control["project_name"] = self.project_name
# Minimal required arguments are training_frame and y (response)
if y is None:
raise ValueError('The response column (y) is not set; please set it to the name of the column that you are trying to predict in your data.')
else:
assert_is_type(y,int,str)
if is_type(y, int):
if not (-ncols <= y < ncols):
raise H2OValueError("Column %d does not exist in the training frame" % y)
y = names[y]
else:
if y not in names:
raise H2OValueError("Column %s does not exist in the training frame" % y)
input_spec = {
'response_column': y,
}
if training_frame is None:
raise ValueError('The training frame is not set!')
else:
assert_is_type(training_frame, H2OFrame)
input_spec['training_frame'] = training_frame.frame_id
if fold_column is not None:
assert_is_type(fold_column,int,str)
input_spec['fold_column'] = fold_column
if weights_column is not None:
assert_is_type(weights_column,int,str)
input_spec['weights_column'] = weights_column
if validation_frame is not None:
assert_is_type(validation_frame, H2OFrame)
input_spec['validation_frame'] = validation_frame.frame_id
if leaderboard_frame is not None:
assert_is_type(leaderboard_frame, H2OFrame)
input_spec['leaderboard_frame'] = leaderboard_frame.frame_id
if blending_frame is not None:
assert_is_type(blending_frame, H2OFrame)
input_spec['blending_frame'] = blending_frame.frame_id
if self.sort_metric is not None:
assert_is_type(self.sort_metric, str)
sort_metric = self.sort_metric.lower()
# Changed the API to use "deviance" to be consistent with stopping_metric values
# TO DO: let's change the backend to use "deviance" since we use the term "deviance"
# After that we can take this `if` statement out
if sort_metric == "deviance":
sort_metric = "mean_residual_deviance"
input_spec['sort_metric'] = sort_metric
if x is not None:
assert_is_type(x,list)
xset = set()
if is_type(x, int, str): x = [x]
for xi in x:
if is_type(xi, int):
if not (-ncols <= xi < ncols):
raise H2OValueError("Column %d does not exist in the training frame" % xi)
xset.add(names[xi])
else:
if xi not in names:
raise H2OValueError("Column %s not in the training frame" % xi)
xset.add(xi)
x = list(xset)
ignored_columns = set(names) - {y} - set(x)
if fold_column is not None and fold_column in ignored_columns:
ignored_columns.remove(fold_column)
if weights_column is not None and weights_column in ignored_columns:
ignored_columns.remove(weights_column)
if ignored_columns is not None:
input_spec['ignored_columns'] = list(ignored_columns)
automl_build_params = dict(input_spec = input_spec)
# NOTE: if the user hasn't specified some block of parameters don't send them!
# This lets the back end use the defaults.
automl_build_params['build_control'] = self.build_control
automl_build_params['build_models'] = self.build_models
resp = h2o.api('POST /99/AutoMLBuilder', json=automl_build_params)
if 'job' not in resp:
print("Exception from the back end: ")
print(resp)
return
self._job = H2OJob(resp['job'], "AutoML")
self._job.poll()
self._fetch()
|
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)
>>> # Launch an H2OAutoML run
>>> aml.train(y=y, training_frame=train)
>>> # Predict with top model from AutoML Leaderboard on a H2OFrame called 'test'
>>> aml.predict(test)
"""
if self._fetch():
self._model = h2o.get_model(self._leader_id)
return self._model.predict(test_data)
print("No model built yet...")
|
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 should be saved.
:param get_genmodel_jar: if True, then also download h2o-genmodel.jar and store it in folder ``path``.
:param genmodel_name Custom name of genmodel jar
:returns: name of the POJO file written.
"""
return h2o.download_pojo(self.leader, path, get_jar=get_genmodel_jar, jar_name=genmodel_name)
|
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``.
:param genmodel_name Custom name of genmodel jar
:returns: name of the MOJO file written.
"""
return ModelBase.download_mojo(self.leader, path, get_genmodel_jar, genmodel_name)
|
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 instance
"""
if isinstance(self.parms["center"], (tuple, list)): self._means = self.parms["center"]
if isinstance(self.parms["scale"], (tuple, list)): self._stds = self.parms["scale"]
if self.means is None and self.parms["center"]:
self._means = X.mean(return_frame=True).getrow()
else:
self._means = False
if self.stds is None and self.parms["scale"]:
self._stds = X.sd()
else:
self._stds = False
return self
|
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.
"""
return X.scale(self.means, self.stds)
|
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):
X[i] = self.means[i] + self.stds[i] * X[i]
return X
|
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+' \
+ 'resolutiondate+>=+' + g_start_date.strftime("%Y-%m-%d") \
+ '+and+' \
+ 'resolution+in+(Done,Fixed)' \
+ 'order+by+type,component,resolutiondate' \
+ '&maxResults=1000'
r = requests.get(url, auth=(g_user, g_pass))
if (r.status_code != 200):
print("ERROR: status code is " + str(r.status_code))
sys.exit(1)
j = r.json()
issues = j[u'issues']
if len(issues) >= 1000:
print("ERROR: len(issues) >= 1000. Too many issues.")
sys.exit(1)
last_issue_type_name = ""
last_component_name = ""
for issue in issues:
issue_type_name = get_issue_type_name(issue)
component_name = get_issue_component_name(issue)
if (issue_type_name != last_issue_type_name):
print("")
print "# " + issue_type_name
last_issue_type_name = issue_type_name
if (component_name != last_component_name):
print("")
print "## " + component_name
last_component_name = component_name
key = get_issue_key(issue)
summary = get_issue_summary(issue)
print "* " + key + ": " + summary
|
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 of the junk.
|
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 the issue. Hence, we are going to the heat and just manually
get rid of the junk.
Parameters
----------
string_content : str
contains a line read in from jenkins console
:return: str: contains the content of the line after the string '[0m'
"""
startL,found,endL = string_content.partition('[0m')
if found:
return endL
else:
return string_content
|
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 perform this action again.
Parameters
----------
each_line : str
contains a line read in from jenkins console
temp_func_list : list of Python function handles
contains a list of functions that we want to invoke to extract information from
the Jenkins console text.
:return: bool to determine if text mining should continue on the jenkins console text
"""
global g_weekdays
global g_months
global g_failed_test_info_dict
temp_strings = each_line.strip().split()
if (len(temp_strings) > 2):
if ((temp_strings[0] in g_weekdays) or (temp_strings[1] in g_weekdays)) and ((temp_strings[1] in g_months) or (temp_strings[2] in g_months)):
g_failed_test_info_dict["3.timestamp"] = each_line.strip()
temp_func_list.remove(find_time) # found timestamp, don't need to look again for it
return True
|
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.
Parameters
----------
each_line : str
contains a line read in from jenkins console
temp_func_list : list of Python function handles
contains a list of functions that we want to invoke to extract information from
the Jenkins console text.
:return: bool to determine if text mining should continue on the jenkins console text
"""
global g_node_name
global g_failed_test_info_dict
if g_node_name in each_line:
temp_strings = each_line.split()
[start,found,endstr] = each_line.partition(g_node_name)
if found:
temp_strings = endstr.split()
g_failed_test_info_dict["6.node_name"] = extract_true_string(temp_strings[1])
temp_func_list.remove(find_node_name)
return True
|
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 action again.
Parameters
----------
each_line : str
contains a line read in from jenkins console
temp_func_list : list of Python function handles
contains a list of functions that we want to invoke to extract information from
the Jenkins console text.
:return: bool to determine if text mining should continue on the jenkins console text
"""
global g_git_hash_branch
global g_failed_test_info_dict
if g_git_hash_branch in each_line:
[start,found,endstr] = each_line.partition(g_git_hash_branch)
temp_strings = endstr.strip().split()
if len(temp_strings) > 1:
g_failed_test_info_dict["4.git_hash"] = temp_strings[0]
g_failed_test_info_dict["5.git_branch"] = temp_strings[1]
temp_func_list.remove(find_git_hash_branch)
return True
|
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 : list of Python function handles
contains a list of functions that we want to invoke to extract information from
the Jenkins console text.
:return: bool to determine if text mining should continue on the jenkins console text
"""
global g_build_timeout
global g_failed_test_info_dict
global g_failure_occurred
if g_build_timeout in each_line:
g_failed_test_info_dict["8.build_timeout"] = 'Yes'
g_failure_occurred = True
return False # build timeout was found, no need to continue mining the console text
else:
return True
|
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
----------
each_line : str
contains a line read in from jenkins console
temp_func_list : list of Python function handles
contains a list of functions that we want to invoke to extract information from
the Jenkins console text.
:return: bool to determine if text mining should continue on the jenkins console text
"""
global g_build_success
global g_build_success_tests
global g_failed_test_info_dict
global g_failure_occurred
global g_build_failed_message
for ind in range(0,len(g_build_failed_message)):
if g_build_failed_message[ind] in each_line.lower():
if ((ind == 0) and (len(g_failed_jobs) > 0)):
continue
else:
g_failure_occurred = True
g_failed_test_info_dict["7.build_failure"] = 'Yes'
temp_func_list.remove(find_build_failure)
return False
return True
|
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 console
temp_func_list : list of Python function handles
contains a list of functions that we want to invoke to extract information from
the Jenkins console text.
:return: bool to determine if text mining should continue on the jenkins console text
"""
global g_before_java_file
global g_java_filenames
for each_word in g_before_java_file:
if (each_word not in each_line):
return True
# line contains the name and location of java txt output filename
temp_strings = each_line.split()
g_java_filenames.append(temp_strings[-1])
return True
|
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
----------
each_line : str
contains a line read in from jenkins console
temp_func_list : list of Python function handles
contains a list of functions that we want to invoke to extract information from
the Jenkins console text.
:return: bool to determine if text mining should continue on the jenkins console text
"""
global g_before_java_file
global g_java_filenames
global g_build_id_text
global g_jenkins_url
global g_output_filename
global g_output_pickle_filename
if g_build_id_text in each_line:
[startStr,found,endStr] = each_line.partition(g_build_id_text)
g_failed_test_info_dict["2.build_id"] = endStr.strip()
temp_func_list.remove(find_build_id)
g_jenkins_url = os.path.join('http://',g_jenkins_url,'view',g_view_name,'job',g_failed_test_info_dict["1.jobName"],g_failed_test_info_dict["2.build_id"],'artifact')
return True
|
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 information on the jenkins job whose console output we are interested in.
:return: none
"""
global g_failed_test_info_dict
global g_jenkins_url
global g_view_name
tempString = url_string.strip('/').split('/')
if len(tempString) < 6:
print "Illegal URL resource address.\n"
sys.exit(1)
g_failed_test_info_dict["1.jobName"] = tempString[6]
g_jenkins_url = tempString[2]
g_view_name = tempString[4]
|
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_testname
global g_java_start_text
global g_ok_java_messages
global g_java_general_bad_messages # store bad java messages not associated with running a unit test
global g_java_general_bad_message_types
global g_failure_occurred
global g_java_message_type
global g_all_java_message_type
global g_toContinue
java_messages = [] # store all bad java messages associated with running a unit test
java_message_types = [] # store all bad java message types associated with running a unit test
if os.path.isfile(g_temp_filename): # open temp file containing content of some java_*_0.out.txt
java_file = open(g_temp_filename,'r')
g_toContinue = False # denote if a multi-line message starts
tempMessage = ""
messageType = ""
for each_line in java_file:
if (g_java_start_text in each_line):
startStr,found,endStr = each_line.partition(g_java_start_text)
if len(found) > 0:
if len(g_current_testname) > 0: # a new unit test is being started. Save old info and move on
associate_test_with_java(g_current_testname,java_messages,java_message_types)
g_current_testname = endStr.strip() # record the test name
java_messages = []
java_message_types = []
temp_strings = each_line.strip().split()
if (len(temp_strings) >= 6) and (temp_strings[5] in g_all_java_message_type):
if g_toContinue == True: # at the end of last message fragment
addJavaMessages(tempMessage,messageType,java_messages,java_message_types)
tempMessage = ""
messageType = ""
# start of new message fragment
g_toContinue = False
else: # non standard output. Continuation of last java message, add it to bad java message list
if g_toContinue:
tempMessage += each_line # add more java message here
# if len(g_current_testname) == 0:
# addJavaMessages(each_line.strip(),"",java_messages,java_message_types)
# else:
# addJavaMessages(each_line.strip(),"",java_messages,java_message_types)
if ((len(temp_strings) > 5) and (temp_strings[5] in g_java_message_type)): # find a bad java message
startStr,found,endStr = each_line.partition(temp_strings[5]) # can be WARN,ERRR,FATAL,TRACE
if found and (len(endStr.strip()) > 0):
tempMessage += endStr
messageType = temp_strings[5]
# if (tempMessage not in g_ok_java_messages["general"]): # found new bad messages that cannot be ignored
g_toContinue = True
# add tempMessage to bad java message list
# addJavaMessages(tempMessage,temp_strings[5],java_messages,java_message_types)
java_file.close()
|
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
----------
tempMessage : str
contains the bad java messages
messageType : str
contains the bad java message type
java_messages : list of str
contains the bad java message list associated with a unit test
java_message_tuypes : list of str
contains the bad java message type list associated with a unit test.
:return: none
"""
global g_current_testname
global g_java_general_bad_messages
global g_java_general_bad_message_types
global g_failure_occurred
tempMess = tempMessage.strip()
if (tempMess not in g_ok_java_messages["general"]):
if (len(g_current_testname) == 0): # java message not associated with any test name
g_java_general_bad_messages.append(tempMess)
g_java_general_bad_message_types.append(messageType)
g_failure_occurred = True
else: # java message found during a test
write_test = False # do not include java message for test if False
if (g_current_testname in g_ok_java_messages.keys()) and (tempMess in g_ok_java_messages[g_current_testname]): # test name associated with ignored Java messages
write_test = False
else: # not java ignored message for current unit test
write_test = True
if write_test:
java_messages.append(tempMess)
java_message_types.append(messageType)
g_failure_occurred = True
|
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
global g_java_filenames
global g_failed_jobs # record job names of failed jobs
global g_failed_job_java_messages # record failed job java message
global g_failed_job_java_message_types
global g_success_jobs # record job names of passed jobs
global g_success_job_java_messages # record of successful jobs bad java messages
global g_success_job_java_message_types
global g_java_general_bad_messages # store java error messages when no job is running
global g_java_general_bad_message_types # store java error message types when no job is running.
if (len(g_failed_jobs) > 0): # artifacts available only during failure of some sort
for fname in g_java_filenames: # grab java message from each java_*_*_.out file
temp_strings = fname.split('/')
start_url = g_jenkins_url
for windex in range(6,len(temp_strings)):
start_url = os.path.join(start_url,temp_strings[windex])
try: # first java file path is different. Can ignore it.
get_console_out(start_url) # get java text and save it in local directory for processing
grab_java_message() # actually process the java text output and see if we found offensive stuff
except:
pass
# build up the dict structure that we are storing our data in
if len(g_failed_jobs) > 0:
g_failed_test_info_dict["failed_tests_info *********"] = [g_failed_jobs,g_failed_job_java_messages,g_failed_job_java_message_types]
if len(g_success_jobs) > 0:
g_failed_test_info_dict["passed_tests_info *********"] = [g_success_jobs,g_success_job_java_messages,g_success_job_java_message_types]
if len(g_java_general_bad_messages) > 0:
g_failed_test_info_dict["9.general_bad_java_messages"] = [g_java_general_bad_messages,g_java_general_bad_message_types]
|
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_filename
global g_failed_test_info_dict
# some build can fail really early that no buid id info is stored in the console text.
if "2.build_id" not in g_failed_test_info_dict.keys():
g_failed_test_info_dict["2.build_id"] = "unknown"
build_id = g_failed_test_info_dict["2.build_id"]
g_output_filename_failed_tests = g_output_filename_failed_tests+'_build_'+build_id+'_failed_tests.log'
g_output_filename_passed_tests = g_output_filename_passed_tests+'_build_'+build_id+'_passed_tests.log'
g_output_pickle_filename = g_output_pickle_filename+'_build_'+build_id+'.pickle'
allKeys = sorted(g_failed_test_info_dict.keys())
# write out the jenkins job info into log files.
with open(g_output_pickle_filename,'wb') as test_file:
pickle.dump(g_failed_test_info_dict,test_file)
# write out the failure report as text into a text file
text_file_failed_tests = open(g_output_filename_failed_tests,'w')
text_file_passed_tests = None
allKeys = sorted(g_failed_test_info_dict.keys())
write_passed_tests = False
if ("passed_tests_info *********" in allKeys):
text_file_passed_tests = open(g_output_filename_passed_tests,'w')
write_passed_tests = True
for keyName in allKeys:
val = g_failed_test_info_dict[keyName]
if isinstance(val,list): # writing one of the job lists
if (len(val) == 3): # it is a message for a test
if keyName == "failed_tests_info *********":
write_test_java_message(keyName,val,text_file_failed_tests)
if keyName == "passed_tests_info *********":
write_test_java_message(keyName,val,text_file_passed_tests)
elif (len(val) == 2): # it is a general bad java message
write_java_message(keyName,val,text_file_failed_tests)
if write_passed_tests:
write_java_message(keyName,val,text_file_passed_tests)
else:
write_general_build_message(keyName,val,text_file_failed_tests)
if write_passed_tests:
write_general_build_message(keyName,val,text_file_passed_tests)
text_file_failed_tests.close()
if write_passed_tests:
text_file_passed_tests.close()
|
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 : file handle
file handle of log file to write the info to.
:return: none
"""
text_file.write(key+": ")
text_file.write(val)
text_file.write('\n\n')
|
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_text_filename,'a') as tempfile:
write_file_content(tempfile,g_output_filename_failed_tests)
write_file_content(tempfile,g_output_filename_passed_tests)
|
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 summary text file.
:return: none
"""
if os.path.isfile(file2read):
# write summary of failed tests logs
with open(file2read,'r') as tfile:
fhandle.write('============ Content of '+ file2read)
fhandle.write('\n')
fhandle.write(tfile.read())
fhandle.write('\n\n')
|
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 the message types.
:return: none
"""
text_file.write(key)
text_file.write('\n')
if (len(val[0]) > 0) and (len(val) >= 3):
for index in range(len(val[0])):
text_file.write("Java Message Type: ")
text_file.write(val[1][index])
text_file.write('\n')
text_file.write("Java Message: ")
for jmess in val[2][index]:
text_file.write(jmess)
text_file.write('\n')
text_file.write('\n \n')
|
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_filename
if os.path.isfile(g_java_message_pickle_filename):
with open(g_java_message_pickle_filename,'rb') as tfile:
g_ok_java_messages = pickle.load(tfile)
else:
g_ok_java_messages["general"] = []
|
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_test_info_dict
global g_java_message_pickle_filename
global g_summary_text_filename
if len(argv) < 3:
print "Must resource url like http://mr-0xa1:8080/view/wendy_jenkins/job/h2o_regression_pyunit_medium_large/lastBuild/consoleFull, filename of summary text, filename (optional ending in .pickle) to retrieve Java error messages to exclude.\n"
sys.exit(1)
else: # we may be in business
g_script_name = os.path.basename(argv[0]) # get name of script being run.
resource_url = argv[1]
g_temp_filename = os.path.join(g_test_root_dir,'tempText')
g_summary_text_filename = os.path.join(g_test_root_dir,argv[2])
if len(argv) == 4:
g_java_message_pickle_filename = argv[3]
get_console_out(resource_url) # save remote console output in local directory
extract_job_build_url(resource_url) # extract the job name of build id for identification purposes
log_filename = g_failed_test_info_dict["1.jobName"]
log_pickle_filename = g_failed_test_info_dict["1.jobName"]
# pickle file that store bad Java messages that we can ignore.
g_java_message_pickle_filename = os.path.join(g_test_root_dir,g_java_message_pickle_filename)
g_output_filename_failed_tests = os.path.join(g_test_root_dir,log_filename)
g_output_filename_passed_tests = os.path.join(g_test_root_dir,log_filename)
g_output_pickle_filename = os.path.join(g_test_root_dir,log_pickle_filename)
load_java_messages_to_ignore() # load in bad java messages to ignore and store in g_ok_java_messages
extract_test_results() # grab the console text and stored the failed tests.
extract_java_messages() # grab dangerous java messages that we found for the various unit tests
if ((len(g_failed_jobs) > 0) or (g_failed_test_info_dict["7.build_failure"]=='Yes')):
g_failure_occurred = True
if g_failure_occurred:
save_dict() # save the dict structure in a pickle file and a text file when failure is detected
update_summary_file() # join together all log files into one giant summary text.
# output this info to console to form the list of failed jenkins jobs.
print g_failed_test_info_dict["1.jobName"]+' build '+g_failed_test_info_dict["2.build_id"]+','
else:
print ""
|
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.
"""
j = h2o.api("GET /3/Word2VecSynonyms", data={'model': self.model_id, 'word': word, 'count': count})
return OrderedDict(sorted(zip(j['synonyms'], j['scores']), key=lambda t: t[1], reverse=True))
|
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 method is `NONE`
then no aggregation is performed and each input word is mapped to a single word-vector.
If method is 'AVERAGE' then input is treated as sequences of words delimited by NA.
Each word of a sequences is internally mapped to a vector and vectors belonging to
the same sentence are averaged and returned in the result.
:returns: the approximate reconstruction of the training data.
"""
j = h2o.api("GET /3/Word2VecTransform", data={'model': self.model_id, 'words_frame': words.frame_id, 'aggregate_method': aggregate_method})
return h2o.get_frame(j["vectors_frame"]["name"])
|
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.
"""
try:
hidden = not H2OJob.__PROGRESS_BAR__
pb = ProgressBar(title=self._job_type + " progress", hidden=hidden)
if verbose_model_scoring_history:
pb.execute(self._refresh_job_status, print_verbose_info=lambda x: self._print_verbose_info() if int(x * 10) % 5 == 0 else " ")
else:
pb.execute(self._refresh_job_status)
except StopIteration as e:
if str(e) == "cancelled":
h2o.api("POST /3/Jobs/%s/cancel" % self.job_key)
self.status = "CANCELLED"
# Potentially we may want to re-raise the exception here
assert self.status in {"DONE", "CANCELLED", "FAILED"} or self._poll_count <= 0, \
"Polling finished while the job has status %s" % self.status
if self.warnings:
for w in self.warnings:
warnings.warn(w)
# check if failed... and politely print relevant message
if self.status == "CANCELLED":
raise H2OJobCancelled("Job<%s> was cancelled by the user." % self.job_key)
if self.status == "FAILED":
if (isinstance(self.job, dict)) and ("stacktrace" in list(self.job)):
raise EnvironmentError("Job with key {} failed with an exception: {}\nstacktrace: "
"\n{}".format(self.job_key, self.exception, self.job["stacktrace"]))
else:
raise EnvironmentError("Job with key %s failed with an exception: %s" % (self.job_key, self.exception))
return self
|
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 compile the POJO
:return: None
"""
assert_is_type(pojo_name, str)
assert_is_type(path, str)
assert_is_type(get_jar, bool)
if pojo_name == "":
pojo_name = "AssemblyPOJO_" + str(uuid.uuid4())
java = h2o.api("GET /99/Assembly.java/%s/%s" % (self.id, pojo_name))
file_path = path + "/" + pojo_name + ".java"
if path == "":
print(java)
else:
with open(file_path, 'w', encoding="utf-8") as f:
f.write(java) # this had better be utf-8 ?
if get_jar and path != "":
h2o.api("GET /3/h2o-genmodel.jar", save_to=os.path.join(path, "h2o-genmodel.jar"))
|
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)
steps = "[%s]" % ",".join(quoted(step[1].to_rest(step[0]).replace('"', "'")) for step in self.steps)
j = h2o.api("POST /99/Assembly", data={"steps": steps, "frame": fr.frame_id})
self.id = j["assembly"]["name"]
return H2OFrame.get_frame(j["result"]["name"])
|
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:", interpolate
print "Supported choices:", interpolateChoices
"""
Find the percentile of a list of values.
@parameter N - is a list of values. Note N MUST BE already sorted.
@parameter percent - a float value from 0.0 to 1.0.
@parameter key - optional key function to compute value from each element of N.
@return - the percentile of the values
"""
if N is None:
return None
k = (len(N)-1) * percent
f = int(math.floor(k))
c = int(math.ceil(k))
if f == c:
d = key(N[f])
msg = "aligned:"
elif interpolate=='floor':
d = key(N[f])
msg = "fractional with floor:"
elif interpolate=='ceil':
d = key(N[c])
msg = "fractional with ceil:"
elif interpolate=='funky':
d0 = key(N[f]) * (c-k)
d1 = key(N[c]) * (k-f)
d = d0+d1
msg = "fractional with Tung(floor and ceil) :"
elif interpolate=='linear':
assert (c-f)==1
assert (k>=f) and (k<=c)
pctDiff = k-f
dDiff = pctDiff * (key(N[c]) - key(N[f]))
d = key(N[f] + dDiff)
msg = "fractional %s with linear(floor and ceil):" % pctDiff
elif interpolate=='mean':
d = (key(N[c]) + key(N[f])) / 2.0
msg = "fractional with mean(floor and ceil):"
# print 3 around the floored k, for eyeballing when we're close
flooredK = int(f)
# print the 3 around the median
if flooredK > 0:
print "prior->", key(N[flooredK-1]), " "
else:
print "prior->", "<bof>"
print "floor->", key(N[flooredK]), " ", msg, 'result:', d, "f:", f, "len(N):", len(N)
if flooredK+1 < len(N):
print " ceil->", key(N[flooredK+1]), "c:", c
else:
print " ceil-> <eof>", "c:", c
return d
|
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"],
"actual": self.parms[p]["actual_value"]}
return params
|
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 = {}
for p in self.parms:
if p in params_to_select.keys():
params[p] = self.parms[p]["actual_value"].get(params_to_select[p], None)
else:
params[p] = self.parms[p]["actual_value"]
return 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 identified by a path from to the root node
of the tree to the node or by H2O's internal node id. One of: ``"Path"``, ``"Node_ID"`` (default: ``"Path"``).
:returns: A new H2OFrame of predictions.
"""
if not isinstance(test_data, h2o.H2OFrame): raise ValueError("test_data must be an instance of H2OFrame")
assert_is_type(type, None, Enum("Path", "Node_ID"))
j = h2o.api("POST /3/Predictions/models/%s/frames/%s" % (self.model_id, test_data.frame_id),
data={"leaf_node_assignment": True, "leaf_node_assignment_type": type})
return h2o.get_frame(j["predictions_frame"]["name"])
|
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 tree 3 and class 1). The value will be the corresponding
predicted probability of this class by combining the raw contributions of trees T1.Cc,..,TtCc. Binomial models
build the trees just for the first class and values in columns Tx.C1 thus correspond to the the probability p0.
:param H2OFrame test_data: Data on which to make predictions.
:returns: A new H2OFrame of staged predictions.
"""
if not isinstance(test_data, h2o.H2OFrame): raise ValueError("test_data must be an instance of H2OFrame")
j = h2o.api("POST /3/Predictions/models/%s/frames/%s" % (self.model_id, test_data.frame_id),
data={"predict_staged_proba": True})
return h2o.get_frame(j["predictions_frame"]["name"])
|
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 cluster
:param custom_metric_func: custom evaluation function reference, e.g, result of upload_custom_metric
:returns: A new H2OFrame of predictions.
"""
# Upload evaluation function into DKV
if custom_metric:
assert_satisfies(custom_metric_func, custom_metric_func is None,
"The argument 'eval_func_ref' cannot be specified when eval_func is specified, ")
eval_func_ref = h2o.upload_custom_metric(custom_metric)
if not isinstance(test_data, h2o.H2OFrame): raise ValueError("test_data must be an instance of H2OFrame")
j = H2OJob(h2o.api("POST /4/Predictions/models/%s/frames/%s" % (self.model_id, test_data.frame_id), data = {'custom_metric_func': custom_metric_func}),
self._model_json["algo"] + " prediction")
j.poll()
return h2o.get_frame(j.dest_key)
|
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_model(k) for k in self._xval_keys]
|
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():
j = H2OJob(h2o.api("POST /4/Predictions/models/%s/frames/%s" % (self._id, test_data.frame_id),
data={"deep_features_hidden_layer": layer}), "deepfeatures")
else:
j = H2OJob(h2o.api("POST /4/Predictions/models/%s/frames/%s" % (self._id, test_data.frame_id),
data={"deep_features_hidden_layer_name": layer}), "deepfeatures")
j.poll()
return h2o.get_frame(j.dest_key)
|
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
"""
num_weight_matrices = len(self._model_json["output"]["weights"])
if matrix_id not in list(range(num_weight_matrices)):
raise ValueError(
"Weight matrix does not exist. Model has {0} weight matrices (0-based indexing), but matrix {1} "
"was requested.".format(num_weight_matrices, matrix_id))
return h2o.get_frame(self._model_json["output"]["weights"][matrix_id]["URL"].split("/")[3])
|
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
"""
num_bias_vectors = len(self._model_json["output"]["biases"])
if vector_id not in list(range(num_bias_vectors)):
raise ValueError(
"Bias vector does not exist. Model has {0} bias vectors (0-based indexing), but vector {1} "
"was requested.".format(num_bias_vectors, vector_id))
return h2o.get_frame(self._model_json["output"]["biases"][vector_id]["URL"].split("/")[3])
|
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 if test_data is not None.
:param bool train: Report the training metrics for the model.
:param bool valid: Report the validation metrics for the model.
:param bool xval: Report the cross-validation metrics for the model. If train and valid are True, then it
defaults to True.
:returns: An object of class H2OModelMetrics.
"""
if test_data is None:
if not train and not valid and not xval: train = True # default to train
if train: return self._model_json["output"]["training_metrics"]
if valid: return self._model_json["output"]["validation_metrics"]
if xval: return self._model_json["output"]["cross_validation_metrics"]
else: # cases dealing with test_data not None
if not isinstance(test_data, h2o.H2OFrame):
raise ValueError("`test_data` must be of type H2OFrame. Got: " + type(test_data))
if (self._model_json["response_column_name"] != None) and not(self._model_json["response_column_name"] in test_data.names):
print("WARNING: Model metrics cannot be calculated and metric_json is empty due to the absence of the response column in your dataset.")
return
res = h2o.api("POST /3/ModelMetrics/models/%s/frames/%s" % (self.model_id, test_data.frame_id))
# FIXME need to do the client-side filtering... (PUBDEV-874)
raw_metrics = None
for mm in res["model_metrics"]:
if mm["frame"] is not None and mm["frame"]["name"] == test_data.frame_id:
raw_metrics = mm
break
return self._metrics_class(raw_metrics, algo=self._model_json["algo"])
|
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["scoring_history"].as_data_frame()
print("No score history for this model")
|
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 H2OEstimator has been removed.")
return
model = self._model_json["output"]
print("Model Details")
print("=============")
print(self.__class__.__name__, ": ", self._model_json["algo_full_name"])
print("Model Key: ", self._id)
self.summary()
print()
# training metrics
tm = model["training_metrics"]
if tm: tm.show()
vm = model["validation_metrics"]
if vm: vm.show()
xm = model["cross_validation_metrics"]
if xm: xm.show()
xms = model["cross_validation_metrics_summary"]
if xms: xms.show()
if "scoring_history" in model and model["scoring_history"]:
model["scoring_history"].show()
if "variable_importances" in model and model["variable_importances"]:
model["variable_importances"].show()
|
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["output"]
if self.algo=='glm' or "variable_importances" in list(model.keys()) and model["variable_importances"]:
if self.algo=='glm':
tempvals = model["standardized_coefficient_magnitudes"].cell_values
maxVal = 0
sum=0
for item in tempvals:
sum=sum+item[1]
if item[1]>maxVal:
maxVal = item[1]
vals = []
for item in tempvals:
tempT = (item[0], item[1], item[1]/maxVal, item[1]/sum)
vals.append(tempT)
header = ["variable", "relative_importance", "scaled_importance", "percentage"]
else:
vals = model["variable_importances"].cell_values
header = model["variable_importances"].col_header
if use_pandas and can_use_pandas():
import pandas
return pandas.DataFrame(vals, columns=header)
else:
return vals
else:
print("Warning: This model doesn't have variable importances")
|
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
is selected by default.
:param bool valid: Get the residual dof for the validation set. If both train and valid are True, then train
is selected by default.
:returns: Return the residual dof, or None if it is not present.
"""
if xval: raise H2OValueError("Cross-validation metrics are not available.")
if not train and not valid: train = True
if train and valid: train = True
if train:
return self._model_json["output"]["training_metrics"].residual_degrees_of_freedom()
else:
return self._model_json["output"]["validation_metrics"].residual_degrees_of_freedom()
|
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 tbl is None:
return None
return {name: coef for name, coef in zip(tbl["names"], tbl["coefficients"])}
|
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 = self._model_json["output"]["standardized_coefficient_magnitudes"]
if tbl is None:
return None
return {name: coef for name, coef in zip(tbl["names"], tbl["coefficients"])}
else:
tbl = self._model_json["output"]["coefficients_table"]
if tbl is None:
return None
return {name: coef for name, coef in zip(tbl["names"], tbl["standardized_coefficients"])}
|
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.
:param get_genmodel_jar: if True, then also download h2o-genmodel.jar and store it in folder ``path``.
:param genmodel_name Custom name of genmodel jar
:returns: name of the POJO file written.
"""
assert_is_type(path, str)
assert_is_type(get_genmodel_jar, bool)
path = path.rstrip("/")
return h2o.download_pojo(self, path, get_jar=get_genmodel_jar, jar_name=genmodel_name)
|
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``.
:param genmodel_name Custom name of genmodel jar
:returns: name of the MOJO file written.
"""
assert_is_type(path, str)
assert_is_type(get_genmodel_jar, bool)
if not self.have_mojo:
raise H2OValueError("Export to MOJO not supported")
if get_genmodel_jar:
if genmodel_name == "":
h2o.api("GET /3/h2o-genmodel.jar", save_to=os.path.join(path, "h2o-genmodel.jar"))
else:
h2o.api("GET /3/h2o-genmodel.jar", save_to=os.path.join(path, genmodel_name))
return h2o.api("GET /3/Models/%s/mojo" % self.model_id, save_to=path)
|
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, or throw exception if set to False.
:returns str: the path of the saved model
"""
assert_is_type(path, str)
assert_is_type(force, bool)
if not self.have_mojo:
raise H2OValueError("Export to MOJO not supported")
path = os.path.join(os.getcwd() if path == "" else path, self.model_id + ".zip")
return h2o.api("GET /99/Models.mojo/%s" % self.model_id, data={"dir": path, "force": force})["dir"]
|
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 case it exists, or throw exception if set to False.
:returns str: the path of the saved model details
"""
assert_is_type(path, str)
assert_is_type(force, bool)
path = os.path.join(os.getcwd() if path == "" else path, self.model_id + ".json")
return h2o.api("GET /99/Models/%s/json" % self.model_id, data={"dir": path, "force": force})["dir"]
|
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 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.
:param H2OFrame data: An H2OFrame object used for scoring and constructing the plot.
:param cols: Feature(s) for which partial dependence will be calculated.
:param destination_key: An key reference to the created partial dependence tables in H2O.
:param nbins: Number of bins used. For categorical columns make sure the number of bins exceed the level count. If you enable add_missing_NA, the returned length will be nbin+1.
:param weight_column: A string denoting which column of data should be used as the weight column.
:param plot: A boolean specifying whether to plot partial dependence table.
:param plot_stddev: A boolean specifying whether to add std err to partial dependence plot.
:param figsize: Dimension/size of the returning plots, adjust to fit your output cells.
:param server: ?
:param include_na: A boolean specifying whether missing value should be included in the Feature values.
:param user_splits: a dictionary containing column names as key and user defined split values as value in a list.
:param save_to_file Fully qualified name to an image file the resulting plot should be saved to, e.g. '/home/user/pdpplot.png'. The 'png' postfix might be omitted. If the file already exists, it will be overridden. Plot is only saved if plot = True.
:returns: Plot and list of calculated mean response tables for each feature requested.
"""
if not isinstance(data, h2o.H2OFrame): raise ValueError("data must be an instance of H2OFrame")
assert_is_type(cols, [str])
assert_is_type(destination_key, None, str)
assert_is_type(nbins, int)
assert_is_type(plot, bool)
assert_is_type(figsize, (int, int))
# Check cols specified exist in frame data
for xi in cols:
if xi not in data.names:
raise H2OValueError("Column %s does not exist in the training frame" % xi)
if isinstance(weight_column, int) and not (weight_column == -1):
raise H2OValueError("Weight column should be a column name in your data frame.")
elif isinstance(weight_column, str): # index is a name
if weight_column not in data.names:
raise H2OValueError("Column %s does not exist in the data frame" % weight_column)
weight_column = data.names.index(weight_column)
kwargs = {}
kwargs["cols"] = cols
kwargs["model_id"] = self.model_id
kwargs["frame_id"] = data.frame_id
kwargs["nbins"] = nbins
kwargs["destination_key"] = destination_key
kwargs["weight_column_index"] = weight_column
kwargs["add_missing_na"] = include_na
# extract user defined split points from dict user_splits into an integer array of column indices
# and a double array of user define values for the corresponding columns
if not(user_splits == None):
if not(isinstance(user_splits, dict)):
raise H2OValueError("user_splits must be a Python dict.")
else:
if len(user_splits)>0: # do nothing with an empty dict
user_cols = []
user_values = []
user_num_splits = []
data_ncol = data.ncol
column_names = data.names
for colKey,val in user_splits.items():
if is_type(colKey, str) and colKey in column_names:
user_cols.append(colKey)
elif isinstance(colKey, int) and colKey < data_ncol:
user_cols.append(column_names[colKey])
else:
raise H2OValueError("column names/indices used in user_splits are not valid. They "
"should be chosen from the columns of your data set.")
if data[colKey].isfactor()[0] or data[colKey].isnumeric()[0]: # replace enum string with actual value
nVal = len(val)
if data[colKey].isfactor()[0]:
domains = data[colKey].levels()[0]
numVal = [0]*nVal
for ind in range(nVal):
if (val[ind] in domains):
numVal[ind] = domains.index(val[ind])
else:
raise H2OValueError("Illegal enum value {0} encountered. To include missing"
" values in your feature values, set include_na to "
"True".format(val[ind]))
user_values.extend(numVal)
else:
user_values.extend(val)
user_num_splits.append(nVal)
else:
raise H2OValueError("Partial dependency plots are generated for numerical and categorical "
"columns only.")
kwargs["user_cols"] = user_cols
kwargs["user_splits"] = user_values
kwargs["num_user_splits"] = user_num_splits
else:
kwargs["user_cols"] = None
kwargs["user_splits"] = None
kwargs["num_user_splits"] = None
json = H2OJob(h2o.api("POST /3/PartialDependence/", data=kwargs), job_type="PartialDependencePlot").poll()
json = h2o.api("GET /3/PartialDependence/%s" % json.dest_key)
# Extract partial dependence data from json response
pps = json["partial_dependence_data"]
# Plot partial dependence plots using matplotlib
if plot:
plt = _get_matplotlib_pyplot(server)
if not plt: return
fig, axs = plt.subplots(len(cols), squeeze=False, figsize=figsize)
for i, pp in enumerate(pps):
# Check weather column was categorical or numeric
col = cols[i]
cat = data[col].isfactor()[0]
upper = [a + b for a, b in zip(pp[1], pp[2]) ]
lower = [a - b for a, b in zip(pp[1], pp[2]) ]
if cat:
labels = pp[0]
x = range(len(labels))
y = pp[1]
axs[i, 0].plot(x, y, "ro")
if plot_stddev:
axs[i, 0].plot(x, lower, 'b--')
axs[i, 0].plot(x, upper, 'b--')
axs[i, 0].set_ylim(min(lower) - 0.1*abs(min(lower)), max(upper) + 0.1*abs(max(upper)))
axs[i, 0].set_xticks(x)
axs[i, 0].set_xticklabels(labels)
axs[i, 0].margins(0.2)
else:
x = pp[0]
y = pp[1]
axs[i, 0].plot(x, y, "r-")
if plot_stddev:
axs[i, 0].plot(x, lower, 'b--')
axs[i, 0].plot(x, upper, 'b--')
axs[i, 0].set_xlim(min(x), max(x))
axs[i, 0].set_ylim(min(lower) - 0.1*abs(min(lower)), max(upper) + 0.1*abs(max(upper)))
axs[i, 0].set_title("Partial Dependence Plot For {}".format(col))
axs[i, 0].set_xlabel(pp.col_header[0])
axs[i, 0].set_ylabel(pp.col_header[1])
axs[i, 0].xaxis.grid()
axs[i, 0].yaxis.grid()
if len(col) > 1:
fig.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
if(save_to_file is not None):
plt.savefig(save_to_file)
return pps
|
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_is_type(num_of_features, None, int)
assert_is_type(server, bool)
plt = _get_matplotlib_pyplot(server)
if not plt: return
# get the variable importances as a list of tuples, do not use pandas dataframe
importances = self.varimp(use_pandas=False)
# features labels correspond to the first value of each tuple in the importances list
feature_labels = [tup[0] for tup in importances]
# relative importances correspond to the first value of each tuple in the importances list
scaled_importances = [tup[2] for tup in importances]
# specify bar centers on the y axis, but flip the order so largest bar appears at top
pos = range(len(feature_labels))[::-1]
# specify the bar lengths
val = scaled_importances
# # check that num_of_features is an integer
# if num_of_features is None:
# num_of_features = len(val)
# default to 10 or less features if num_of_features is not specified
if num_of_features is None:
num_of_features = min(len(val), 10)
fig, ax = plt.subplots(1, 1, figsize=(14, 10))
# create separate plot for the case where num_of_features == 1
if num_of_features == 1:
plt.barh(pos[0:num_of_features], val[0:num_of_features], align="center",
height=0.8, color="#1F77B4", edgecolor="none")
# Hide the right and top spines, color others grey
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_color("#7B7B7B")
ax.spines["left"].set_color("#7B7B7B")
# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position("left")
ax.xaxis.set_ticks_position("bottom")
plt.yticks(pos[0:num_of_features], feature_labels[0:num_of_features])
ax.margins(None, 0.5)
else:
plt.barh(pos[0:num_of_features], val[0:num_of_features], align="center",
height=0.8, color="#1F77B4", edgecolor="none")
# Hide the right and top spines, color others grey
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_color("#7B7B7B")
ax.spines["left"].set_color("#7B7B7B")
# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position("left")
ax.xaxis.set_ticks_position("bottom")
plt.yticks(pos[0:num_of_features], feature_labels[0:num_of_features])
plt.ylim([min(pos[0:num_of_features])- 1, max(pos[0:num_of_features])+1])
# ax.margins(y=0.5)
# check which algorithm was used to select right plot title
if self._model_json["algo"] == "gbm":
plt.title("Variable Importance: H2O GBM", fontsize=20)
if not server: plt.show()
elif self._model_json["algo"] == "drf":
plt.title("Variable Importance: H2O DRF", fontsize=20)
if not server: plt.show()
elif self._model_json["algo"] == "xgboost":
plt.title("Variable Importance: H2O XGBoost", fontsize=20)
if not server: plt.show()
# if H2ODeepLearningEstimator has variable_importances == True
elif self._model_json["algo"] == "deeplearning":
plt.title("Variable Importance: H2O Deep Learning", fontsize=20)
if not server: plt.show()
elif self._model_json["algo"] == "glm":
plt.title("Variable Importance: H2O GLM", fontsize=20)
if not server: plt.show()
else:
raise H2OValueError("A variable importances plot is not implemented for this type of model")
|
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, I(int, lambda x: x > 0))
# check that model is a glm
if self._model_json["algo"] != "glm":
raise H2OValueError("This function is available for GLM models only")
plt = _get_matplotlib_pyplot(server)
if not plt: return
# get unsorted tuple of labels and coefficients
unsorted_norm_coef = self.coef_norm().items()
# drop intercept value then sort tuples by the coefficient"s absolute value
drop_intercept = [tup for tup in unsorted_norm_coef if tup[0] != "Intercept"]
norm_coef = sorted(drop_intercept, key=lambda x: abs(x[1]), reverse=True)
signage = []
for element in norm_coef:
# if positive including zero, color blue, else color orange (use same colors as Flow)
if element[1] >= 0:
signage.append("#1F77B4") # blue
else:
signage.append("#FF7F0E") # dark orange
# get feature labels and their corresponding magnitudes
feature_labels = [tup[0] for tup in norm_coef]
norm_coef_magn = [abs(tup[1]) for tup in norm_coef]
# specify bar centers on the y axis, but flip the order so largest bar appears at top
pos = range(len(feature_labels))[::-1]
# specify the bar lengths
val = norm_coef_magn
# check number of features, default is all the features
if num_of_features is None:
num_of_features = len(val)
# plot horizontal plot
fig, ax = plt.subplots(1, 1, figsize=(14, 10))
# create separate plot for the case where num_of_features = 1
if num_of_features == 1:
plt.barh(pos[0], val[0],
align="center", height=0.8, color=signage[0], edgecolor="none")
# Hide the right and top spines, color others grey
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_color("#7B7B7B")
ax.spines["left"].set_color("#7B7B7B")
# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position("left")
ax.xaxis.set_ticks_position("bottom")
plt.yticks([0], feature_labels[0])
ax.margins(None, 0.5)
else:
plt.barh(pos[0:num_of_features], val[0:num_of_features],
align="center", height=0.8, color=signage[0:num_of_features], edgecolor="none")
# Hide the right and top spines, color others grey
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_color("#7B7B7B")
ax.spines["left"].set_color("#7B7B7B")
# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position("left")
ax.xaxis.set_ticks_position("bottom")
plt.yticks(pos[0:num_of_features], feature_labels[0:num_of_features])
ax.margins(None, 0.05)
# generate custom fake lines that will be used as legend entries:
# check if positive and negative values exist
# if positive create positive legend
if "#1F77B4" in signage[0:num_of_features] and "#FF7F0E" not in signage[0:num_of_features]:
color_ids = ("Positive",)
markers = [plt.Line2D([0, 0], [0, 0], color=color, marker="s", linestyle="")
for color in signage[0:num_of_features]]
lgnd = plt.legend(markers, color_ids, numpoints=1, loc="best", frameon=False, fontsize=13)
lgnd.legendHandles[0]._legmarker.set_markersize(10)
# if neg create neg legend
elif "#FF7F0E" in signage[0:num_of_features] and "#1F77B4" not in signage[0:num_of_features]:
color_ids = ("Negative",)
markers = [plt.Line2D([0, 0], [0, 0], color=color, marker="s", linestyle="")
for color in set(signage[0:num_of_features])]
lgnd = plt.legend(markers, color_ids, numpoints=1, loc="best", frameon=False, fontsize=13)
lgnd.legendHandles[0]._legmarker.set_markersize(10)
# if both provide both colors in legend
else:
color_ids = ("Positive", "Negative")
markers = [plt.Line2D([0, 0], [0, 0], color=color, marker="s", linestyle="")
for color in ['#1F77B4', '#FF7F0E']] # blue should always be positive, orange negative
lgnd = plt.legend(markers, color_ids, numpoints=1, loc="best", frameon=False, fontsize=13)
lgnd.legendHandles[0]._legmarker.set_markersize(10)
lgnd.legendHandles[1]._legmarker.set_markersize(10)
# Hide the right and top spines, color others grey
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_color("#7B7B7B")
ax.spines["left"].set_color("#7B7B7B")
# Only show ticks on the left and bottom spines
# ax.yaxis.set_ticks_position("left")
# ax.xaxis.set_ticks_position("bottom")
plt.yticks(pos[0:num_of_features], feature_labels[0:num_of_features])
plt.tick_params(axis="x", which="minor", bottom="off", top="off", labelbottom="off")
plt.title("Standardized Coef. Magnitudes: H2O GLM", fontsize=20)
# plt.axis("tight")
# show plot
if not server: plt.show()
|
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: [{},{}]".format(len(y_actual), len(y_predicted)))
|
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(h2o.get_model(p["name"]))
return m
|
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.
"""
preds = self._model_json["output"]["cross_validation_predictions"]
if preds is None: return None
m = []
for p in preds: m.append(h2o.get_frame(p["name"]))
return m
|
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 GLM
from the training set, and makes predictions for the test set.
Finally, default performance metrics are displayed.
"""
go()
# Connect to H2O
h2o.init()
go()
# Upload the prostate dataset that comes included in the h2o python package
prostate = h2o.load_dataset("prostate")
go()
# Print a description of the prostate data
prostate.describe()
go()
# Randomly split the dataset into ~70/30, training/test sets
train, test = prostate.split_frame(ratios=[0.70])
go()
# Convert the response columns to factors (for binary classification problems)
train["CAPSULE"] = train["CAPSULE"].asfactor()
test["CAPSULE"] = test["CAPSULE"].asfactor()
go()
# Build a (classification) GLM
from h2o.estimators import H2OGradientBoostingEstimator
prostate_gbm = H2OGradientBoostingEstimator(distribution="bernoulli", ntrees=10, max_depth=8,
min_rows=10, learn_rate=0.2)
prostate_gbm.train(x=["AGE", "RACE", "PSA", "VOL", "GLEASON"],
y="CAPSULE", training_frame=train)
go()
# Show the model
prostate_gbm.show()
go()
# Predict on the test set and show the first ten predictions
predictions = prostate_gbm.predict(test)
predictions.show()
go()
# Fetch a tree, print number of tree nodes, show root node description
from h2o.tree import H2OTree, H2ONode
tree = H2OTree(prostate_gbm, 0, "0")
len(tree)
tree.left_children
tree.right_children
tree.root_node.show()
go()
# Show default performance metrics
performance = prostate_gbm.model_performance(test)
performance.show()
# Execute:
_run_demo(demo_body, interactive, echo, testing)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.