repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/utils.py | _sanitize_value | def _sanitize_value(x):
"""
Performs cleaning steps on the data so various type comparisons can
be performed correctly.
"""
if isinstance(x, _six.string_types + _six.integer_types + (float,)):
return x
elif _HAS_SKLEARN and _sp.issparse(x):
return x.todense()
elif isinstance(x, _np.ndarray):
return x
elif isinstance(x, tuple):
return (_sanitize_value(v) for v in x)
elif isinstance(x, list):
return [_sanitize_value(v) for v in x]
elif isinstance(x, dict):
return dict( (_sanitize_value(k), _sanitize_value(v)) for k, v in x.items())
else:
assert False, str(x) | python | def _sanitize_value(x):
"""
Performs cleaning steps on the data so various type comparisons can
be performed correctly.
"""
if isinstance(x, _six.string_types + _six.integer_types + (float,)):
return x
elif _HAS_SKLEARN and _sp.issparse(x):
return x.todense()
elif isinstance(x, _np.ndarray):
return x
elif isinstance(x, tuple):
return (_sanitize_value(v) for v in x)
elif isinstance(x, list):
return [_sanitize_value(v) for v in x]
elif isinstance(x, dict):
return dict( (_sanitize_value(k), _sanitize_value(v)) for k, v in x.items())
else:
assert False, str(x) | [
"def",
"_sanitize_value",
"(",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"_six",
".",
"string_types",
"+",
"_six",
".",
"integer_types",
"+",
"(",
"float",
",",
")",
")",
":",
"return",
"x",
"elif",
"_HAS_SKLEARN",
"and",
"_sp",
".",
"issparse",
"(",
"x",
")",
":",
"return",
"x",
".",
"todense",
"(",
")",
"elif",
"isinstance",
"(",
"x",
",",
"_np",
".",
"ndarray",
")",
":",
"return",
"x",
"elif",
"isinstance",
"(",
"x",
",",
"tuple",
")",
":",
"return",
"(",
"_sanitize_value",
"(",
"v",
")",
"for",
"v",
"in",
"x",
")",
"elif",
"isinstance",
"(",
"x",
",",
"list",
")",
":",
"return",
"[",
"_sanitize_value",
"(",
"v",
")",
"for",
"v",
"in",
"x",
"]",
"elif",
"isinstance",
"(",
"x",
",",
"dict",
")",
":",
"return",
"dict",
"(",
"(",
"_sanitize_value",
"(",
"k",
")",
",",
"_sanitize_value",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"x",
".",
"items",
"(",
")",
")",
"else",
":",
"assert",
"False",
",",
"str",
"(",
"x",
")"
] | Performs cleaning steps on the data so various type comparisons can
be performed correctly. | [
"Performs",
"cleaning",
"steps",
"on",
"the",
"data",
"so",
"various",
"type",
"comparisons",
"can",
"be",
"performed",
"correctly",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/utils.py#L677-L695 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/utils.py | _element_equal | def _element_equal(x, y):
"""
Performs a robust equality test between elements.
"""
if isinstance(x, _np.ndarray) or isinstance(y, _np.ndarray):
try:
return (abs(_np.asarray(x) - _np.asarray(y)) < 1e-5).all()
except:
return False
elif isinstance(x, dict):
return (isinstance(y, dict)
and _element_equal(x.keys(), y.keys())
and all(_element_equal(x[k], y[k]) for k in x.keys()))
elif isinstance(x, float):
return abs(x - y) < 1e-5 * (abs(x) + abs(y))
elif isinstance(x, (list, tuple)):
return x == y
else:
return bool(x == y) | python | def _element_equal(x, y):
"""
Performs a robust equality test between elements.
"""
if isinstance(x, _np.ndarray) or isinstance(y, _np.ndarray):
try:
return (abs(_np.asarray(x) - _np.asarray(y)) < 1e-5).all()
except:
return False
elif isinstance(x, dict):
return (isinstance(y, dict)
and _element_equal(x.keys(), y.keys())
and all(_element_equal(x[k], y[k]) for k in x.keys()))
elif isinstance(x, float):
return abs(x - y) < 1e-5 * (abs(x) + abs(y))
elif isinstance(x, (list, tuple)):
return x == y
else:
return bool(x == y) | [
"def",
"_element_equal",
"(",
"x",
",",
"y",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"_np",
".",
"ndarray",
")",
"or",
"isinstance",
"(",
"y",
",",
"_np",
".",
"ndarray",
")",
":",
"try",
":",
"return",
"(",
"abs",
"(",
"_np",
".",
"asarray",
"(",
"x",
")",
"-",
"_np",
".",
"asarray",
"(",
"y",
")",
")",
"<",
"1e-5",
")",
".",
"all",
"(",
")",
"except",
":",
"return",
"False",
"elif",
"isinstance",
"(",
"x",
",",
"dict",
")",
":",
"return",
"(",
"isinstance",
"(",
"y",
",",
"dict",
")",
"and",
"_element_equal",
"(",
"x",
".",
"keys",
"(",
")",
",",
"y",
".",
"keys",
"(",
")",
")",
"and",
"all",
"(",
"_element_equal",
"(",
"x",
"[",
"k",
"]",
",",
"y",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"x",
".",
"keys",
"(",
")",
")",
")",
"elif",
"isinstance",
"(",
"x",
",",
"float",
")",
":",
"return",
"abs",
"(",
"x",
"-",
"y",
")",
"<",
"1e-5",
"*",
"(",
"abs",
"(",
"x",
")",
"+",
"abs",
"(",
"y",
")",
")",
"elif",
"isinstance",
"(",
"x",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"x",
"==",
"y",
"else",
":",
"return",
"bool",
"(",
"x",
"==",
"y",
")"
] | Performs a robust equality test between elements. | [
"Performs",
"a",
"robust",
"equality",
"test",
"between",
"elements",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/utils.py#L698-L716 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/utils.py | evaluate_transformer | def evaluate_transformer(model, input_data, reference_output,
verbose=False):
"""
Evaluate a transformer specification for testing.
Parameters
----------
spec: [str | MLModel]
File from where to load the Model from (OR) a loaded
version of MLModel.
input_data: list[dict]
Test data on which to evaluate the models.
reference_output: list[dict]
Expected results for the model.
verbose: bool
Verbosity levels of the predictions.
Examples
--------
.. sourcecode:: python
>>> input_data = [{'input_1': 1, 'input_2': 2}, {'input_1': 3, 'input_2': 3}]
>>> expected_output = [{'input_1': 2.5, 'input_2': 2.0}, {'input_1': 1.3, 'input_2': 2.3}]
>>> metrics = coremltools.utils.evaluate_transformer(scaler_spec, input_data, expected_output)
See Also
--------
evaluate_regressor, evaluate_classifier
"""
model = _get_model(model)
if verbose:
print(model)
print("")
print("Other Framework\t\tPredicted")
num_errors = 0
for index, row in enumerate(input_data):
assert isinstance(row, dict)
sanitized_row = _sanitize_value(row)
ref_data = _sanitize_value(reference_output[index])
if verbose:
print("Input:\n\t", str(row))
print("Correct output:\n\t", str(ref_data))
predicted = _sanitize_value(model.predict(sanitized_row))
assert isinstance(ref_data, dict)
assert isinstance(predicted, dict)
predicted_trimmed = dict( (k, predicted[k]) for k in ref_data.keys())
if verbose:
print("Predicted:\n\t", str(predicted_trimmed))
if not _element_equal(predicted_trimmed, ref_data):
num_errors += 1
ret = {
"num_samples": len(input_data),
"num_errors": num_errors
}
if verbose:
print("results: %s" % ret)
return ret | python | def evaluate_transformer(model, input_data, reference_output,
verbose=False):
"""
Evaluate a transformer specification for testing.
Parameters
----------
spec: [str | MLModel]
File from where to load the Model from (OR) a loaded
version of MLModel.
input_data: list[dict]
Test data on which to evaluate the models.
reference_output: list[dict]
Expected results for the model.
verbose: bool
Verbosity levels of the predictions.
Examples
--------
.. sourcecode:: python
>>> input_data = [{'input_1': 1, 'input_2': 2}, {'input_1': 3, 'input_2': 3}]
>>> expected_output = [{'input_1': 2.5, 'input_2': 2.0}, {'input_1': 1.3, 'input_2': 2.3}]
>>> metrics = coremltools.utils.evaluate_transformer(scaler_spec, input_data, expected_output)
See Also
--------
evaluate_regressor, evaluate_classifier
"""
model = _get_model(model)
if verbose:
print(model)
print("")
print("Other Framework\t\tPredicted")
num_errors = 0
for index, row in enumerate(input_data):
assert isinstance(row, dict)
sanitized_row = _sanitize_value(row)
ref_data = _sanitize_value(reference_output[index])
if verbose:
print("Input:\n\t", str(row))
print("Correct output:\n\t", str(ref_data))
predicted = _sanitize_value(model.predict(sanitized_row))
assert isinstance(ref_data, dict)
assert isinstance(predicted, dict)
predicted_trimmed = dict( (k, predicted[k]) for k in ref_data.keys())
if verbose:
print("Predicted:\n\t", str(predicted_trimmed))
if not _element_equal(predicted_trimmed, ref_data):
num_errors += 1
ret = {
"num_samples": len(input_data),
"num_errors": num_errors
}
if verbose:
print("results: %s" % ret)
return ret | [
"def",
"evaluate_transformer",
"(",
"model",
",",
"input_data",
",",
"reference_output",
",",
"verbose",
"=",
"False",
")",
":",
"model",
"=",
"_get_model",
"(",
"model",
")",
"if",
"verbose",
":",
"print",
"(",
"model",
")",
"print",
"(",
"\"\"",
")",
"print",
"(",
"\"Other Framework\\t\\tPredicted\"",
")",
"num_errors",
"=",
"0",
"for",
"index",
",",
"row",
"in",
"enumerate",
"(",
"input_data",
")",
":",
"assert",
"isinstance",
"(",
"row",
",",
"dict",
")",
"sanitized_row",
"=",
"_sanitize_value",
"(",
"row",
")",
"ref_data",
"=",
"_sanitize_value",
"(",
"reference_output",
"[",
"index",
"]",
")",
"if",
"verbose",
":",
"print",
"(",
"\"Input:\\n\\t\"",
",",
"str",
"(",
"row",
")",
")",
"print",
"(",
"\"Correct output:\\n\\t\"",
",",
"str",
"(",
"ref_data",
")",
")",
"predicted",
"=",
"_sanitize_value",
"(",
"model",
".",
"predict",
"(",
"sanitized_row",
")",
")",
"assert",
"isinstance",
"(",
"ref_data",
",",
"dict",
")",
"assert",
"isinstance",
"(",
"predicted",
",",
"dict",
")",
"predicted_trimmed",
"=",
"dict",
"(",
"(",
"k",
",",
"predicted",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"ref_data",
".",
"keys",
"(",
")",
")",
"if",
"verbose",
":",
"print",
"(",
"\"Predicted:\\n\\t\"",
",",
"str",
"(",
"predicted_trimmed",
")",
")",
"if",
"not",
"_element_equal",
"(",
"predicted_trimmed",
",",
"ref_data",
")",
":",
"num_errors",
"+=",
"1",
"ret",
"=",
"{",
"\"num_samples\"",
":",
"len",
"(",
"input_data",
")",
",",
"\"num_errors\"",
":",
"num_errors",
"}",
"if",
"verbose",
":",
"print",
"(",
"\"results: %s\"",
"%",
"ret",
")",
"return",
"ret"
] | Evaluate a transformer specification for testing.
Parameters
----------
spec: [str | MLModel]
File from where to load the Model from (OR) a loaded
version of MLModel.
input_data: list[dict]
Test data on which to evaluate the models.
reference_output: list[dict]
Expected results for the model.
verbose: bool
Verbosity levels of the predictions.
Examples
--------
.. sourcecode:: python
>>> input_data = [{'input_1': 1, 'input_2': 2}, {'input_1': 3, 'input_2': 3}]
>>> expected_output = [{'input_1': 2.5, 'input_2': 2.0}, {'input_1': 1.3, 'input_2': 2.3}]
>>> metrics = coremltools.utils.evaluate_transformer(scaler_spec, input_data, expected_output)
See Also
--------
evaluate_regressor, evaluate_classifier | [
"Evaluate",
"a",
"transformer",
"specification",
"for",
"testing",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/utils.py#L719-L786 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/utils.py | _get_input_names | def _get_input_names(spec):
"""
Returns a list of the names of the inputs to this model.
:param spec: The model protobuf specification
:return: [str] A list of input feature names
"""
retval = [feature.name for feature in spec.description.input]
return retval | python | def _get_input_names(spec):
"""
Returns a list of the names of the inputs to this model.
:param spec: The model protobuf specification
:return: [str] A list of input feature names
"""
retval = [feature.name for feature in spec.description.input]
return retval | [
"def",
"_get_input_names",
"(",
"spec",
")",
":",
"retval",
"=",
"[",
"feature",
".",
"name",
"for",
"feature",
"in",
"spec",
".",
"description",
".",
"input",
"]",
"return",
"retval"
] | Returns a list of the names of the inputs to this model.
:param spec: The model protobuf specification
:return: [str] A list of input feature names | [
"Returns",
"a",
"list",
"of",
"the",
"names",
"of",
"the",
"inputs",
"to",
"this",
"model",
".",
":",
"param",
"spec",
":",
"The",
"model",
"protobuf",
"specification",
":",
"return",
":",
"[",
"str",
"]",
"A",
"list",
"of",
"input",
"feature",
"names"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/utils.py#L912-L919 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/graph_analytics/degree_counting.py | create | def create(graph, verbose=True):
"""
Compute the in degree, out degree and total degree of each vertex.
Parameters
----------
graph : SGraph
The graph on which to compute degree counts.
verbose : bool, optional
If True, print progress updates.
Returns
-------
out : DegreeCountingModel
Examples
--------
If given an :class:`~turicreate.SGraph` ``g``, we can create
a :class:`~turicreate.degree_counting.DegreeCountingModel` as follows:
>>> g = turicreate.load_sgraph('http://snap.stanford.edu/data/web-Google.txt.gz',
... format='snap')
>>> m = turicreate.degree_counting.create(g)
>>> g2 = m['graph']
>>> g2
SGraph({'num_edges': 5105039, 'num_vertices': 875713})
Vertex Fields:['__id', 'in_degree', 'out_degree', 'total_degree']
Edge Fields:['__src_id', '__dst_id']
>>> g2.vertices.head(5)
Columns:
__id int
in_degree int
out_degree int
total_degree int
<BLANKLINE>
Rows: 5
<BLANKLINE>
Data:
+------+-----------+------------+--------------+
| __id | in_degree | out_degree | total_degree |
+------+-----------+------------+--------------+
| 5 | 15 | 7 | 22 |
| 7 | 3 | 16 | 19 |
| 8 | 1 | 2 | 3 |
| 10 | 13 | 11 | 24 |
| 27 | 19 | 16 | 35 |
+------+-----------+------------+--------------+
See Also
--------
DegreeCountingModel
"""
from turicreate._cython.cy_server import QuietProgress
if not isinstance(graph, _SGraph):
raise TypeError('"graph" input must be a SGraph object.')
with QuietProgress(verbose):
params = _tc.extensions._toolkits.graph.degree_count.create(
{'graph': graph.__proxy__})
return DegreeCountingModel(params['model']) | python | def create(graph, verbose=True):
"""
Compute the in degree, out degree and total degree of each vertex.
Parameters
----------
graph : SGraph
The graph on which to compute degree counts.
verbose : bool, optional
If True, print progress updates.
Returns
-------
out : DegreeCountingModel
Examples
--------
If given an :class:`~turicreate.SGraph` ``g``, we can create
a :class:`~turicreate.degree_counting.DegreeCountingModel` as follows:
>>> g = turicreate.load_sgraph('http://snap.stanford.edu/data/web-Google.txt.gz',
... format='snap')
>>> m = turicreate.degree_counting.create(g)
>>> g2 = m['graph']
>>> g2
SGraph({'num_edges': 5105039, 'num_vertices': 875713})
Vertex Fields:['__id', 'in_degree', 'out_degree', 'total_degree']
Edge Fields:['__src_id', '__dst_id']
>>> g2.vertices.head(5)
Columns:
__id int
in_degree int
out_degree int
total_degree int
<BLANKLINE>
Rows: 5
<BLANKLINE>
Data:
+------+-----------+------------+--------------+
| __id | in_degree | out_degree | total_degree |
+------+-----------+------------+--------------+
| 5 | 15 | 7 | 22 |
| 7 | 3 | 16 | 19 |
| 8 | 1 | 2 | 3 |
| 10 | 13 | 11 | 24 |
| 27 | 19 | 16 | 35 |
+------+-----------+------------+--------------+
See Also
--------
DegreeCountingModel
"""
from turicreate._cython.cy_server import QuietProgress
if not isinstance(graph, _SGraph):
raise TypeError('"graph" input must be a SGraph object.')
with QuietProgress(verbose):
params = _tc.extensions._toolkits.graph.degree_count.create(
{'graph': graph.__proxy__})
return DegreeCountingModel(params['model']) | [
"def",
"create",
"(",
"graph",
",",
"verbose",
"=",
"True",
")",
":",
"from",
"turicreate",
".",
"_cython",
".",
"cy_server",
"import",
"QuietProgress",
"if",
"not",
"isinstance",
"(",
"graph",
",",
"_SGraph",
")",
":",
"raise",
"TypeError",
"(",
"'\"graph\" input must be a SGraph object.'",
")",
"with",
"QuietProgress",
"(",
"verbose",
")",
":",
"params",
"=",
"_tc",
".",
"extensions",
".",
"_toolkits",
".",
"graph",
".",
"degree_count",
".",
"create",
"(",
"{",
"'graph'",
":",
"graph",
".",
"__proxy__",
"}",
")",
"return",
"DegreeCountingModel",
"(",
"params",
"[",
"'model'",
"]",
")"
] | Compute the in degree, out degree and total degree of each vertex.
Parameters
----------
graph : SGraph
The graph on which to compute degree counts.
verbose : bool, optional
If True, print progress updates.
Returns
-------
out : DegreeCountingModel
Examples
--------
If given an :class:`~turicreate.SGraph` ``g``, we can create
a :class:`~turicreate.degree_counting.DegreeCountingModel` as follows:
>>> g = turicreate.load_sgraph('http://snap.stanford.edu/data/web-Google.txt.gz',
... format='snap')
>>> m = turicreate.degree_counting.create(g)
>>> g2 = m['graph']
>>> g2
SGraph({'num_edges': 5105039, 'num_vertices': 875713})
Vertex Fields:['__id', 'in_degree', 'out_degree', 'total_degree']
Edge Fields:['__src_id', '__dst_id']
>>> g2.vertices.head(5)
Columns:
__id int
in_degree int
out_degree int
total_degree int
<BLANKLINE>
Rows: 5
<BLANKLINE>
Data:
+------+-----------+------------+--------------+
| __id | in_degree | out_degree | total_degree |
+------+-----------+------------+--------------+
| 5 | 15 | 7 | 22 |
| 7 | 3 | 16 | 19 |
| 8 | 1 | 2 | 3 |
| 10 | 13 | 11 | 24 |
| 27 | 19 | 16 | 35 |
+------+-----------+------------+--------------+
See Also
--------
DegreeCountingModel | [
"Compute",
"the",
"in",
"degree",
"out",
"degree",
"and",
"total",
"degree",
"of",
"each",
"vertex",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/graph_analytics/degree_counting.py#L57-L119 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/litre/cplusplus.py | Example.replace_emphasis | def replace_emphasis(self, s, index = 0):
"""replace the index'th emphasized text with s"""
e = self.emphasized[index]
self.body[e[0]:e[1]] = [s]
del self.emphasized[index] | python | def replace_emphasis(self, s, index = 0):
"""replace the index'th emphasized text with s"""
e = self.emphasized[index]
self.body[e[0]:e[1]] = [s]
del self.emphasized[index] | [
"def",
"replace_emphasis",
"(",
"self",
",",
"s",
",",
"index",
"=",
"0",
")",
":",
"e",
"=",
"self",
".",
"emphasized",
"[",
"index",
"]",
"self",
".",
"body",
"[",
"e",
"[",
"0",
"]",
":",
"e",
"[",
"1",
"]",
"]",
"=",
"[",
"s",
"]",
"del",
"self",
".",
"emphasized",
"[",
"index",
"]"
] | replace the index'th emphasized text with s | [
"replace",
"the",
"index",
"th",
"emphasized",
"text",
"with",
"s"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/litre/cplusplus.py#L90-L94 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/litre/cplusplus.py | CPlusPlusTranslator._execute | def _execute(self, code):
"""Override of litre._execute; sets up variable context before
evaluating code
"""
self.globals['example'] = self.example
eval(code, self.globals) | python | def _execute(self, code):
"""Override of litre._execute; sets up variable context before
evaluating code
"""
self.globals['example'] = self.example
eval(code, self.globals) | [
"def",
"_execute",
"(",
"self",
",",
"code",
")",
":",
"self",
".",
"globals",
"[",
"'example'",
"]",
"=",
"self",
".",
"example",
"eval",
"(",
"code",
",",
"self",
".",
"globals",
")"
] | Override of litre._execute; sets up variable context before
evaluating code | [
"Override",
"of",
"litre",
".",
"_execute",
";",
"sets",
"up",
"variable",
"context",
"before",
"evaluating",
"code"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/litre/cplusplus.py#L320-L325 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/litre/cplusplus.py | CPlusPlusTranslator.compile | def compile(
self
, howmany = 1
, pop = -1
, expect_error = False
, extension = '.o'
, options = ['-c']
, built_handler = lambda built_file: None
, source_file = None
, source_suffix = '.cpp'
# C-style comments by default; handles C++ and YACC
, make_comment = lambda text: '/*\n%s\n*/' % text
, built_file = None
, command = None
):
"""
Compile examples on the stack, whose topmost item is the last example
seen but not yet handled so far.
:howmany: How many of the topmost examples on the stack to compile.
You can pass a number, or 'all' to indicate that all examples should
be compiled.
:pop: How many of the topmost examples to discard. By default, all of
the examples that are compiled are discarded.
:expect_error: Whether a compilation error is to be expected. Any value
> 1 will cause the expected diagnostic's text to be dumped for
diagnostic purposes. It's common to expect an error but see a
completely unrelated one because of bugs in the example (you can get
this behavior for all examples by setting show_expected_error_output
in your config).
:extension: The extension of the file to build (set to .exe for
run)
:options: Compiler flags
:built_file: A path to use for the built file. By default, a temp
filename is conjured up
:built_handler: A function that's called with the name of the built file
upon success.
:source_file: The full name of the source file to write
:source_suffix: If source_file is None, the suffix to use for the source file
:make_comment: A function that transforms text into an appropriate comment.
:command: A function that is passed (includes, opts, target, source), where
opts is a string representing compiler options, target is the name of
the file to build, and source is the name of the file into which the
example code is written. By default, the function formats
litre.config.compiler with its argument tuple.
"""
# Grab one example by default
if howmany == 'all':
howmany = len(self.stack)
source = '\n'.join(
self.prefix
+ [str(x) for x in self.stack[-howmany:]]
)
source = reduce(lambda s, f: f(s), self.preprocessors, source)
if pop:
if pop < 0:
pop = howmany
del self.stack[-pop:]
if len(self.stack):
self.example = self.stack[-1]
cpp = self._source_file_path(source_file, source_suffix)
if built_file is None:
built_file = self._output_file_path(source_file, extension)
opts = ' '.join(options)
includes = ' '.join(['-I%s' % d for d in self.includes])
if not command:
command = self.config.compiler
if type(command) == str:
command = lambda i, o, t, s, c = command: c % (i, o, t, s)
cmd = command(includes, opts, expand_vars(built_file), expand_vars(cpp))
if expect_error and self.config.show_expected_error_output:
expect_error += 1
comment_cmd = command(includes, opts, built_file, os.path.basename(cpp))
comment = make_comment(config.comment_text(comment_cmd, expect_error))
self._write_source(cpp, '\n'.join([comment, source]))
#print 'wrote in', cpp
#print 'trying command', cmd
status, output = syscmd(cmd, expect_error)
if status or expect_error > 1:
print
if expect_error and expect_error < 2:
print 'Compilation failure expected, but none seen'
print '------------ begin offending source ------------'
print open(cpp).read()
print '------------ end offending source ------------'
if self.config.save_cpp:
print 'saved in', repr(cpp)
else:
self._remove_source(cpp)
sys.stdout.flush()
else:
print '.',
sys.stdout.flush()
built_handler(built_file)
self._remove_source(cpp)
try:
self._unlink(built_file)
except:
if not expect_error:
print 'failed to unlink', built_file
return status | python | def compile(
self
, howmany = 1
, pop = -1
, expect_error = False
, extension = '.o'
, options = ['-c']
, built_handler = lambda built_file: None
, source_file = None
, source_suffix = '.cpp'
# C-style comments by default; handles C++ and YACC
, make_comment = lambda text: '/*\n%s\n*/' % text
, built_file = None
, command = None
):
"""
Compile examples on the stack, whose topmost item is the last example
seen but not yet handled so far.
:howmany: How many of the topmost examples on the stack to compile.
You can pass a number, or 'all' to indicate that all examples should
be compiled.
:pop: How many of the topmost examples to discard. By default, all of
the examples that are compiled are discarded.
:expect_error: Whether a compilation error is to be expected. Any value
> 1 will cause the expected diagnostic's text to be dumped for
diagnostic purposes. It's common to expect an error but see a
completely unrelated one because of bugs in the example (you can get
this behavior for all examples by setting show_expected_error_output
in your config).
:extension: The extension of the file to build (set to .exe for
run)
:options: Compiler flags
:built_file: A path to use for the built file. By default, a temp
filename is conjured up
:built_handler: A function that's called with the name of the built file
upon success.
:source_file: The full name of the source file to write
:source_suffix: If source_file is None, the suffix to use for the source file
:make_comment: A function that transforms text into an appropriate comment.
:command: A function that is passed (includes, opts, target, source), where
opts is a string representing compiler options, target is the name of
the file to build, and source is the name of the file into which the
example code is written. By default, the function formats
litre.config.compiler with its argument tuple.
"""
# Grab one example by default
if howmany == 'all':
howmany = len(self.stack)
source = '\n'.join(
self.prefix
+ [str(x) for x in self.stack[-howmany:]]
)
source = reduce(lambda s, f: f(s), self.preprocessors, source)
if pop:
if pop < 0:
pop = howmany
del self.stack[-pop:]
if len(self.stack):
self.example = self.stack[-1]
cpp = self._source_file_path(source_file, source_suffix)
if built_file is None:
built_file = self._output_file_path(source_file, extension)
opts = ' '.join(options)
includes = ' '.join(['-I%s' % d for d in self.includes])
if not command:
command = self.config.compiler
if type(command) == str:
command = lambda i, o, t, s, c = command: c % (i, o, t, s)
cmd = command(includes, opts, expand_vars(built_file), expand_vars(cpp))
if expect_error and self.config.show_expected_error_output:
expect_error += 1
comment_cmd = command(includes, opts, built_file, os.path.basename(cpp))
comment = make_comment(config.comment_text(comment_cmd, expect_error))
self._write_source(cpp, '\n'.join([comment, source]))
#print 'wrote in', cpp
#print 'trying command', cmd
status, output = syscmd(cmd, expect_error)
if status or expect_error > 1:
print
if expect_error and expect_error < 2:
print 'Compilation failure expected, but none seen'
print '------------ begin offending source ------------'
print open(cpp).read()
print '------------ end offending source ------------'
if self.config.save_cpp:
print 'saved in', repr(cpp)
else:
self._remove_source(cpp)
sys.stdout.flush()
else:
print '.',
sys.stdout.flush()
built_handler(built_file)
self._remove_source(cpp)
try:
self._unlink(built_file)
except:
if not expect_error:
print 'failed to unlink', built_file
return status | [
"def",
"compile",
"(",
"self",
",",
"howmany",
"=",
"1",
",",
"pop",
"=",
"-",
"1",
",",
"expect_error",
"=",
"False",
",",
"extension",
"=",
"'.o'",
",",
"options",
"=",
"[",
"'-c'",
"]",
",",
"built_handler",
"=",
"lambda",
"built_file",
":",
"None",
",",
"source_file",
"=",
"None",
",",
"source_suffix",
"=",
"'.cpp'",
"# C-style comments by default; handles C++ and YACC",
",",
"make_comment",
"=",
"lambda",
"text",
":",
"'/*\\n%s\\n*/'",
"%",
"text",
",",
"built_file",
"=",
"None",
",",
"command",
"=",
"None",
")",
":",
"# Grab one example by default",
"if",
"howmany",
"==",
"'all'",
":",
"howmany",
"=",
"len",
"(",
"self",
".",
"stack",
")",
"source",
"=",
"'\\n'",
".",
"join",
"(",
"self",
".",
"prefix",
"+",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"stack",
"[",
"-",
"howmany",
":",
"]",
"]",
")",
"source",
"=",
"reduce",
"(",
"lambda",
"s",
",",
"f",
":",
"f",
"(",
"s",
")",
",",
"self",
".",
"preprocessors",
",",
"source",
")",
"if",
"pop",
":",
"if",
"pop",
"<",
"0",
":",
"pop",
"=",
"howmany",
"del",
"self",
".",
"stack",
"[",
"-",
"pop",
":",
"]",
"if",
"len",
"(",
"self",
".",
"stack",
")",
":",
"self",
".",
"example",
"=",
"self",
".",
"stack",
"[",
"-",
"1",
"]",
"cpp",
"=",
"self",
".",
"_source_file_path",
"(",
"source_file",
",",
"source_suffix",
")",
"if",
"built_file",
"is",
"None",
":",
"built_file",
"=",
"self",
".",
"_output_file_path",
"(",
"source_file",
",",
"extension",
")",
"opts",
"=",
"' '",
".",
"join",
"(",
"options",
")",
"includes",
"=",
"' '",
".",
"join",
"(",
"[",
"'-I%s'",
"%",
"d",
"for",
"d",
"in",
"self",
".",
"includes",
"]",
")",
"if",
"not",
"command",
":",
"command",
"=",
"self",
".",
"config",
".",
"compiler",
"if",
"type",
"(",
"command",
")",
"==",
"str",
":",
"command",
"=",
"lambda",
"i",
",",
"o",
",",
"t",
",",
"s",
",",
"c",
"=",
"command",
":",
"c",
"%",
"(",
"i",
",",
"o",
",",
"t",
",",
"s",
")",
"cmd",
"=",
"command",
"(",
"includes",
",",
"opts",
",",
"expand_vars",
"(",
"built_file",
")",
",",
"expand_vars",
"(",
"cpp",
")",
")",
"if",
"expect_error",
"and",
"self",
".",
"config",
".",
"show_expected_error_output",
":",
"expect_error",
"+=",
"1",
"comment_cmd",
"=",
"command",
"(",
"includes",
",",
"opts",
",",
"built_file",
",",
"os",
".",
"path",
".",
"basename",
"(",
"cpp",
")",
")",
"comment",
"=",
"make_comment",
"(",
"config",
".",
"comment_text",
"(",
"comment_cmd",
",",
"expect_error",
")",
")",
"self",
".",
"_write_source",
"(",
"cpp",
",",
"'\\n'",
".",
"join",
"(",
"[",
"comment",
",",
"source",
"]",
")",
")",
"#print 'wrote in', cpp",
"#print 'trying command', cmd",
"status",
",",
"output",
"=",
"syscmd",
"(",
"cmd",
",",
"expect_error",
")",
"if",
"status",
"or",
"expect_error",
">",
"1",
":",
"print",
"if",
"expect_error",
"and",
"expect_error",
"<",
"2",
":",
"print",
"'Compilation failure expected, but none seen'",
"print",
"'------------ begin offending source ------------'",
"print",
"open",
"(",
"cpp",
")",
".",
"read",
"(",
")",
"print",
"'------------ end offending source ------------'",
"if",
"self",
".",
"config",
".",
"save_cpp",
":",
"print",
"'saved in'",
",",
"repr",
"(",
"cpp",
")",
"else",
":",
"self",
".",
"_remove_source",
"(",
"cpp",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"else",
":",
"print",
"'.'",
",",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"built_handler",
"(",
"built_file",
")",
"self",
".",
"_remove_source",
"(",
"cpp",
")",
"try",
":",
"self",
".",
"_unlink",
"(",
"built_file",
")",
"except",
":",
"if",
"not",
"expect_error",
":",
"print",
"'failed to unlink'",
",",
"built_file",
"return",
"status"
] | Compile examples on the stack, whose topmost item is the last example
seen but not yet handled so far.
:howmany: How many of the topmost examples on the stack to compile.
You can pass a number, or 'all' to indicate that all examples should
be compiled.
:pop: How many of the topmost examples to discard. By default, all of
the examples that are compiled are discarded.
:expect_error: Whether a compilation error is to be expected. Any value
> 1 will cause the expected diagnostic's text to be dumped for
diagnostic purposes. It's common to expect an error but see a
completely unrelated one because of bugs in the example (you can get
this behavior for all examples by setting show_expected_error_output
in your config).
:extension: The extension of the file to build (set to .exe for
run)
:options: Compiler flags
:built_file: A path to use for the built file. By default, a temp
filename is conjured up
:built_handler: A function that's called with the name of the built file
upon success.
:source_file: The full name of the source file to write
:source_suffix: If source_file is None, the suffix to use for the source file
:make_comment: A function that transforms text into an appropriate comment.
:command: A function that is passed (includes, opts, target, source), where
opts is a string representing compiler options, target is the name of
the file to build, and source is the name of the file into which the
example code is written. By default, the function formats
litre.config.compiler with its argument tuple. | [
"Compile",
"examples",
"on",
"the",
"stack",
"whose",
"topmost",
"item",
"is",
"the",
"last",
"example",
"seen",
"but",
"not",
"yet",
"handled",
"so",
"far",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/litre/cplusplus.py#L357-L490 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.load | def load (self, jamfile_location):
"""Loads jamfile at the given location. After loading, project global
file and jamfile needed by the loaded one will be loaded recursively.
If the jamfile at that location is loaded already, does nothing.
Returns the project module for the Jamfile."""
assert isinstance(jamfile_location, basestring)
absolute = os.path.join(os.getcwd(), jamfile_location)
absolute = os.path.normpath(absolute)
jamfile_location = b2.util.path.relpath(os.getcwd(), absolute)
mname = self.module_name(jamfile_location)
# If Jamfile is already loaded, do not try again.
if not mname in self.jamfile_modules:
if "--debug-loading" in self.manager.argv():
print "Loading Jamfile at '%s'" % jamfile_location
self.load_jamfile(jamfile_location, mname)
# We want to make sure that child project are loaded only
# after parent projects. In particular, because parent projects
# define attributes which are inherited by children, and we do not
# want children to be loaded before parents has defined everything.
#
# While "build-project" and "use-project" can potentially refer
# to child projects from parent projects, we do not immediately
# load child projects when seing those attributes. Instead,
# we record the minimal information that will be used only later.
self.load_used_projects(mname)
return mname | python | def load (self, jamfile_location):
"""Loads jamfile at the given location. After loading, project global
file and jamfile needed by the loaded one will be loaded recursively.
If the jamfile at that location is loaded already, does nothing.
Returns the project module for the Jamfile."""
assert isinstance(jamfile_location, basestring)
absolute = os.path.join(os.getcwd(), jamfile_location)
absolute = os.path.normpath(absolute)
jamfile_location = b2.util.path.relpath(os.getcwd(), absolute)
mname = self.module_name(jamfile_location)
# If Jamfile is already loaded, do not try again.
if not mname in self.jamfile_modules:
if "--debug-loading" in self.manager.argv():
print "Loading Jamfile at '%s'" % jamfile_location
self.load_jamfile(jamfile_location, mname)
# We want to make sure that child project are loaded only
# after parent projects. In particular, because parent projects
# define attributes which are inherited by children, and we do not
# want children to be loaded before parents has defined everything.
#
# While "build-project" and "use-project" can potentially refer
# to child projects from parent projects, we do not immediately
# load child projects when seing those attributes. Instead,
# we record the minimal information that will be used only later.
self.load_used_projects(mname)
return mname | [
"def",
"load",
"(",
"self",
",",
"jamfile_location",
")",
":",
"assert",
"isinstance",
"(",
"jamfile_location",
",",
"basestring",
")",
"absolute",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"jamfile_location",
")",
"absolute",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"absolute",
")",
"jamfile_location",
"=",
"b2",
".",
"util",
".",
"path",
".",
"relpath",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"absolute",
")",
"mname",
"=",
"self",
".",
"module_name",
"(",
"jamfile_location",
")",
"# If Jamfile is already loaded, do not try again.",
"if",
"not",
"mname",
"in",
"self",
".",
"jamfile_modules",
":",
"if",
"\"--debug-loading\"",
"in",
"self",
".",
"manager",
".",
"argv",
"(",
")",
":",
"print",
"\"Loading Jamfile at '%s'\"",
"%",
"jamfile_location",
"self",
".",
"load_jamfile",
"(",
"jamfile_location",
",",
"mname",
")",
"# We want to make sure that child project are loaded only",
"# after parent projects. In particular, because parent projects",
"# define attributes which are inherited by children, and we do not",
"# want children to be loaded before parents has defined everything.",
"#",
"# While \"build-project\" and \"use-project\" can potentially refer",
"# to child projects from parent projects, we do not immediately",
"# load child projects when seing those attributes. Instead,",
"# we record the minimal information that will be used only later.",
"self",
".",
"load_used_projects",
"(",
"mname",
")",
"return",
"mname"
] | Loads jamfile at the given location. After loading, project global
file and jamfile needed by the loaded one will be loaded recursively.
If the jamfile at that location is loaded already, does nothing.
Returns the project module for the Jamfile. | [
"Loads",
"jamfile",
"at",
"the",
"given",
"location",
".",
"After",
"loading",
"project",
"global",
"file",
"and",
"jamfile",
"needed",
"by",
"the",
"loaded",
"one",
"will",
"be",
"loaded",
"recursively",
".",
"If",
"the",
"jamfile",
"at",
"that",
"location",
"is",
"loaded",
"already",
"does",
"nothing",
".",
"Returns",
"the",
"project",
"module",
"for",
"the",
"Jamfile",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L132-L164 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.load_parent | def load_parent(self, location):
"""Loads parent of Jamfile at 'location'.
Issues an error if nothing is found."""
assert isinstance(location, basestring)
found = b2.util.path.glob_in_parents(
location, self.JAMROOT + self.JAMFILE)
if not found:
print "error: Could not find parent for project at '%s'" % location
print "error: Did not find Jamfile.jam or Jamroot.jam in any parent directory."
sys.exit(1)
return self.load(os.path.dirname(found[0])) | python | def load_parent(self, location):
"""Loads parent of Jamfile at 'location'.
Issues an error if nothing is found."""
assert isinstance(location, basestring)
found = b2.util.path.glob_in_parents(
location, self.JAMROOT + self.JAMFILE)
if not found:
print "error: Could not find parent for project at '%s'" % location
print "error: Did not find Jamfile.jam or Jamroot.jam in any parent directory."
sys.exit(1)
return self.load(os.path.dirname(found[0])) | [
"def",
"load_parent",
"(",
"self",
",",
"location",
")",
":",
"assert",
"isinstance",
"(",
"location",
",",
"basestring",
")",
"found",
"=",
"b2",
".",
"util",
".",
"path",
".",
"glob_in_parents",
"(",
"location",
",",
"self",
".",
"JAMROOT",
"+",
"self",
".",
"JAMFILE",
")",
"if",
"not",
"found",
":",
"print",
"\"error: Could not find parent for project at '%s'\"",
"%",
"location",
"print",
"\"error: Did not find Jamfile.jam or Jamroot.jam in any parent directory.\"",
"sys",
".",
"exit",
"(",
"1",
")",
"return",
"self",
".",
"load",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"found",
"[",
"0",
"]",
")",
")"
] | Loads parent of Jamfile at 'location'.
Issues an error if nothing is found. | [
"Loads",
"parent",
"of",
"Jamfile",
"at",
"location",
".",
"Issues",
"an",
"error",
"if",
"nothing",
"is",
"found",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L178-L190 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.find | def find(self, name, current_location):
"""Given 'name' which can be project-id or plain directory name,
return project module corresponding to that id or directory.
Returns nothing of project is not found."""
assert isinstance(name, basestring)
assert isinstance(current_location, basestring)
project_module = None
# Try interpreting name as project id.
if name[0] == '/':
project_module = self.id2module.get(name)
if not project_module:
location = os.path.join(current_location, name)
# If no project is registered for the given location, try to
# load it. First see if we have Jamfile. If not we might have project
# root, willing to act as Jamfile. In that case, project-root
# must be placed in the directory referred by id.
project_module = self.module_name(location)
if not project_module in self.jamfile_modules:
if b2.util.path.glob([location], self.JAMROOT + self.JAMFILE):
project_module = self.load(location)
else:
project_module = None
return project_module | python | def find(self, name, current_location):
"""Given 'name' which can be project-id or plain directory name,
return project module corresponding to that id or directory.
Returns nothing of project is not found."""
assert isinstance(name, basestring)
assert isinstance(current_location, basestring)
project_module = None
# Try interpreting name as project id.
if name[0] == '/':
project_module = self.id2module.get(name)
if not project_module:
location = os.path.join(current_location, name)
# If no project is registered for the given location, try to
# load it. First see if we have Jamfile. If not we might have project
# root, willing to act as Jamfile. In that case, project-root
# must be placed in the directory referred by id.
project_module = self.module_name(location)
if not project_module in self.jamfile_modules:
if b2.util.path.glob([location], self.JAMROOT + self.JAMFILE):
project_module = self.load(location)
else:
project_module = None
return project_module | [
"def",
"find",
"(",
"self",
",",
"name",
",",
"current_location",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"current_location",
",",
"basestring",
")",
"project_module",
"=",
"None",
"# Try interpreting name as project id.",
"if",
"name",
"[",
"0",
"]",
"==",
"'/'",
":",
"project_module",
"=",
"self",
".",
"id2module",
".",
"get",
"(",
"name",
")",
"if",
"not",
"project_module",
":",
"location",
"=",
"os",
".",
"path",
".",
"join",
"(",
"current_location",
",",
"name",
")",
"# If no project is registered for the given location, try to",
"# load it. First see if we have Jamfile. If not we might have project",
"# root, willing to act as Jamfile. In that case, project-root",
"# must be placed in the directory referred by id.",
"project_module",
"=",
"self",
".",
"module_name",
"(",
"location",
")",
"if",
"not",
"project_module",
"in",
"self",
".",
"jamfile_modules",
":",
"if",
"b2",
".",
"util",
".",
"path",
".",
"glob",
"(",
"[",
"location",
"]",
",",
"self",
".",
"JAMROOT",
"+",
"self",
".",
"JAMFILE",
")",
":",
"project_module",
"=",
"self",
".",
"load",
"(",
"location",
")",
"else",
":",
"project_module",
"=",
"None",
"return",
"project_module"
] | Given 'name' which can be project-id or plain directory name,
return project module corresponding to that id or directory.
Returns nothing of project is not found. | [
"Given",
"name",
"which",
"can",
"be",
"project",
"-",
"id",
"or",
"plain",
"directory",
"name",
"return",
"project",
"module",
"corresponding",
"to",
"that",
"id",
"or",
"directory",
".",
"Returns",
"nothing",
"of",
"project",
"is",
"not",
"found",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L192-L219 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.module_name | def module_name(self, jamfile_location):
"""Returns the name of module corresponding to 'jamfile-location'.
If no module corresponds to location yet, associates default
module name with that location."""
assert isinstance(jamfile_location, basestring)
module = self.location2module.get(jamfile_location)
if not module:
# Root the path, so that locations are always umbiguious.
# Without this, we can't decide if '../../exe/program1' and '.'
# are the same paths, or not.
jamfile_location = os.path.realpath(
os.path.join(os.getcwd(), jamfile_location))
module = "Jamfile<%s>" % jamfile_location
self.location2module[jamfile_location] = module
return module | python | def module_name(self, jamfile_location):
"""Returns the name of module corresponding to 'jamfile-location'.
If no module corresponds to location yet, associates default
module name with that location."""
assert isinstance(jamfile_location, basestring)
module = self.location2module.get(jamfile_location)
if not module:
# Root the path, so that locations are always umbiguious.
# Without this, we can't decide if '../../exe/program1' and '.'
# are the same paths, or not.
jamfile_location = os.path.realpath(
os.path.join(os.getcwd(), jamfile_location))
module = "Jamfile<%s>" % jamfile_location
self.location2module[jamfile_location] = module
return module | [
"def",
"module_name",
"(",
"self",
",",
"jamfile_location",
")",
":",
"assert",
"isinstance",
"(",
"jamfile_location",
",",
"basestring",
")",
"module",
"=",
"self",
".",
"location2module",
".",
"get",
"(",
"jamfile_location",
")",
"if",
"not",
"module",
":",
"# Root the path, so that locations are always umbiguious.",
"# Without this, we can't decide if '../../exe/program1' and '.'",
"# are the same paths, or not.",
"jamfile_location",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"jamfile_location",
")",
")",
"module",
"=",
"\"Jamfile<%s>\"",
"%",
"jamfile_location",
"self",
".",
"location2module",
"[",
"jamfile_location",
"]",
"=",
"module",
"return",
"module"
] | Returns the name of module corresponding to 'jamfile-location'.
If no module corresponds to location yet, associates default
module name with that location. | [
"Returns",
"the",
"name",
"of",
"module",
"corresponding",
"to",
"jamfile",
"-",
"location",
".",
"If",
"no",
"module",
"corresponds",
"to",
"location",
"yet",
"associates",
"default",
"module",
"name",
"with",
"that",
"location",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L221-L235 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.find_jamfile | def find_jamfile (self, dir, parent_root=0, no_errors=0):
"""Find the Jamfile at the given location. This returns the
exact names of all the Jamfiles in the given directory. The optional
parent-root argument causes this to search not the given directory
but the ones above it up to the directory given in it."""
assert isinstance(dir, basestring)
assert isinstance(parent_root, (int, bool))
assert isinstance(no_errors, (int, bool))
# Glob for all the possible Jamfiles according to the match pattern.
#
jamfile_glob = None
if parent_root:
parent = self.dir2parent_jamfile.get(dir)
if not parent:
parent = b2.util.path.glob_in_parents(dir,
self.JAMFILE)
self.dir2parent_jamfile[dir] = parent
jamfile_glob = parent
else:
jamfile = self.dir2jamfile.get(dir)
if not jamfile:
jamfile = b2.util.path.glob([dir], self.JAMFILE)
self.dir2jamfile[dir] = jamfile
jamfile_glob = jamfile
if len(jamfile_glob) > 1:
# Multiple Jamfiles found in the same place. Warn about this.
# And ensure we use only one of them.
# As a temporary convenience measure, if there's Jamfile.v2 amount
# found files, suppress the warning and use it.
#
pattern = "(.*[Jj]amfile\\.v2)|(.*[Bb]uild\\.jam)"
v2_jamfiles = [x for x in jamfile_glob if re.match(pattern, x)]
if len(v2_jamfiles) == 1:
jamfile_glob = v2_jamfiles
else:
print """warning: Found multiple Jamfiles at '%s'!""" % (dir)
for j in jamfile_glob:
print " -", j
print "Loading the first one"
# Could not find it, error.
if not no_errors and not jamfile_glob:
self.manager.errors()(
"""Unable to load Jamfile.
Could not find a Jamfile in directory '%s'
Attempted to find it with pattern '%s'.
Please consult the documentation at 'http://boost.org/boost-build2'."""
% (dir, string.join(self.JAMFILE)))
if jamfile_glob:
return jamfile_glob[0] | python | def find_jamfile (self, dir, parent_root=0, no_errors=0):
"""Find the Jamfile at the given location. This returns the
exact names of all the Jamfiles in the given directory. The optional
parent-root argument causes this to search not the given directory
but the ones above it up to the directory given in it."""
assert isinstance(dir, basestring)
assert isinstance(parent_root, (int, bool))
assert isinstance(no_errors, (int, bool))
# Glob for all the possible Jamfiles according to the match pattern.
#
jamfile_glob = None
if parent_root:
parent = self.dir2parent_jamfile.get(dir)
if not parent:
parent = b2.util.path.glob_in_parents(dir,
self.JAMFILE)
self.dir2parent_jamfile[dir] = parent
jamfile_glob = parent
else:
jamfile = self.dir2jamfile.get(dir)
if not jamfile:
jamfile = b2.util.path.glob([dir], self.JAMFILE)
self.dir2jamfile[dir] = jamfile
jamfile_glob = jamfile
if len(jamfile_glob) > 1:
# Multiple Jamfiles found in the same place. Warn about this.
# And ensure we use only one of them.
# As a temporary convenience measure, if there's Jamfile.v2 amount
# found files, suppress the warning and use it.
#
pattern = "(.*[Jj]amfile\\.v2)|(.*[Bb]uild\\.jam)"
v2_jamfiles = [x for x in jamfile_glob if re.match(pattern, x)]
if len(v2_jamfiles) == 1:
jamfile_glob = v2_jamfiles
else:
print """warning: Found multiple Jamfiles at '%s'!""" % (dir)
for j in jamfile_glob:
print " -", j
print "Loading the first one"
# Could not find it, error.
if not no_errors and not jamfile_glob:
self.manager.errors()(
"""Unable to load Jamfile.
Could not find a Jamfile in directory '%s'
Attempted to find it with pattern '%s'.
Please consult the documentation at 'http://boost.org/boost-build2'."""
% (dir, string.join(self.JAMFILE)))
if jamfile_glob:
return jamfile_glob[0] | [
"def",
"find_jamfile",
"(",
"self",
",",
"dir",
",",
"parent_root",
"=",
"0",
",",
"no_errors",
"=",
"0",
")",
":",
"assert",
"isinstance",
"(",
"dir",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"parent_root",
",",
"(",
"int",
",",
"bool",
")",
")",
"assert",
"isinstance",
"(",
"no_errors",
",",
"(",
"int",
",",
"bool",
")",
")",
"# Glob for all the possible Jamfiles according to the match pattern.",
"#",
"jamfile_glob",
"=",
"None",
"if",
"parent_root",
":",
"parent",
"=",
"self",
".",
"dir2parent_jamfile",
".",
"get",
"(",
"dir",
")",
"if",
"not",
"parent",
":",
"parent",
"=",
"b2",
".",
"util",
".",
"path",
".",
"glob_in_parents",
"(",
"dir",
",",
"self",
".",
"JAMFILE",
")",
"self",
".",
"dir2parent_jamfile",
"[",
"dir",
"]",
"=",
"parent",
"jamfile_glob",
"=",
"parent",
"else",
":",
"jamfile",
"=",
"self",
".",
"dir2jamfile",
".",
"get",
"(",
"dir",
")",
"if",
"not",
"jamfile",
":",
"jamfile",
"=",
"b2",
".",
"util",
".",
"path",
".",
"glob",
"(",
"[",
"dir",
"]",
",",
"self",
".",
"JAMFILE",
")",
"self",
".",
"dir2jamfile",
"[",
"dir",
"]",
"=",
"jamfile",
"jamfile_glob",
"=",
"jamfile",
"if",
"len",
"(",
"jamfile_glob",
")",
">",
"1",
":",
"# Multiple Jamfiles found in the same place. Warn about this.",
"# And ensure we use only one of them.",
"# As a temporary convenience measure, if there's Jamfile.v2 amount",
"# found files, suppress the warning and use it.",
"#",
"pattern",
"=",
"\"(.*[Jj]amfile\\\\.v2)|(.*[Bb]uild\\\\.jam)\"",
"v2_jamfiles",
"=",
"[",
"x",
"for",
"x",
"in",
"jamfile_glob",
"if",
"re",
".",
"match",
"(",
"pattern",
",",
"x",
")",
"]",
"if",
"len",
"(",
"v2_jamfiles",
")",
"==",
"1",
":",
"jamfile_glob",
"=",
"v2_jamfiles",
"else",
":",
"print",
"\"\"\"warning: Found multiple Jamfiles at '%s'!\"\"\"",
"%",
"(",
"dir",
")",
"for",
"j",
"in",
"jamfile_glob",
":",
"print",
"\" -\"",
",",
"j",
"print",
"\"Loading the first one\"",
"# Could not find it, error.",
"if",
"not",
"no_errors",
"and",
"not",
"jamfile_glob",
":",
"self",
".",
"manager",
".",
"errors",
"(",
")",
"(",
"\"\"\"Unable to load Jamfile.\nCould not find a Jamfile in directory '%s'\nAttempted to find it with pattern '%s'.\nPlease consult the documentation at 'http://boost.org/boost-build2'.\"\"\"",
"%",
"(",
"dir",
",",
"string",
".",
"join",
"(",
"self",
".",
"JAMFILE",
")",
")",
")",
"if",
"jamfile_glob",
":",
"return",
"jamfile_glob",
"[",
"0",
"]"
] | Find the Jamfile at the given location. This returns the
exact names of all the Jamfiles in the given directory. The optional
parent-root argument causes this to search not the given directory
but the ones above it up to the directory given in it. | [
"Find",
"the",
"Jamfile",
"at",
"the",
"given",
"location",
".",
"This",
"returns",
"the",
"exact",
"names",
"of",
"all",
"the",
"Jamfiles",
"in",
"the",
"given",
"directory",
".",
"The",
"optional",
"parent",
"-",
"root",
"argument",
"causes",
"this",
"to",
"search",
"not",
"the",
"given",
"directory",
"but",
"the",
"ones",
"above",
"it",
"up",
"to",
"the",
"directory",
"given",
"in",
"it",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L237-L289 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.load_jamfile | def load_jamfile(self, dir, jamfile_module):
"""Load a Jamfile at the given directory. Returns nothing.
Will attempt to load the file as indicated by the JAMFILE patterns.
Effect of calling this rule twice with the same 'dir' is underfined."""
assert isinstance(dir, basestring)
assert isinstance(jamfile_module, basestring)
# See if the Jamfile is where it should be.
is_jamroot = False
jamfile_to_load = b2.util.path.glob([dir], self.JAMROOT)
if jamfile_to_load:
if len(jamfile_to_load) > 1:
get_manager().errors()(
"Multiple Jamfiles found at '{}'\n"
"Filenames are: {}"
.format(dir, ' '.join(os.path.basename(j) for j in jamfile_to_load))
)
is_jamroot = True
jamfile_to_load = jamfile_to_load[0]
else:
jamfile_to_load = self.find_jamfile(dir)
dir = os.path.dirname(jamfile_to_load)
if not dir:
dir = "."
self.used_projects[jamfile_module] = []
# Now load the Jamfile in it's own context.
# The call to 'initialize' may load parent Jamfile, which might have
# 'use-project' statement that causes a second attempt to load the
# same project we're loading now. Checking inside .jamfile-modules
# prevents that second attempt from messing up.
if not jamfile_module in self.jamfile_modules:
previous_project = self.current_project
# Initialize the jamfile module before loading.
self.initialize(jamfile_module, dir, os.path.basename(jamfile_to_load))
if not jamfile_module in self.jamfile_modules:
saved_project = self.current_project
self.jamfile_modules[jamfile_module] = True
bjam.call("load", jamfile_module, jamfile_to_load)
if is_jamroot:
jamfile = self.find_jamfile(dir, no_errors=True)
if jamfile:
bjam.call("load", jamfile_module, jamfile)
# Now do some checks
if self.current_project != saved_project:
from textwrap import dedent
self.manager.errors()(dedent(
"""
The value of the .current-project variable has magically changed
after loading a Jamfile. This means some of the targets might be
defined a the wrong project.
after loading %s
expected value %s
actual value %s
"""
% (jamfile_module, saved_project, self.current_project)
))
self.end_load(previous_project)
if self.global_build_dir:
id = self.attributeDefault(jamfile_module, "id", None)
project_root = self.attribute(jamfile_module, "project-root")
location = self.attribute(jamfile_module, "location")
if location and project_root == dir:
# This is Jamroot
if not id:
# FIXME: go via errors module, so that contexts are
# shown?
print "warning: the --build-dir option was specified"
print "warning: but Jamroot at '%s'" % dir
print "warning: specified no project id"
print "warning: the --build-dir option will be ignored" | python | def load_jamfile(self, dir, jamfile_module):
"""Load a Jamfile at the given directory. Returns nothing.
Will attempt to load the file as indicated by the JAMFILE patterns.
Effect of calling this rule twice with the same 'dir' is underfined."""
assert isinstance(dir, basestring)
assert isinstance(jamfile_module, basestring)
# See if the Jamfile is where it should be.
is_jamroot = False
jamfile_to_load = b2.util.path.glob([dir], self.JAMROOT)
if jamfile_to_load:
if len(jamfile_to_load) > 1:
get_manager().errors()(
"Multiple Jamfiles found at '{}'\n"
"Filenames are: {}"
.format(dir, ' '.join(os.path.basename(j) for j in jamfile_to_load))
)
is_jamroot = True
jamfile_to_load = jamfile_to_load[0]
else:
jamfile_to_load = self.find_jamfile(dir)
dir = os.path.dirname(jamfile_to_load)
if not dir:
dir = "."
self.used_projects[jamfile_module] = []
# Now load the Jamfile in it's own context.
# The call to 'initialize' may load parent Jamfile, which might have
# 'use-project' statement that causes a second attempt to load the
# same project we're loading now. Checking inside .jamfile-modules
# prevents that second attempt from messing up.
if not jamfile_module in self.jamfile_modules:
previous_project = self.current_project
# Initialize the jamfile module before loading.
self.initialize(jamfile_module, dir, os.path.basename(jamfile_to_load))
if not jamfile_module in self.jamfile_modules:
saved_project = self.current_project
self.jamfile_modules[jamfile_module] = True
bjam.call("load", jamfile_module, jamfile_to_load)
if is_jamroot:
jamfile = self.find_jamfile(dir, no_errors=True)
if jamfile:
bjam.call("load", jamfile_module, jamfile)
# Now do some checks
if self.current_project != saved_project:
from textwrap import dedent
self.manager.errors()(dedent(
"""
The value of the .current-project variable has magically changed
after loading a Jamfile. This means some of the targets might be
defined a the wrong project.
after loading %s
expected value %s
actual value %s
"""
% (jamfile_module, saved_project, self.current_project)
))
self.end_load(previous_project)
if self.global_build_dir:
id = self.attributeDefault(jamfile_module, "id", None)
project_root = self.attribute(jamfile_module, "project-root")
location = self.attribute(jamfile_module, "location")
if location and project_root == dir:
# This is Jamroot
if not id:
# FIXME: go via errors module, so that contexts are
# shown?
print "warning: the --build-dir option was specified"
print "warning: but Jamroot at '%s'" % dir
print "warning: specified no project id"
print "warning: the --build-dir option will be ignored" | [
"def",
"load_jamfile",
"(",
"self",
",",
"dir",
",",
"jamfile_module",
")",
":",
"assert",
"isinstance",
"(",
"dir",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"jamfile_module",
",",
"basestring",
")",
"# See if the Jamfile is where it should be.",
"is_jamroot",
"=",
"False",
"jamfile_to_load",
"=",
"b2",
".",
"util",
".",
"path",
".",
"glob",
"(",
"[",
"dir",
"]",
",",
"self",
".",
"JAMROOT",
")",
"if",
"jamfile_to_load",
":",
"if",
"len",
"(",
"jamfile_to_load",
")",
">",
"1",
":",
"get_manager",
"(",
")",
".",
"errors",
"(",
")",
"(",
"\"Multiple Jamfiles found at '{}'\\n\"",
"\"Filenames are: {}\"",
".",
"format",
"(",
"dir",
",",
"' '",
".",
"join",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"j",
")",
"for",
"j",
"in",
"jamfile_to_load",
")",
")",
")",
"is_jamroot",
"=",
"True",
"jamfile_to_load",
"=",
"jamfile_to_load",
"[",
"0",
"]",
"else",
":",
"jamfile_to_load",
"=",
"self",
".",
"find_jamfile",
"(",
"dir",
")",
"dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"jamfile_to_load",
")",
"if",
"not",
"dir",
":",
"dir",
"=",
"\".\"",
"self",
".",
"used_projects",
"[",
"jamfile_module",
"]",
"=",
"[",
"]",
"# Now load the Jamfile in it's own context.",
"# The call to 'initialize' may load parent Jamfile, which might have",
"# 'use-project' statement that causes a second attempt to load the",
"# same project we're loading now. Checking inside .jamfile-modules",
"# prevents that second attempt from messing up.",
"if",
"not",
"jamfile_module",
"in",
"self",
".",
"jamfile_modules",
":",
"previous_project",
"=",
"self",
".",
"current_project",
"# Initialize the jamfile module before loading.",
"self",
".",
"initialize",
"(",
"jamfile_module",
",",
"dir",
",",
"os",
".",
"path",
".",
"basename",
"(",
"jamfile_to_load",
")",
")",
"if",
"not",
"jamfile_module",
"in",
"self",
".",
"jamfile_modules",
":",
"saved_project",
"=",
"self",
".",
"current_project",
"self",
".",
"jamfile_modules",
"[",
"jamfile_module",
"]",
"=",
"True",
"bjam",
".",
"call",
"(",
"\"load\"",
",",
"jamfile_module",
",",
"jamfile_to_load",
")",
"if",
"is_jamroot",
":",
"jamfile",
"=",
"self",
".",
"find_jamfile",
"(",
"dir",
",",
"no_errors",
"=",
"True",
")",
"if",
"jamfile",
":",
"bjam",
".",
"call",
"(",
"\"load\"",
",",
"jamfile_module",
",",
"jamfile",
")",
"# Now do some checks",
"if",
"self",
".",
"current_project",
"!=",
"saved_project",
":",
"from",
"textwrap",
"import",
"dedent",
"self",
".",
"manager",
".",
"errors",
"(",
")",
"(",
"dedent",
"(",
"\"\"\"\n The value of the .current-project variable has magically changed\n after loading a Jamfile. This means some of the targets might be\n defined a the wrong project.\n after loading %s\n expected value %s\n actual value %s\n \"\"\"",
"%",
"(",
"jamfile_module",
",",
"saved_project",
",",
"self",
".",
"current_project",
")",
")",
")",
"self",
".",
"end_load",
"(",
"previous_project",
")",
"if",
"self",
".",
"global_build_dir",
":",
"id",
"=",
"self",
".",
"attributeDefault",
"(",
"jamfile_module",
",",
"\"id\"",
",",
"None",
")",
"project_root",
"=",
"self",
".",
"attribute",
"(",
"jamfile_module",
",",
"\"project-root\"",
")",
"location",
"=",
"self",
".",
"attribute",
"(",
"jamfile_module",
",",
"\"location\"",
")",
"if",
"location",
"and",
"project_root",
"==",
"dir",
":",
"# This is Jamroot",
"if",
"not",
"id",
":",
"# FIXME: go via errors module, so that contexts are",
"# shown?",
"print",
"\"warning: the --build-dir option was specified\"",
"print",
"\"warning: but Jamroot at '%s'\"",
"%",
"dir",
"print",
"\"warning: specified no project id\"",
"print",
"\"warning: the --build-dir option will be ignored\""
] | Load a Jamfile at the given directory. Returns nothing.
Will attempt to load the file as indicated by the JAMFILE patterns.
Effect of calling this rule twice with the same 'dir' is underfined. | [
"Load",
"a",
"Jamfile",
"at",
"the",
"given",
"directory",
".",
"Returns",
"nothing",
".",
"Will",
"attempt",
"to",
"load",
"the",
"file",
"as",
"indicated",
"by",
"the",
"JAMFILE",
"patterns",
".",
"Effect",
"of",
"calling",
"this",
"rule",
"twice",
"with",
"the",
"same",
"dir",
"is",
"underfined",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L291-L370 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.load_standalone | def load_standalone(self, jamfile_module, file):
"""Loads 'file' as standalone project that has no location
associated with it. This is mostly useful for user-config.jam,
which should be able to define targets, but although it has
some location in filesystem, we do not want any build to
happen in user's HOME, for example.
The caller is required to never call this method twice on
the same file.
"""
assert isinstance(jamfile_module, basestring)
assert isinstance(file, basestring)
self.used_projects[jamfile_module] = []
bjam.call("load", jamfile_module, file)
self.load_used_projects(jamfile_module) | python | def load_standalone(self, jamfile_module, file):
"""Loads 'file' as standalone project that has no location
associated with it. This is mostly useful for user-config.jam,
which should be able to define targets, but although it has
some location in filesystem, we do not want any build to
happen in user's HOME, for example.
The caller is required to never call this method twice on
the same file.
"""
assert isinstance(jamfile_module, basestring)
assert isinstance(file, basestring)
self.used_projects[jamfile_module] = []
bjam.call("load", jamfile_module, file)
self.load_used_projects(jamfile_module) | [
"def",
"load_standalone",
"(",
"self",
",",
"jamfile_module",
",",
"file",
")",
":",
"assert",
"isinstance",
"(",
"jamfile_module",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"file",
",",
"basestring",
")",
"self",
".",
"used_projects",
"[",
"jamfile_module",
"]",
"=",
"[",
"]",
"bjam",
".",
"call",
"(",
"\"load\"",
",",
"jamfile_module",
",",
"file",
")",
"self",
".",
"load_used_projects",
"(",
"jamfile_module",
")"
] | Loads 'file' as standalone project that has no location
associated with it. This is mostly useful for user-config.jam,
which should be able to define targets, but although it has
some location in filesystem, we do not want any build to
happen in user's HOME, for example.
The caller is required to never call this method twice on
the same file. | [
"Loads",
"file",
"as",
"standalone",
"project",
"that",
"has",
"no",
"location",
"associated",
"with",
"it",
".",
"This",
"is",
"mostly",
"useful",
"for",
"user",
"-",
"config",
".",
"jam",
"which",
"should",
"be",
"able",
"to",
"define",
"targets",
"but",
"although",
"it",
"has",
"some",
"location",
"in",
"filesystem",
"we",
"do",
"not",
"want",
"any",
"build",
"to",
"happen",
"in",
"user",
"s",
"HOME",
"for",
"example",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L387-L402 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.initialize | def initialize(self, module_name, location=None, basename=None, standalone_path=''):
"""Initialize the module for a project.
module-name is the name of the project module.
location is the location (directory) of the project to initialize.
If not specified, standalone project will be initialized
standalone_path is the path to the source-location.
this should only be called from the python side.
"""
assert isinstance(module_name, basestring)
assert isinstance(location, basestring) or location is None
assert isinstance(basename, basestring) or basename is None
jamroot = False
parent_module = None
if module_name == "test-config":
# No parent
pass
elif module_name == "site-config":
parent_module = "test-config"
elif module_name == "user-config":
parent_module = "site-config"
elif module_name == "project-config":
parent_module = "user-config"
elif location and not self.is_jamroot(basename):
# We search for parent/project-root only if jamfile was specified
# --- i.e
# if the project is not standalone.
parent_module = self.load_parent(location)
elif location:
# It's either jamroot, or standalone project.
# If it's jamroot, inherit from user-config.
# If project-config module exist, inherit from it.
parent_module = 'user-config'
if 'project-config' in self.module2attributes:
parent_module = 'project-config'
jamroot = True
# TODO: need to consider if standalone projects can do anything but defining
# prebuilt targets. If so, we need to give more sensible "location", so that
# source paths are correct.
if not location:
location = ""
# the call to load_parent() above can end up loading this module again
# make sure we don't reinitialize the module's attributes
if module_name not in self.module2attributes:
if "--debug-loading" in self.manager.argv():
print "Initializing project '%s'" % module_name
attributes = ProjectAttributes(self.manager, location, module_name)
self.module2attributes[module_name] = attributes
python_standalone = False
if location:
attributes.set("source-location", [location], exact=1)
elif not module_name in ["test-config", "site-config", "user-config", "project-config"]:
# This is a standalone project with known location. Set source location
# so that it can declare targets. This is intended so that you can put
# a .jam file in your sources and use it via 'using'. Standard modules
# (in 'tools' subdir) may not assume source dir is set.
source_location = standalone_path
if not source_location:
source_location = self.loaded_tool_module_path_.get(module_name)
if not source_location:
self.manager.errors()('Standalone module path not found for "{}"'
.format(module_name))
attributes.set("source-location", [source_location], exact=1)
python_standalone = True
attributes.set("requirements", property_set.empty(), exact=True)
attributes.set("usage-requirements", property_set.empty(), exact=True)
attributes.set("default-build", property_set.empty(), exact=True)
attributes.set("projects-to-build", [], exact=True)
attributes.set("project-root", None, exact=True)
attributes.set("build-dir", None, exact=True)
self.project_rules_.init_project(module_name, python_standalone)
if parent_module:
self.inherit_attributes(module_name, parent_module)
attributes.set("parent-module", parent_module, exact=1)
if jamroot:
attributes.set("project-root", location, exact=1)
parent = None
if parent_module:
parent = self.target(parent_module)
if module_name not in self.module2target:
target = b2.build.targets.ProjectTarget(self.manager,
module_name, module_name, parent,
self.attribute(module_name, "requirements"),
# FIXME: why we need to pass this? It's not
# passed in jam code.
self.attribute(module_name, "default-build"))
self.module2target[module_name] = target
self.current_project = self.target(module_name) | python | def initialize(self, module_name, location=None, basename=None, standalone_path=''):
"""Initialize the module for a project.
module-name is the name of the project module.
location is the location (directory) of the project to initialize.
If not specified, standalone project will be initialized
standalone_path is the path to the source-location.
this should only be called from the python side.
"""
assert isinstance(module_name, basestring)
assert isinstance(location, basestring) or location is None
assert isinstance(basename, basestring) or basename is None
jamroot = False
parent_module = None
if module_name == "test-config":
# No parent
pass
elif module_name == "site-config":
parent_module = "test-config"
elif module_name == "user-config":
parent_module = "site-config"
elif module_name == "project-config":
parent_module = "user-config"
elif location and not self.is_jamroot(basename):
# We search for parent/project-root only if jamfile was specified
# --- i.e
# if the project is not standalone.
parent_module = self.load_parent(location)
elif location:
# It's either jamroot, or standalone project.
# If it's jamroot, inherit from user-config.
# If project-config module exist, inherit from it.
parent_module = 'user-config'
if 'project-config' in self.module2attributes:
parent_module = 'project-config'
jamroot = True
# TODO: need to consider if standalone projects can do anything but defining
# prebuilt targets. If so, we need to give more sensible "location", so that
# source paths are correct.
if not location:
location = ""
# the call to load_parent() above can end up loading this module again
# make sure we don't reinitialize the module's attributes
if module_name not in self.module2attributes:
if "--debug-loading" in self.manager.argv():
print "Initializing project '%s'" % module_name
attributes = ProjectAttributes(self.manager, location, module_name)
self.module2attributes[module_name] = attributes
python_standalone = False
if location:
attributes.set("source-location", [location], exact=1)
elif not module_name in ["test-config", "site-config", "user-config", "project-config"]:
# This is a standalone project with known location. Set source location
# so that it can declare targets. This is intended so that you can put
# a .jam file in your sources and use it via 'using'. Standard modules
# (in 'tools' subdir) may not assume source dir is set.
source_location = standalone_path
if not source_location:
source_location = self.loaded_tool_module_path_.get(module_name)
if not source_location:
self.manager.errors()('Standalone module path not found for "{}"'
.format(module_name))
attributes.set("source-location", [source_location], exact=1)
python_standalone = True
attributes.set("requirements", property_set.empty(), exact=True)
attributes.set("usage-requirements", property_set.empty(), exact=True)
attributes.set("default-build", property_set.empty(), exact=True)
attributes.set("projects-to-build", [], exact=True)
attributes.set("project-root", None, exact=True)
attributes.set("build-dir", None, exact=True)
self.project_rules_.init_project(module_name, python_standalone)
if parent_module:
self.inherit_attributes(module_name, parent_module)
attributes.set("parent-module", parent_module, exact=1)
if jamroot:
attributes.set("project-root", location, exact=1)
parent = None
if parent_module:
parent = self.target(parent_module)
if module_name not in self.module2target:
target = b2.build.targets.ProjectTarget(self.manager,
module_name, module_name, parent,
self.attribute(module_name, "requirements"),
# FIXME: why we need to pass this? It's not
# passed in jam code.
self.attribute(module_name, "default-build"))
self.module2target[module_name] = target
self.current_project = self.target(module_name) | [
"def",
"initialize",
"(",
"self",
",",
"module_name",
",",
"location",
"=",
"None",
",",
"basename",
"=",
"None",
",",
"standalone_path",
"=",
"''",
")",
":",
"assert",
"isinstance",
"(",
"module_name",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"location",
",",
"basestring",
")",
"or",
"location",
"is",
"None",
"assert",
"isinstance",
"(",
"basename",
",",
"basestring",
")",
"or",
"basename",
"is",
"None",
"jamroot",
"=",
"False",
"parent_module",
"=",
"None",
"if",
"module_name",
"==",
"\"test-config\"",
":",
"# No parent",
"pass",
"elif",
"module_name",
"==",
"\"site-config\"",
":",
"parent_module",
"=",
"\"test-config\"",
"elif",
"module_name",
"==",
"\"user-config\"",
":",
"parent_module",
"=",
"\"site-config\"",
"elif",
"module_name",
"==",
"\"project-config\"",
":",
"parent_module",
"=",
"\"user-config\"",
"elif",
"location",
"and",
"not",
"self",
".",
"is_jamroot",
"(",
"basename",
")",
":",
"# We search for parent/project-root only if jamfile was specified",
"# --- i.e",
"# if the project is not standalone.",
"parent_module",
"=",
"self",
".",
"load_parent",
"(",
"location",
")",
"elif",
"location",
":",
"# It's either jamroot, or standalone project.",
"# If it's jamroot, inherit from user-config.",
"# If project-config module exist, inherit from it.",
"parent_module",
"=",
"'user-config'",
"if",
"'project-config'",
"in",
"self",
".",
"module2attributes",
":",
"parent_module",
"=",
"'project-config'",
"jamroot",
"=",
"True",
"# TODO: need to consider if standalone projects can do anything but defining",
"# prebuilt targets. If so, we need to give more sensible \"location\", so that",
"# source paths are correct.",
"if",
"not",
"location",
":",
"location",
"=",
"\"\"",
"# the call to load_parent() above can end up loading this module again",
"# make sure we don't reinitialize the module's attributes",
"if",
"module_name",
"not",
"in",
"self",
".",
"module2attributes",
":",
"if",
"\"--debug-loading\"",
"in",
"self",
".",
"manager",
".",
"argv",
"(",
")",
":",
"print",
"\"Initializing project '%s'\"",
"%",
"module_name",
"attributes",
"=",
"ProjectAttributes",
"(",
"self",
".",
"manager",
",",
"location",
",",
"module_name",
")",
"self",
".",
"module2attributes",
"[",
"module_name",
"]",
"=",
"attributes",
"python_standalone",
"=",
"False",
"if",
"location",
":",
"attributes",
".",
"set",
"(",
"\"source-location\"",
",",
"[",
"location",
"]",
",",
"exact",
"=",
"1",
")",
"elif",
"not",
"module_name",
"in",
"[",
"\"test-config\"",
",",
"\"site-config\"",
",",
"\"user-config\"",
",",
"\"project-config\"",
"]",
":",
"# This is a standalone project with known location. Set source location",
"# so that it can declare targets. This is intended so that you can put",
"# a .jam file in your sources and use it via 'using'. Standard modules",
"# (in 'tools' subdir) may not assume source dir is set.",
"source_location",
"=",
"standalone_path",
"if",
"not",
"source_location",
":",
"source_location",
"=",
"self",
".",
"loaded_tool_module_path_",
".",
"get",
"(",
"module_name",
")",
"if",
"not",
"source_location",
":",
"self",
".",
"manager",
".",
"errors",
"(",
")",
"(",
"'Standalone module path not found for \"{}\"'",
".",
"format",
"(",
"module_name",
")",
")",
"attributes",
".",
"set",
"(",
"\"source-location\"",
",",
"[",
"source_location",
"]",
",",
"exact",
"=",
"1",
")",
"python_standalone",
"=",
"True",
"attributes",
".",
"set",
"(",
"\"requirements\"",
",",
"property_set",
".",
"empty",
"(",
")",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"usage-requirements\"",
",",
"property_set",
".",
"empty",
"(",
")",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"default-build\"",
",",
"property_set",
".",
"empty",
"(",
")",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"projects-to-build\"",
",",
"[",
"]",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"project-root\"",
",",
"None",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"build-dir\"",
",",
"None",
",",
"exact",
"=",
"True",
")",
"self",
".",
"project_rules_",
".",
"init_project",
"(",
"module_name",
",",
"python_standalone",
")",
"if",
"parent_module",
":",
"self",
".",
"inherit_attributes",
"(",
"module_name",
",",
"parent_module",
")",
"attributes",
".",
"set",
"(",
"\"parent-module\"",
",",
"parent_module",
",",
"exact",
"=",
"1",
")",
"if",
"jamroot",
":",
"attributes",
".",
"set",
"(",
"\"project-root\"",
",",
"location",
",",
"exact",
"=",
"1",
")",
"parent",
"=",
"None",
"if",
"parent_module",
":",
"parent",
"=",
"self",
".",
"target",
"(",
"parent_module",
")",
"if",
"module_name",
"not",
"in",
"self",
".",
"module2target",
":",
"target",
"=",
"b2",
".",
"build",
".",
"targets",
".",
"ProjectTarget",
"(",
"self",
".",
"manager",
",",
"module_name",
",",
"module_name",
",",
"parent",
",",
"self",
".",
"attribute",
"(",
"module_name",
",",
"\"requirements\"",
")",
",",
"# FIXME: why we need to pass this? It's not",
"# passed in jam code.",
"self",
".",
"attribute",
"(",
"module_name",
",",
"\"default-build\"",
")",
")",
"self",
".",
"module2target",
"[",
"module_name",
"]",
"=",
"target",
"self",
".",
"current_project",
"=",
"self",
".",
"target",
"(",
"module_name",
")"
] | Initialize the module for a project.
module-name is the name of the project module.
location is the location (directory) of the project to initialize.
If not specified, standalone project will be initialized
standalone_path is the path to the source-location.
this should only be called from the python side. | [
"Initialize",
"the",
"module",
"for",
"a",
"project",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L412-L509 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.inherit_attributes | def inherit_attributes(self, project_module, parent_module):
"""Make 'project-module' inherit attributes of project
root and parent module."""
assert isinstance(project_module, basestring)
assert isinstance(parent_module, basestring)
attributes = self.module2attributes[project_module]
pattributes = self.module2attributes[parent_module]
# Parent module might be locationless user-config.
# FIXME:
#if [ modules.binding $(parent-module) ]
#{
# $(attributes).set parent : [ path.parent
# [ path.make [ modules.binding $(parent-module) ] ] ] ;
# }
attributes.set("project-root", pattributes.get("project-root"), exact=True)
attributes.set("default-build", pattributes.get("default-build"), exact=True)
attributes.set("requirements", pattributes.get("requirements"), exact=True)
attributes.set("usage-requirements",
pattributes.get("usage-requirements"), exact=1)
parent_build_dir = pattributes.get("build-dir")
if parent_build_dir:
# Have to compute relative path from parent dir to our dir
# Convert both paths to absolute, since we cannot
# find relative path from ".." to "."
location = attributes.get("location")
parent_location = pattributes.get("location")
our_dir = os.path.join(os.getcwd(), location)
parent_dir = os.path.join(os.getcwd(), parent_location)
build_dir = os.path.join(parent_build_dir,
os.path.relpath(our_dir, parent_dir))
attributes.set("build-dir", build_dir, exact=True) | python | def inherit_attributes(self, project_module, parent_module):
"""Make 'project-module' inherit attributes of project
root and parent module."""
assert isinstance(project_module, basestring)
assert isinstance(parent_module, basestring)
attributes = self.module2attributes[project_module]
pattributes = self.module2attributes[parent_module]
# Parent module might be locationless user-config.
# FIXME:
#if [ modules.binding $(parent-module) ]
#{
# $(attributes).set parent : [ path.parent
# [ path.make [ modules.binding $(parent-module) ] ] ] ;
# }
attributes.set("project-root", pattributes.get("project-root"), exact=True)
attributes.set("default-build", pattributes.get("default-build"), exact=True)
attributes.set("requirements", pattributes.get("requirements"), exact=True)
attributes.set("usage-requirements",
pattributes.get("usage-requirements"), exact=1)
parent_build_dir = pattributes.get("build-dir")
if parent_build_dir:
# Have to compute relative path from parent dir to our dir
# Convert both paths to absolute, since we cannot
# find relative path from ".." to "."
location = attributes.get("location")
parent_location = pattributes.get("location")
our_dir = os.path.join(os.getcwd(), location)
parent_dir = os.path.join(os.getcwd(), parent_location)
build_dir = os.path.join(parent_build_dir,
os.path.relpath(our_dir, parent_dir))
attributes.set("build-dir", build_dir, exact=True) | [
"def",
"inherit_attributes",
"(",
"self",
",",
"project_module",
",",
"parent_module",
")",
":",
"assert",
"isinstance",
"(",
"project_module",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"parent_module",
",",
"basestring",
")",
"attributes",
"=",
"self",
".",
"module2attributes",
"[",
"project_module",
"]",
"pattributes",
"=",
"self",
".",
"module2attributes",
"[",
"parent_module",
"]",
"# Parent module might be locationless user-config.",
"# FIXME:",
"#if [ modules.binding $(parent-module) ]",
"#{",
"# $(attributes).set parent : [ path.parent",
"# [ path.make [ modules.binding $(parent-module) ] ] ] ;",
"# }",
"attributes",
".",
"set",
"(",
"\"project-root\"",
",",
"pattributes",
".",
"get",
"(",
"\"project-root\"",
")",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"default-build\"",
",",
"pattributes",
".",
"get",
"(",
"\"default-build\"",
")",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"requirements\"",
",",
"pattributes",
".",
"get",
"(",
"\"requirements\"",
")",
",",
"exact",
"=",
"True",
")",
"attributes",
".",
"set",
"(",
"\"usage-requirements\"",
",",
"pattributes",
".",
"get",
"(",
"\"usage-requirements\"",
")",
",",
"exact",
"=",
"1",
")",
"parent_build_dir",
"=",
"pattributes",
".",
"get",
"(",
"\"build-dir\"",
")",
"if",
"parent_build_dir",
":",
"# Have to compute relative path from parent dir to our dir",
"# Convert both paths to absolute, since we cannot",
"# find relative path from \"..\" to \".\"",
"location",
"=",
"attributes",
".",
"get",
"(",
"\"location\"",
")",
"parent_location",
"=",
"pattributes",
".",
"get",
"(",
"\"location\"",
")",
"our_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"location",
")",
"parent_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"parent_location",
")",
"build_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"parent_build_dir",
",",
"os",
".",
"path",
".",
"relpath",
"(",
"our_dir",
",",
"parent_dir",
")",
")",
"attributes",
".",
"set",
"(",
"\"build-dir\"",
",",
"build_dir",
",",
"exact",
"=",
"True",
")"
] | Make 'project-module' inherit attributes of project
root and parent module. | [
"Make",
"project",
"-",
"module",
"inherit",
"attributes",
"of",
"project",
"root",
"and",
"parent",
"module",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L511-L549 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.register_id | def register_id(self, id, module):
"""Associate the given id with the given project module."""
assert isinstance(id, basestring)
assert isinstance(module, basestring)
self.id2module[id] = module | python | def register_id(self, id, module):
"""Associate the given id with the given project module."""
assert isinstance(id, basestring)
assert isinstance(module, basestring)
self.id2module[id] = module | [
"def",
"register_id",
"(",
"self",
",",
"id",
",",
"module",
")",
":",
"assert",
"isinstance",
"(",
"id",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"module",
",",
"basestring",
")",
"self",
".",
"id2module",
"[",
"id",
"]",
"=",
"module"
] | Associate the given id with the given project module. | [
"Associate",
"the",
"given",
"id",
"with",
"the",
"given",
"project",
"module",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L551-L555 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.push_current | def push_current(self, project):
"""Temporary changes the current project to 'project'. Should
be followed by 'pop-current'."""
if __debug__:
from .targets import ProjectTarget
assert isinstance(project, ProjectTarget)
self.saved_current_project.append(self.current_project)
self.current_project = project | python | def push_current(self, project):
"""Temporary changes the current project to 'project'. Should
be followed by 'pop-current'."""
if __debug__:
from .targets import ProjectTarget
assert isinstance(project, ProjectTarget)
self.saved_current_project.append(self.current_project)
self.current_project = project | [
"def",
"push_current",
"(",
"self",
",",
"project",
")",
":",
"if",
"__debug__",
":",
"from",
".",
"targets",
"import",
"ProjectTarget",
"assert",
"isinstance",
"(",
"project",
",",
"ProjectTarget",
")",
"self",
".",
"saved_current_project",
".",
"append",
"(",
"self",
".",
"current_project",
")",
"self",
".",
"current_project",
"=",
"project"
] | Temporary changes the current project to 'project'. Should
be followed by 'pop-current'. | [
"Temporary",
"changes",
"the",
"current",
"project",
"to",
"project",
".",
"Should",
"be",
"followed",
"by",
"pop",
"-",
"current",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L572-L579 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.attribute | def attribute(self, project, attribute):
"""Returns the value of the specified attribute in the
specified jamfile module."""
assert isinstance(project, basestring)
assert isinstance(attribute, basestring)
try:
return self.module2attributes[project].get(attribute)
except:
raise BaseException("No attribute '%s' for project %s" % (attribute, project)) | python | def attribute(self, project, attribute):
"""Returns the value of the specified attribute in the
specified jamfile module."""
assert isinstance(project, basestring)
assert isinstance(attribute, basestring)
try:
return self.module2attributes[project].get(attribute)
except:
raise BaseException("No attribute '%s' for project %s" % (attribute, project)) | [
"def",
"attribute",
"(",
"self",
",",
"project",
",",
"attribute",
")",
":",
"assert",
"isinstance",
"(",
"project",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"attribute",
",",
"basestring",
")",
"try",
":",
"return",
"self",
".",
"module2attributes",
"[",
"project",
"]",
".",
"get",
"(",
"attribute",
")",
"except",
":",
"raise",
"BaseException",
"(",
"\"No attribute '%s' for project %s\"",
"%",
"(",
"attribute",
",",
"project",
")",
")"
] | Returns the value of the specified attribute in the
specified jamfile module. | [
"Returns",
"the",
"value",
"of",
"the",
"specified",
"attribute",
"in",
"the",
"specified",
"jamfile",
"module",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L593-L601 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.attributeDefault | def attributeDefault(self, project, attribute, default):
"""Returns the value of the specified attribute in the
specified jamfile module."""
assert isinstance(project, basestring)
assert isinstance(attribute, basestring)
assert isinstance(default, basestring) or default is None
return self.module2attributes[project].getDefault(attribute, default) | python | def attributeDefault(self, project, attribute, default):
"""Returns the value of the specified attribute in the
specified jamfile module."""
assert isinstance(project, basestring)
assert isinstance(attribute, basestring)
assert isinstance(default, basestring) or default is None
return self.module2attributes[project].getDefault(attribute, default) | [
"def",
"attributeDefault",
"(",
"self",
",",
"project",
",",
"attribute",
",",
"default",
")",
":",
"assert",
"isinstance",
"(",
"project",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"attribute",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"default",
",",
"basestring",
")",
"or",
"default",
"is",
"None",
"return",
"self",
".",
"module2attributes",
"[",
"project",
"]",
".",
"getDefault",
"(",
"attribute",
",",
"default",
")"
] | Returns the value of the specified attribute in the
specified jamfile module. | [
"Returns",
"the",
"value",
"of",
"the",
"specified",
"attribute",
"in",
"the",
"specified",
"jamfile",
"module",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L603-L609 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.target | def target(self, project_module):
"""Returns the project target corresponding to the 'project-module'."""
assert isinstance(project_module, basestring)
if project_module not in self.module2target:
self.module2target[project_module] = \
b2.build.targets.ProjectTarget(project_module, project_module,
self.attribute(project_module, "requirements"))
return self.module2target[project_module] | python | def target(self, project_module):
"""Returns the project target corresponding to the 'project-module'."""
assert isinstance(project_module, basestring)
if project_module not in self.module2target:
self.module2target[project_module] = \
b2.build.targets.ProjectTarget(project_module, project_module,
self.attribute(project_module, "requirements"))
return self.module2target[project_module] | [
"def",
"target",
"(",
"self",
",",
"project_module",
")",
":",
"assert",
"isinstance",
"(",
"project_module",
",",
"basestring",
")",
"if",
"project_module",
"not",
"in",
"self",
".",
"module2target",
":",
"self",
".",
"module2target",
"[",
"project_module",
"]",
"=",
"b2",
".",
"build",
".",
"targets",
".",
"ProjectTarget",
"(",
"project_module",
",",
"project_module",
",",
"self",
".",
"attribute",
"(",
"project_module",
",",
"\"requirements\"",
")",
")",
"return",
"self",
".",
"module2target",
"[",
"project_module",
"]"
] | Returns the project target corresponding to the 'project-module'. | [
"Returns",
"the",
"project",
"target",
"corresponding",
"to",
"the",
"project",
"-",
"module",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L611-L619 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.add_rule | def add_rule(self, name, callable_):
"""Makes rule 'name' available to all subsequently loaded Jamfiles.
Calling that rule wil relay to 'callable'."""
assert isinstance(name, basestring)
assert callable(callable_)
self.project_rules_.add_rule(name, callable_) | python | def add_rule(self, name, callable_):
"""Makes rule 'name' available to all subsequently loaded Jamfiles.
Calling that rule wil relay to 'callable'."""
assert isinstance(name, basestring)
assert callable(callable_)
self.project_rules_.add_rule(name, callable_) | [
"def",
"add_rule",
"(",
"self",
",",
"name",
",",
"callable_",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"basestring",
")",
"assert",
"callable",
"(",
"callable_",
")",
"self",
".",
"project_rules_",
".",
"add_rule",
"(",
"name",
",",
"callable_",
")"
] | Makes rule 'name' available to all subsequently loaded Jamfiles.
Calling that rule wil relay to 'callable'. | [
"Makes",
"rule",
"name",
"available",
"to",
"all",
"subsequently",
"loaded",
"Jamfiles",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L639-L645 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.__build_python_module_cache | def __build_python_module_cache(self):
"""Recursively walks through the b2/src subdirectories and
creates an index of base module name to package name. The
index is stored within self.__python_module_cache and allows
for an O(1) module lookup.
For example, given the base module name `toolset`,
self.__python_module_cache['toolset'] will return
'b2.build.toolset'
pkgutil.walk_packages() will find any python package
provided a directory contains an __init__.py. This has the
added benefit of allowing libraries to be installed and
automatically avaiable within the contrib directory.
*Note*: pkgutil.walk_packages() will import any subpackage
in order to access its __path__variable. Meaning:
any initialization code will be run if the package hasn't
already been imported.
"""
cache = {}
for importer, mname, ispkg in pkgutil.walk_packages(b2.__path__, prefix='b2.'):
basename = mname.split('.')[-1]
# since the jam code is only going to have "import toolset ;"
# it doesn't matter if there are separately named "b2.build.toolset" and
# "b2.contrib.toolset" as it is impossible to know which the user is
# referring to.
if basename in cache:
self.manager.errors()('duplicate module name "{0}" '
'found in boost-build path'.format(basename))
cache[basename] = mname
self.__python_module_cache = cache | python | def __build_python_module_cache(self):
"""Recursively walks through the b2/src subdirectories and
creates an index of base module name to package name. The
index is stored within self.__python_module_cache and allows
for an O(1) module lookup.
For example, given the base module name `toolset`,
self.__python_module_cache['toolset'] will return
'b2.build.toolset'
pkgutil.walk_packages() will find any python package
provided a directory contains an __init__.py. This has the
added benefit of allowing libraries to be installed and
automatically avaiable within the contrib directory.
*Note*: pkgutil.walk_packages() will import any subpackage
in order to access its __path__variable. Meaning:
any initialization code will be run if the package hasn't
already been imported.
"""
cache = {}
for importer, mname, ispkg in pkgutil.walk_packages(b2.__path__, prefix='b2.'):
basename = mname.split('.')[-1]
# since the jam code is only going to have "import toolset ;"
# it doesn't matter if there are separately named "b2.build.toolset" and
# "b2.contrib.toolset" as it is impossible to know which the user is
# referring to.
if basename in cache:
self.manager.errors()('duplicate module name "{0}" '
'found in boost-build path'.format(basename))
cache[basename] = mname
self.__python_module_cache = cache | [
"def",
"__build_python_module_cache",
"(",
"self",
")",
":",
"cache",
"=",
"{",
"}",
"for",
"importer",
",",
"mname",
",",
"ispkg",
"in",
"pkgutil",
".",
"walk_packages",
"(",
"b2",
".",
"__path__",
",",
"prefix",
"=",
"'b2.'",
")",
":",
"basename",
"=",
"mname",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]",
"# since the jam code is only going to have \"import toolset ;\"",
"# it doesn't matter if there are separately named \"b2.build.toolset\" and",
"# \"b2.contrib.toolset\" as it is impossible to know which the user is",
"# referring to.",
"if",
"basename",
"in",
"cache",
":",
"self",
".",
"manager",
".",
"errors",
"(",
")",
"(",
"'duplicate module name \"{0}\" '",
"'found in boost-build path'",
".",
"format",
"(",
"basename",
")",
")",
"cache",
"[",
"basename",
"]",
"=",
"mname",
"self",
".",
"__python_module_cache",
"=",
"cache"
] | Recursively walks through the b2/src subdirectories and
creates an index of base module name to package name. The
index is stored within self.__python_module_cache and allows
for an O(1) module lookup.
For example, given the base module name `toolset`,
self.__python_module_cache['toolset'] will return
'b2.build.toolset'
pkgutil.walk_packages() will find any python package
provided a directory contains an __init__.py. This has the
added benefit of allowing libraries to be installed and
automatically avaiable within the contrib directory.
*Note*: pkgutil.walk_packages() will import any subpackage
in order to access its __path__variable. Meaning:
any initialization code will be run if the package hasn't
already been imported. | [
"Recursively",
"walks",
"through",
"the",
"b2",
"/",
"src",
"subdirectories",
"and",
"creates",
"an",
"index",
"of",
"base",
"module",
"name",
"to",
"package",
"name",
".",
"The",
"index",
"is",
"stored",
"within",
"self",
".",
"__python_module_cache",
"and",
"allows",
"for",
"an",
"O",
"(",
"1",
")",
"module",
"lookup",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L693-L724 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRegistry.load_module | def load_module(self, name, extra_path=None):
"""Load a Python module that should be useable from Jamfiles.
There are generally two types of modules Jamfiles might want to
use:
- Core Boost.Build. Those are imported using plain names, e.g.
'toolset', so this function checks if we have module named
b2.package.module already.
- Python modules in the same directory as Jamfile. We don't
want to even temporary add Jamfile's directory to sys.path,
since then we might get naming conflicts between standard
Python modules and those.
"""
assert isinstance(name, basestring)
assert is_iterable_typed(extra_path, basestring) or extra_path is None
# See if we loaded module of this name already
existing = self.loaded_tool_modules_.get(name)
if existing:
return existing
# check the extra path as well as any paths outside
# of the b2 package and import the module if it exists
b2_path = os.path.normpath(b2.__path__[0])
# normalize the pathing in the BOOST_BUILD_PATH.
# this allows for using startswith() to determine
# if a path is a subdirectory of the b2 root_path
paths = [os.path.normpath(p) for p in self.manager.boost_build_path()]
# remove all paths that start with b2's root_path
paths = [p for p in paths if not p.startswith(b2_path)]
# add any extra paths
paths.extend(extra_path)
try:
# find_module is used so that the pyc's can be used.
# an ImportError is raised if not found
f, location, description = imp.find_module(name, paths)
except ImportError:
# if the module is not found in the b2 package,
# this error will be handled later
pass
else:
# we've found the module, now let's try loading it.
# it's possible that the module itself contains an ImportError
# which is why we're loading it in this else clause so that the
# proper error message is shown to the end user.
# TODO: does this module name really need to be mangled like this?
mname = name + "__for_jamfile"
self.loaded_tool_module_path_[mname] = location
module = imp.load_module(mname, f, location, description)
self.loaded_tool_modules_[name] = module
return module
# the cache is created here due to possibly importing packages
# that end up calling get_manager() which might fail
if not self.__python_module_cache:
self.__build_python_module_cache()
underscore_name = name.replace('-', '_')
# check to see if the module is within the b2 package
# and already loaded
mname = self.__python_module_cache.get(underscore_name)
if mname in sys.modules:
return sys.modules[mname]
# otherwise, if the module name is within the cache,
# the module exists within the BOOST_BUILD_PATH,
# load it.
elif mname:
# in some cases, self.loaded_tool_module_path_ needs to
# have the path to the file during the import
# (project.initialize() for example),
# so the path needs to be set *before* importing the module.
path = os.path.join(b2.__path__[0], *mname.split('.')[1:])
self.loaded_tool_module_path_[mname] = path
# mname is guaranteed to be importable since it was
# found within the cache
__import__(mname)
module = sys.modules[mname]
self.loaded_tool_modules_[name] = module
return module
self.manager.errors()("Cannot find module '%s'" % name) | python | def load_module(self, name, extra_path=None):
"""Load a Python module that should be useable from Jamfiles.
There are generally two types of modules Jamfiles might want to
use:
- Core Boost.Build. Those are imported using plain names, e.g.
'toolset', so this function checks if we have module named
b2.package.module already.
- Python modules in the same directory as Jamfile. We don't
want to even temporary add Jamfile's directory to sys.path,
since then we might get naming conflicts between standard
Python modules and those.
"""
assert isinstance(name, basestring)
assert is_iterable_typed(extra_path, basestring) or extra_path is None
# See if we loaded module of this name already
existing = self.loaded_tool_modules_.get(name)
if existing:
return existing
# check the extra path as well as any paths outside
# of the b2 package and import the module if it exists
b2_path = os.path.normpath(b2.__path__[0])
# normalize the pathing in the BOOST_BUILD_PATH.
# this allows for using startswith() to determine
# if a path is a subdirectory of the b2 root_path
paths = [os.path.normpath(p) for p in self.manager.boost_build_path()]
# remove all paths that start with b2's root_path
paths = [p for p in paths if not p.startswith(b2_path)]
# add any extra paths
paths.extend(extra_path)
try:
# find_module is used so that the pyc's can be used.
# an ImportError is raised if not found
f, location, description = imp.find_module(name, paths)
except ImportError:
# if the module is not found in the b2 package,
# this error will be handled later
pass
else:
# we've found the module, now let's try loading it.
# it's possible that the module itself contains an ImportError
# which is why we're loading it in this else clause so that the
# proper error message is shown to the end user.
# TODO: does this module name really need to be mangled like this?
mname = name + "__for_jamfile"
self.loaded_tool_module_path_[mname] = location
module = imp.load_module(mname, f, location, description)
self.loaded_tool_modules_[name] = module
return module
# the cache is created here due to possibly importing packages
# that end up calling get_manager() which might fail
if not self.__python_module_cache:
self.__build_python_module_cache()
underscore_name = name.replace('-', '_')
# check to see if the module is within the b2 package
# and already loaded
mname = self.__python_module_cache.get(underscore_name)
if mname in sys.modules:
return sys.modules[mname]
# otherwise, if the module name is within the cache,
# the module exists within the BOOST_BUILD_PATH,
# load it.
elif mname:
# in some cases, self.loaded_tool_module_path_ needs to
# have the path to the file during the import
# (project.initialize() for example),
# so the path needs to be set *before* importing the module.
path = os.path.join(b2.__path__[0], *mname.split('.')[1:])
self.loaded_tool_module_path_[mname] = path
# mname is guaranteed to be importable since it was
# found within the cache
__import__(mname)
module = sys.modules[mname]
self.loaded_tool_modules_[name] = module
return module
self.manager.errors()("Cannot find module '%s'" % name) | [
"def",
"load_module",
"(",
"self",
",",
"name",
",",
"extra_path",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"name",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"extra_path",
",",
"basestring",
")",
"or",
"extra_path",
"is",
"None",
"# See if we loaded module of this name already",
"existing",
"=",
"self",
".",
"loaded_tool_modules_",
".",
"get",
"(",
"name",
")",
"if",
"existing",
":",
"return",
"existing",
"# check the extra path as well as any paths outside",
"# of the b2 package and import the module if it exists",
"b2_path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"b2",
".",
"__path__",
"[",
"0",
"]",
")",
"# normalize the pathing in the BOOST_BUILD_PATH.",
"# this allows for using startswith() to determine",
"# if a path is a subdirectory of the b2 root_path",
"paths",
"=",
"[",
"os",
".",
"path",
".",
"normpath",
"(",
"p",
")",
"for",
"p",
"in",
"self",
".",
"manager",
".",
"boost_build_path",
"(",
")",
"]",
"# remove all paths that start with b2's root_path",
"paths",
"=",
"[",
"p",
"for",
"p",
"in",
"paths",
"if",
"not",
"p",
".",
"startswith",
"(",
"b2_path",
")",
"]",
"# add any extra paths",
"paths",
".",
"extend",
"(",
"extra_path",
")",
"try",
":",
"# find_module is used so that the pyc's can be used.",
"# an ImportError is raised if not found",
"f",
",",
"location",
",",
"description",
"=",
"imp",
".",
"find_module",
"(",
"name",
",",
"paths",
")",
"except",
"ImportError",
":",
"# if the module is not found in the b2 package,",
"# this error will be handled later",
"pass",
"else",
":",
"# we've found the module, now let's try loading it.",
"# it's possible that the module itself contains an ImportError",
"# which is why we're loading it in this else clause so that the",
"# proper error message is shown to the end user.",
"# TODO: does this module name really need to be mangled like this?",
"mname",
"=",
"name",
"+",
"\"__for_jamfile\"",
"self",
".",
"loaded_tool_module_path_",
"[",
"mname",
"]",
"=",
"location",
"module",
"=",
"imp",
".",
"load_module",
"(",
"mname",
",",
"f",
",",
"location",
",",
"description",
")",
"self",
".",
"loaded_tool_modules_",
"[",
"name",
"]",
"=",
"module",
"return",
"module",
"# the cache is created here due to possibly importing packages",
"# that end up calling get_manager() which might fail",
"if",
"not",
"self",
".",
"__python_module_cache",
":",
"self",
".",
"__build_python_module_cache",
"(",
")",
"underscore_name",
"=",
"name",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"# check to see if the module is within the b2 package",
"# and already loaded",
"mname",
"=",
"self",
".",
"__python_module_cache",
".",
"get",
"(",
"underscore_name",
")",
"if",
"mname",
"in",
"sys",
".",
"modules",
":",
"return",
"sys",
".",
"modules",
"[",
"mname",
"]",
"# otherwise, if the module name is within the cache,",
"# the module exists within the BOOST_BUILD_PATH,",
"# load it.",
"elif",
"mname",
":",
"# in some cases, self.loaded_tool_module_path_ needs to",
"# have the path to the file during the import",
"# (project.initialize() for example),",
"# so the path needs to be set *before* importing the module.",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"b2",
".",
"__path__",
"[",
"0",
"]",
",",
"*",
"mname",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
":",
"]",
")",
"self",
".",
"loaded_tool_module_path_",
"[",
"mname",
"]",
"=",
"path",
"# mname is guaranteed to be importable since it was",
"# found within the cache",
"__import__",
"(",
"mname",
")",
"module",
"=",
"sys",
".",
"modules",
"[",
"mname",
"]",
"self",
".",
"loaded_tool_modules_",
"[",
"name",
"]",
"=",
"module",
"return",
"module",
"self",
".",
"manager",
".",
"errors",
"(",
")",
"(",
"\"Cannot find module '%s'\"",
"%",
"name",
")"
] | Load a Python module that should be useable from Jamfiles.
There are generally two types of modules Jamfiles might want to
use:
- Core Boost.Build. Those are imported using plain names, e.g.
'toolset', so this function checks if we have module named
b2.package.module already.
- Python modules in the same directory as Jamfile. We don't
want to even temporary add Jamfile's directory to sys.path,
since then we might get naming conflicts between standard
Python modules and those. | [
"Load",
"a",
"Python",
"module",
"that",
"should",
"be",
"useable",
"from",
"Jamfiles",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L726-L806 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectAttributes.set | def set(self, attribute, specification, exact=False):
"""Set the named attribute from the specification given by the user.
The value actually set may be different."""
assert isinstance(attribute, basestring)
assert isinstance(exact, (int, bool))
if __debug__ and not exact:
if attribute == 'requirements':
assert (isinstance(specification, property_set.PropertySet)
or all(isinstance(s, basestring) for s in specification))
elif attribute in (
'usage-requirements', 'default-build', 'source-location', 'build-dir', 'id'):
assert is_iterable_typed(specification, basestring)
elif __debug__:
assert (
isinstance(specification, (property_set.PropertySet, type(None), basestring))
or all(isinstance(s, basestring) for s in specification)
)
if exact:
self.__dict__[attribute] = specification
elif attribute == "requirements":
self.requirements = property_set.refine_from_user_input(
self.requirements, specification,
self.project_module, self.location)
elif attribute == "usage-requirements":
unconditional = []
for p in specification:
split = property.split_conditional(p)
if split:
unconditional.append(split[1])
else:
unconditional.append(p)
non_free = property.remove("free", unconditional)
if non_free:
get_manager().errors()("usage-requirements %s have non-free properties %s" \
% (specification, non_free))
t = property.translate_paths(
property.create_from_strings(specification, allow_condition=True),
self.location)
existing = self.__dict__.get("usage-requirements")
if existing:
new = property_set.create(existing.all() + t)
else:
new = property_set.create(t)
self.__dict__["usage-requirements"] = new
elif attribute == "default-build":
self.__dict__["default-build"] = property_set.create(specification)
elif attribute == "source-location":
source_location = []
for path in specification:
source_location.append(os.path.join(self.location, path))
self.__dict__["source-location"] = source_location
elif attribute == "build-dir":
self.__dict__["build-dir"] = os.path.join(self.location, specification[0])
elif attribute == "id":
id = specification[0]
if id[0] != '/':
id = "/" + id
self.manager.projects().register_id(id, self.project_module)
self.__dict__["id"] = id
elif not attribute in ["default-build", "location",
"source-location", "parent",
"projects-to-build", "project-root"]:
self.manager.errors()(
"""Invalid project attribute '%s' specified
for project at '%s'""" % (attribute, self.location))
else:
self.__dict__[attribute] = specification | python | def set(self, attribute, specification, exact=False):
"""Set the named attribute from the specification given by the user.
The value actually set may be different."""
assert isinstance(attribute, basestring)
assert isinstance(exact, (int, bool))
if __debug__ and not exact:
if attribute == 'requirements':
assert (isinstance(specification, property_set.PropertySet)
or all(isinstance(s, basestring) for s in specification))
elif attribute in (
'usage-requirements', 'default-build', 'source-location', 'build-dir', 'id'):
assert is_iterable_typed(specification, basestring)
elif __debug__:
assert (
isinstance(specification, (property_set.PropertySet, type(None), basestring))
or all(isinstance(s, basestring) for s in specification)
)
if exact:
self.__dict__[attribute] = specification
elif attribute == "requirements":
self.requirements = property_set.refine_from_user_input(
self.requirements, specification,
self.project_module, self.location)
elif attribute == "usage-requirements":
unconditional = []
for p in specification:
split = property.split_conditional(p)
if split:
unconditional.append(split[1])
else:
unconditional.append(p)
non_free = property.remove("free", unconditional)
if non_free:
get_manager().errors()("usage-requirements %s have non-free properties %s" \
% (specification, non_free))
t = property.translate_paths(
property.create_from_strings(specification, allow_condition=True),
self.location)
existing = self.__dict__.get("usage-requirements")
if existing:
new = property_set.create(existing.all() + t)
else:
new = property_set.create(t)
self.__dict__["usage-requirements"] = new
elif attribute == "default-build":
self.__dict__["default-build"] = property_set.create(specification)
elif attribute == "source-location":
source_location = []
for path in specification:
source_location.append(os.path.join(self.location, path))
self.__dict__["source-location"] = source_location
elif attribute == "build-dir":
self.__dict__["build-dir"] = os.path.join(self.location, specification[0])
elif attribute == "id":
id = specification[0]
if id[0] != '/':
id = "/" + id
self.manager.projects().register_id(id, self.project_module)
self.__dict__["id"] = id
elif not attribute in ["default-build", "location",
"source-location", "parent",
"projects-to-build", "project-root"]:
self.manager.errors()(
"""Invalid project attribute '%s' specified
for project at '%s'""" % (attribute, self.location))
else:
self.__dict__[attribute] = specification | [
"def",
"set",
"(",
"self",
",",
"attribute",
",",
"specification",
",",
"exact",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"attribute",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"exact",
",",
"(",
"int",
",",
"bool",
")",
")",
"if",
"__debug__",
"and",
"not",
"exact",
":",
"if",
"attribute",
"==",
"'requirements'",
":",
"assert",
"(",
"isinstance",
"(",
"specification",
",",
"property_set",
".",
"PropertySet",
")",
"or",
"all",
"(",
"isinstance",
"(",
"s",
",",
"basestring",
")",
"for",
"s",
"in",
"specification",
")",
")",
"elif",
"attribute",
"in",
"(",
"'usage-requirements'",
",",
"'default-build'",
",",
"'source-location'",
",",
"'build-dir'",
",",
"'id'",
")",
":",
"assert",
"is_iterable_typed",
"(",
"specification",
",",
"basestring",
")",
"elif",
"__debug__",
":",
"assert",
"(",
"isinstance",
"(",
"specification",
",",
"(",
"property_set",
".",
"PropertySet",
",",
"type",
"(",
"None",
")",
",",
"basestring",
")",
")",
"or",
"all",
"(",
"isinstance",
"(",
"s",
",",
"basestring",
")",
"for",
"s",
"in",
"specification",
")",
")",
"if",
"exact",
":",
"self",
".",
"__dict__",
"[",
"attribute",
"]",
"=",
"specification",
"elif",
"attribute",
"==",
"\"requirements\"",
":",
"self",
".",
"requirements",
"=",
"property_set",
".",
"refine_from_user_input",
"(",
"self",
".",
"requirements",
",",
"specification",
",",
"self",
".",
"project_module",
",",
"self",
".",
"location",
")",
"elif",
"attribute",
"==",
"\"usage-requirements\"",
":",
"unconditional",
"=",
"[",
"]",
"for",
"p",
"in",
"specification",
":",
"split",
"=",
"property",
".",
"split_conditional",
"(",
"p",
")",
"if",
"split",
":",
"unconditional",
".",
"append",
"(",
"split",
"[",
"1",
"]",
")",
"else",
":",
"unconditional",
".",
"append",
"(",
"p",
")",
"non_free",
"=",
"property",
".",
"remove",
"(",
"\"free\"",
",",
"unconditional",
")",
"if",
"non_free",
":",
"get_manager",
"(",
")",
".",
"errors",
"(",
")",
"(",
"\"usage-requirements %s have non-free properties %s\"",
"%",
"(",
"specification",
",",
"non_free",
")",
")",
"t",
"=",
"property",
".",
"translate_paths",
"(",
"property",
".",
"create_from_strings",
"(",
"specification",
",",
"allow_condition",
"=",
"True",
")",
",",
"self",
".",
"location",
")",
"existing",
"=",
"self",
".",
"__dict__",
".",
"get",
"(",
"\"usage-requirements\"",
")",
"if",
"existing",
":",
"new",
"=",
"property_set",
".",
"create",
"(",
"existing",
".",
"all",
"(",
")",
"+",
"t",
")",
"else",
":",
"new",
"=",
"property_set",
".",
"create",
"(",
"t",
")",
"self",
".",
"__dict__",
"[",
"\"usage-requirements\"",
"]",
"=",
"new",
"elif",
"attribute",
"==",
"\"default-build\"",
":",
"self",
".",
"__dict__",
"[",
"\"default-build\"",
"]",
"=",
"property_set",
".",
"create",
"(",
"specification",
")",
"elif",
"attribute",
"==",
"\"source-location\"",
":",
"source_location",
"=",
"[",
"]",
"for",
"path",
"in",
"specification",
":",
"source_location",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"location",
",",
"path",
")",
")",
"self",
".",
"__dict__",
"[",
"\"source-location\"",
"]",
"=",
"source_location",
"elif",
"attribute",
"==",
"\"build-dir\"",
":",
"self",
".",
"__dict__",
"[",
"\"build-dir\"",
"]",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"location",
",",
"specification",
"[",
"0",
"]",
")",
"elif",
"attribute",
"==",
"\"id\"",
":",
"id",
"=",
"specification",
"[",
"0",
"]",
"if",
"id",
"[",
"0",
"]",
"!=",
"'/'",
":",
"id",
"=",
"\"/\"",
"+",
"id",
"self",
".",
"manager",
".",
"projects",
"(",
")",
".",
"register_id",
"(",
"id",
",",
"self",
".",
"project_module",
")",
"self",
".",
"__dict__",
"[",
"\"id\"",
"]",
"=",
"id",
"elif",
"not",
"attribute",
"in",
"[",
"\"default-build\"",
",",
"\"location\"",
",",
"\"source-location\"",
",",
"\"parent\"",
",",
"\"projects-to-build\"",
",",
"\"project-root\"",
"]",
":",
"self",
".",
"manager",
".",
"errors",
"(",
")",
"(",
"\"\"\"Invalid project attribute '%s' specified\nfor project at '%s'\"\"\"",
"%",
"(",
"attribute",
",",
"self",
".",
"location",
")",
")",
"else",
":",
"self",
".",
"__dict__",
"[",
"attribute",
"]",
"=",
"specification"
] | Set the named attribute from the specification given by the user.
The value actually set may be different. | [
"Set",
"the",
"named",
"attribute",
"from",
"the",
"specification",
"given",
"by",
"the",
"user",
".",
"The",
"value",
"actually",
"set",
"may",
"be",
"different",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L867-L944 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectAttributes.dump | def dump(self):
"""Prints the project attributes."""
id = self.get("id")
if not id:
id = "(none)"
else:
id = id[0]
parent = self.get("parent")
if not parent:
parent = "(none)"
else:
parent = parent[0]
print "'%s'" % id
print "Parent project:%s", parent
print "Requirements:%s", self.get("requirements")
print "Default build:%s", string.join(self.get("debuild-build"))
print "Source location:%s", string.join(self.get("source-location"))
print "Projects to build:%s", string.join(self.get("projects-to-build").sort()); | python | def dump(self):
"""Prints the project attributes."""
id = self.get("id")
if not id:
id = "(none)"
else:
id = id[0]
parent = self.get("parent")
if not parent:
parent = "(none)"
else:
parent = parent[0]
print "'%s'" % id
print "Parent project:%s", parent
print "Requirements:%s", self.get("requirements")
print "Default build:%s", string.join(self.get("debuild-build"))
print "Source location:%s", string.join(self.get("source-location"))
print "Projects to build:%s", string.join(self.get("projects-to-build").sort()); | [
"def",
"dump",
"(",
"self",
")",
":",
"id",
"=",
"self",
".",
"get",
"(",
"\"id\"",
")",
"if",
"not",
"id",
":",
"id",
"=",
"\"(none)\"",
"else",
":",
"id",
"=",
"id",
"[",
"0",
"]",
"parent",
"=",
"self",
".",
"get",
"(",
"\"parent\"",
")",
"if",
"not",
"parent",
":",
"parent",
"=",
"\"(none)\"",
"else",
":",
"parent",
"=",
"parent",
"[",
"0",
"]",
"print",
"\"'%s'\"",
"%",
"id",
"print",
"\"Parent project:%s\"",
",",
"parent",
"print",
"\"Requirements:%s\"",
",",
"self",
".",
"get",
"(",
"\"requirements\"",
")",
"print",
"\"Default build:%s\"",
",",
"string",
".",
"join",
"(",
"self",
".",
"get",
"(",
"\"debuild-build\"",
")",
")",
"print",
"\"Source location:%s\"",
",",
"string",
".",
"join",
"(",
"self",
".",
"get",
"(",
"\"source-location\"",
")",
")",
"print",
"\"Projects to build:%s\"",
",",
"string",
".",
"join",
"(",
"self",
".",
"get",
"(",
"\"projects-to-build\"",
")",
".",
"sort",
"(",
")",
")"
] | Prints the project attributes. | [
"Prints",
"the",
"project",
"attributes",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L954-L973 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRules.make_wrapper | def make_wrapper(self, callable_):
"""Given a free-standing function 'callable', return a new
callable that will call 'callable' and report all exceptins,
using 'call_and_report_errors'."""
assert callable(callable_)
def wrapper(*args, **kw):
return self.call_and_report_errors(callable_, *args, **kw)
return wrapper | python | def make_wrapper(self, callable_):
"""Given a free-standing function 'callable', return a new
callable that will call 'callable' and report all exceptins,
using 'call_and_report_errors'."""
assert callable(callable_)
def wrapper(*args, **kw):
return self.call_and_report_errors(callable_, *args, **kw)
return wrapper | [
"def",
"make_wrapper",
"(",
"self",
",",
"callable_",
")",
":",
"assert",
"callable",
"(",
"callable_",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"self",
".",
"call_and_report_errors",
"(",
"callable_",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"return",
"wrapper"
] | Given a free-standing function 'callable', return a new
callable that will call 'callable' and report all exceptins,
using 'call_and_report_errors'. | [
"Given",
"a",
"free",
"-",
"standing",
"function",
"callable",
"return",
"a",
"new",
"callable",
"that",
"will",
"call",
"callable",
"and",
"report",
"all",
"exceptins",
"using",
"call_and_report_errors",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L1044-L1051 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRules.constant | def constant(self, name, value):
"""Declare and set a project global constant.
Project global constants are normal variables but should
not be changed. They are applied to every child Jamfile."""
assert is_iterable_typed(name, basestring)
assert is_iterable_typed(value, basestring)
self.registry.current().add_constant(name[0], value) | python | def constant(self, name, value):
"""Declare and set a project global constant.
Project global constants are normal variables but should
not be changed. They are applied to every child Jamfile."""
assert is_iterable_typed(name, basestring)
assert is_iterable_typed(value, basestring)
self.registry.current().add_constant(name[0], value) | [
"def",
"constant",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"assert",
"is_iterable_typed",
"(",
"name",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"value",
",",
"basestring",
")",
"self",
".",
"registry",
".",
"current",
"(",
")",
".",
"add_constant",
"(",
"name",
"[",
"0",
"]",
",",
"value",
")"
] | Declare and set a project global constant.
Project global constants are normal variables but should
not be changed. They are applied to every child Jamfile. | [
"Declare",
"and",
"set",
"a",
"project",
"global",
"constant",
".",
"Project",
"global",
"constants",
"are",
"normal",
"variables",
"but",
"should",
"not",
"be",
"changed",
".",
"They",
"are",
"applied",
"to",
"every",
"child",
"Jamfile",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L1136-L1142 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRules.path_constant | def path_constant(self, name, value):
"""Declare and set a project global constant, whose value is a path. The
path is adjusted to be relative to the invocation directory. The given
value path is taken to be either absolute, or relative to this project
root."""
assert is_iterable_typed(name, basestring)
assert is_iterable_typed(value, basestring)
if len(value) > 1:
self.registry.manager.errors()("path constant should have one element")
self.registry.current().add_constant(name[0], value, path=1) | python | def path_constant(self, name, value):
"""Declare and set a project global constant, whose value is a path. The
path is adjusted to be relative to the invocation directory. The given
value path is taken to be either absolute, or relative to this project
root."""
assert is_iterable_typed(name, basestring)
assert is_iterable_typed(value, basestring)
if len(value) > 1:
self.registry.manager.errors()("path constant should have one element")
self.registry.current().add_constant(name[0], value, path=1) | [
"def",
"path_constant",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"assert",
"is_iterable_typed",
"(",
"name",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"value",
",",
"basestring",
")",
"if",
"len",
"(",
"value",
")",
">",
"1",
":",
"self",
".",
"registry",
".",
"manager",
".",
"errors",
"(",
")",
"(",
"\"path constant should have one element\"",
")",
"self",
".",
"registry",
".",
"current",
"(",
")",
".",
"add_constant",
"(",
"name",
"[",
"0",
"]",
",",
"value",
",",
"path",
"=",
"1",
")"
] | Declare and set a project global constant, whose value is a path. The
path is adjusted to be relative to the invocation directory. The given
value path is taken to be either absolute, or relative to this project
root. | [
"Declare",
"and",
"set",
"a",
"project",
"global",
"constant",
"whose",
"value",
"is",
"a",
"path",
".",
"The",
"path",
"is",
"adjusted",
"to",
"be",
"relative",
"to",
"the",
"invocation",
"directory",
".",
"The",
"given",
"value",
"path",
"is",
"taken",
"to",
"be",
"either",
"absolute",
"or",
"relative",
"to",
"this",
"project",
"root",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L1144-L1153 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/project.py | ProjectRules.conditional | def conditional(self, condition, requirements):
"""Calculates conditional requirements for multiple requirements
at once. This is a shorthand to be reduce duplication and to
keep an inline declarative syntax. For example:
lib x : x.cpp : [ conditional <toolset>gcc <variant>debug :
<define>DEBUG_EXCEPTION <define>DEBUG_TRACE ] ;
"""
assert is_iterable_typed(condition, basestring)
assert is_iterable_typed(requirements, basestring)
c = string.join(condition, ",")
if c.find(":") != -1:
return [c + r for r in requirements]
else:
return [c + ":" + r for r in requirements] | python | def conditional(self, condition, requirements):
"""Calculates conditional requirements for multiple requirements
at once. This is a shorthand to be reduce duplication and to
keep an inline declarative syntax. For example:
lib x : x.cpp : [ conditional <toolset>gcc <variant>debug :
<define>DEBUG_EXCEPTION <define>DEBUG_TRACE ] ;
"""
assert is_iterable_typed(condition, basestring)
assert is_iterable_typed(requirements, basestring)
c = string.join(condition, ",")
if c.find(":") != -1:
return [c + r for r in requirements]
else:
return [c + ":" + r for r in requirements] | [
"def",
"conditional",
"(",
"self",
",",
"condition",
",",
"requirements",
")",
":",
"assert",
"is_iterable_typed",
"(",
"condition",
",",
"basestring",
")",
"assert",
"is_iterable_typed",
"(",
"requirements",
",",
"basestring",
")",
"c",
"=",
"string",
".",
"join",
"(",
"condition",
",",
"\",\"",
")",
"if",
"c",
".",
"find",
"(",
"\":\"",
")",
"!=",
"-",
"1",
":",
"return",
"[",
"c",
"+",
"r",
"for",
"r",
"in",
"requirements",
"]",
"else",
":",
"return",
"[",
"c",
"+",
"\":\"",
"+",
"r",
"for",
"r",
"in",
"requirements",
"]"
] | Calculates conditional requirements for multiple requirements
at once. This is a shorthand to be reduce duplication and to
keep an inline declarative syntax. For example:
lib x : x.cpp : [ conditional <toolset>gcc <variant>debug :
<define>DEBUG_EXCEPTION <define>DEBUG_TRACE ] ; | [
"Calculates",
"conditional",
"requirements",
"for",
"multiple",
"requirements",
"at",
"once",
".",
"This",
"is",
"a",
"shorthand",
"to",
"be",
"reduce",
"duplication",
"and",
"to",
"keep",
"an",
"inline",
"declarative",
"syntax",
".",
"For",
"example",
":"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/project.py#L1262-L1276 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/array_feature_extractor.py | create_array_feature_extractor | def create_array_feature_extractor(input_features, output_name, extract_indices,
output_type = None):
"""
Creates a feature extractor from an input array feature, return
input_features is a list of one (name, array) tuple.
extract_indices is either an integer or a list. If it's an integer,
the output type is by default a double (but may also be an integer).
If a list, the output type is an array.
"""
# Make sure that our starting stuff is in the proper form.
assert len(input_features) == 1
assert isinstance(input_features[0][1], datatypes.Array)
# Create the model.
spec = _Model_pb2.Model()
spec.specificationVersion = SPECIFICATION_VERSION
if isinstance(extract_indices, _integer_types):
extract_indices = [extract_indices]
if output_type is None:
output_type = datatypes.Double()
elif isinstance(extract_indices, (list, tuple)):
if not all(isinstance(x, _integer_types) for x in extract_indices):
raise TypeError("extract_indices must be an integer or a list of integers.")
if output_type is None:
output_type = datatypes.Array(len(extract_indices))
else:
raise TypeError("extract_indices must be an integer or a list of integers.")
output_features = [(output_name, output_type)]
for idx in extract_indices:
assert idx < input_features[0][1].num_elements
spec.arrayFeatureExtractor.extractIndex.append(idx)
set_transform_interface_params(spec, input_features, output_features)
return spec | python | def create_array_feature_extractor(input_features, output_name, extract_indices,
output_type = None):
"""
Creates a feature extractor from an input array feature, return
input_features is a list of one (name, array) tuple.
extract_indices is either an integer or a list. If it's an integer,
the output type is by default a double (but may also be an integer).
If a list, the output type is an array.
"""
# Make sure that our starting stuff is in the proper form.
assert len(input_features) == 1
assert isinstance(input_features[0][1], datatypes.Array)
# Create the model.
spec = _Model_pb2.Model()
spec.specificationVersion = SPECIFICATION_VERSION
if isinstance(extract_indices, _integer_types):
extract_indices = [extract_indices]
if output_type is None:
output_type = datatypes.Double()
elif isinstance(extract_indices, (list, tuple)):
if not all(isinstance(x, _integer_types) for x in extract_indices):
raise TypeError("extract_indices must be an integer or a list of integers.")
if output_type is None:
output_type = datatypes.Array(len(extract_indices))
else:
raise TypeError("extract_indices must be an integer or a list of integers.")
output_features = [(output_name, output_type)]
for idx in extract_indices:
assert idx < input_features[0][1].num_elements
spec.arrayFeatureExtractor.extractIndex.append(idx)
set_transform_interface_params(spec, input_features, output_features)
return spec | [
"def",
"create_array_feature_extractor",
"(",
"input_features",
",",
"output_name",
",",
"extract_indices",
",",
"output_type",
"=",
"None",
")",
":",
"# Make sure that our starting stuff is in the proper form.",
"assert",
"len",
"(",
"input_features",
")",
"==",
"1",
"assert",
"isinstance",
"(",
"input_features",
"[",
"0",
"]",
"[",
"1",
"]",
",",
"datatypes",
".",
"Array",
")",
"# Create the model.",
"spec",
"=",
"_Model_pb2",
".",
"Model",
"(",
")",
"spec",
".",
"specificationVersion",
"=",
"SPECIFICATION_VERSION",
"if",
"isinstance",
"(",
"extract_indices",
",",
"_integer_types",
")",
":",
"extract_indices",
"=",
"[",
"extract_indices",
"]",
"if",
"output_type",
"is",
"None",
":",
"output_type",
"=",
"datatypes",
".",
"Double",
"(",
")",
"elif",
"isinstance",
"(",
"extract_indices",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"if",
"not",
"all",
"(",
"isinstance",
"(",
"x",
",",
"_integer_types",
")",
"for",
"x",
"in",
"extract_indices",
")",
":",
"raise",
"TypeError",
"(",
"\"extract_indices must be an integer or a list of integers.\"",
")",
"if",
"output_type",
"is",
"None",
":",
"output_type",
"=",
"datatypes",
".",
"Array",
"(",
"len",
"(",
"extract_indices",
")",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"extract_indices must be an integer or a list of integers.\"",
")",
"output_features",
"=",
"[",
"(",
"output_name",
",",
"output_type",
")",
"]",
"for",
"idx",
"in",
"extract_indices",
":",
"assert",
"idx",
"<",
"input_features",
"[",
"0",
"]",
"[",
"1",
"]",
".",
"num_elements",
"spec",
".",
"arrayFeatureExtractor",
".",
"extractIndex",
".",
"append",
"(",
"idx",
")",
"set_transform_interface_params",
"(",
"spec",
",",
"input_features",
",",
"output_features",
")",
"return",
"spec"
] | Creates a feature extractor from an input array feature, return
input_features is a list of one (name, array) tuple.
extract_indices is either an integer or a list. If it's an integer,
the output type is by default a double (but may also be an integer).
If a list, the output type is an array. | [
"Creates",
"a",
"feature",
"extractor",
"from",
"an",
"input",
"array",
"feature",
"return"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/array_feature_extractor.py#L16-L59 | train |
apple/turicreate | deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py | BuildOutputProcessor.add_input | def add_input(self, input):
'''
Add a single build XML output file to our data.
'''
events = xml.dom.pulldom.parse(input)
context = []
for (event,node) in events:
if event == xml.dom.pulldom.START_ELEMENT:
context.append(node)
if node.nodeType == xml.dom.Node.ELEMENT_NODE:
x_f = self.x_name_(*context)
if x_f:
events.expandNode(node)
# expanding eats the end element, hence walking us out one level
context.pop()
# call handler
(x_f[1])(node)
elif event == xml.dom.pulldom.END_ELEMENT:
context.pop() | python | def add_input(self, input):
'''
Add a single build XML output file to our data.
'''
events = xml.dom.pulldom.parse(input)
context = []
for (event,node) in events:
if event == xml.dom.pulldom.START_ELEMENT:
context.append(node)
if node.nodeType == xml.dom.Node.ELEMENT_NODE:
x_f = self.x_name_(*context)
if x_f:
events.expandNode(node)
# expanding eats the end element, hence walking us out one level
context.pop()
# call handler
(x_f[1])(node)
elif event == xml.dom.pulldom.END_ELEMENT:
context.pop() | [
"def",
"add_input",
"(",
"self",
",",
"input",
")",
":",
"events",
"=",
"xml",
".",
"dom",
".",
"pulldom",
".",
"parse",
"(",
"input",
")",
"context",
"=",
"[",
"]",
"for",
"(",
"event",
",",
"node",
")",
"in",
"events",
":",
"if",
"event",
"==",
"xml",
".",
"dom",
".",
"pulldom",
".",
"START_ELEMENT",
":",
"context",
".",
"append",
"(",
"node",
")",
"if",
"node",
".",
"nodeType",
"==",
"xml",
".",
"dom",
".",
"Node",
".",
"ELEMENT_NODE",
":",
"x_f",
"=",
"self",
".",
"x_name_",
"(",
"*",
"context",
")",
"if",
"x_f",
":",
"events",
".",
"expandNode",
"(",
"node",
")",
"# expanding eats the end element, hence walking us out one level",
"context",
".",
"pop",
"(",
")",
"# call handler",
"(",
"x_f",
"[",
"1",
"]",
")",
"(",
"node",
")",
"elif",
"event",
"==",
"xml",
".",
"dom",
".",
"pulldom",
".",
"END_ELEMENT",
":",
"context",
".",
"pop",
"(",
")"
] | Add a single build XML output file to our data. | [
"Add",
"a",
"single",
"build",
"XML",
"output",
"file",
"to",
"our",
"data",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py#L85-L103 | train |
apple/turicreate | deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py | BuildOutputProcessor.x_build_targets_target | def x_build_targets_target( self, node ):
'''
Process the target dependency DAG into an ancestry tree so we can look up
which top-level library and test targets specific build actions correspond to.
'''
target_node = node
name = self.get_child_data(target_node,tag='name',strip=True)
path = self.get_child_data(target_node,tag='path',strip=True)
jam_target = self.get_child_data(target_node,tag='jam-target',strip=True)
#~ Map for jam targets to virtual targets.
self.target[jam_target] = {
'name' : name,
'path' : path
}
#~ Create the ancestry.
dep_node = self.get_child(self.get_child(target_node,tag='dependencies'),tag='dependency')
while dep_node:
child = self.get_data(dep_node,strip=True)
child_jam_target = '<p%s>%s' % (path,child.split('//',1)[1])
self.parent[child_jam_target] = jam_target
dep_node = self.get_sibling(dep_node.nextSibling,tag='dependency')
return None | python | def x_build_targets_target( self, node ):
'''
Process the target dependency DAG into an ancestry tree so we can look up
which top-level library and test targets specific build actions correspond to.
'''
target_node = node
name = self.get_child_data(target_node,tag='name',strip=True)
path = self.get_child_data(target_node,tag='path',strip=True)
jam_target = self.get_child_data(target_node,tag='jam-target',strip=True)
#~ Map for jam targets to virtual targets.
self.target[jam_target] = {
'name' : name,
'path' : path
}
#~ Create the ancestry.
dep_node = self.get_child(self.get_child(target_node,tag='dependencies'),tag='dependency')
while dep_node:
child = self.get_data(dep_node,strip=True)
child_jam_target = '<p%s>%s' % (path,child.split('//',1)[1])
self.parent[child_jam_target] = jam_target
dep_node = self.get_sibling(dep_node.nextSibling,tag='dependency')
return None | [
"def",
"x_build_targets_target",
"(",
"self",
",",
"node",
")",
":",
"target_node",
"=",
"node",
"name",
"=",
"self",
".",
"get_child_data",
"(",
"target_node",
",",
"tag",
"=",
"'name'",
",",
"strip",
"=",
"True",
")",
"path",
"=",
"self",
".",
"get_child_data",
"(",
"target_node",
",",
"tag",
"=",
"'path'",
",",
"strip",
"=",
"True",
")",
"jam_target",
"=",
"self",
".",
"get_child_data",
"(",
"target_node",
",",
"tag",
"=",
"'jam-target'",
",",
"strip",
"=",
"True",
")",
"#~ Map for jam targets to virtual targets.",
"self",
".",
"target",
"[",
"jam_target",
"]",
"=",
"{",
"'name'",
":",
"name",
",",
"'path'",
":",
"path",
"}",
"#~ Create the ancestry.",
"dep_node",
"=",
"self",
".",
"get_child",
"(",
"self",
".",
"get_child",
"(",
"target_node",
",",
"tag",
"=",
"'dependencies'",
")",
",",
"tag",
"=",
"'dependency'",
")",
"while",
"dep_node",
":",
"child",
"=",
"self",
".",
"get_data",
"(",
"dep_node",
",",
"strip",
"=",
"True",
")",
"child_jam_target",
"=",
"'<p%s>%s'",
"%",
"(",
"path",
",",
"child",
".",
"split",
"(",
"'//'",
",",
"1",
")",
"[",
"1",
"]",
")",
"self",
".",
"parent",
"[",
"child_jam_target",
"]",
"=",
"jam_target",
"dep_node",
"=",
"self",
".",
"get_sibling",
"(",
"dep_node",
".",
"nextSibling",
",",
"tag",
"=",
"'dependency'",
")",
"return",
"None"
] | Process the target dependency DAG into an ancestry tree so we can look up
which top-level library and test targets specific build actions correspond to. | [
"Process",
"the",
"target",
"dependency",
"DAG",
"into",
"an",
"ancestry",
"tree",
"so",
"we",
"can",
"look",
"up",
"which",
"top",
"-",
"level",
"library",
"and",
"test",
"targets",
"specific",
"build",
"actions",
"correspond",
"to",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py#L146-L167 | train |
apple/turicreate | deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py | BuildOutputProcessor.x_build_action | def x_build_action( self, node ):
'''
Given a build action log, process into the corresponding test log and
specific test log sub-part.
'''
action_node = node
name = self.get_child(action_node,tag='name')
if name:
name = self.get_data(name)
#~ Based on the action, we decide what sub-section the log
#~ should go into.
action_type = None
if re.match('[^%]+%[^.]+[.](compile)',name):
action_type = 'compile'
elif re.match('[^%]+%[^.]+[.](link|archive)',name):
action_type = 'link'
elif re.match('[^%]+%testing[.](capture-output)',name):
action_type = 'run'
elif re.match('[^%]+%testing[.](expect-failure|expect-success)',name):
action_type = 'result'
else:
# TODO: Enable to see what other actions can be included in the test results.
# action_type = None
action_type = 'other'
#~ print "+ [%s] %s %s :: %s" %(action_type,name,'','')
if action_type:
#~ Get the corresponding test.
(target,test) = self.get_test(action_node,type=action_type)
#~ Skip action that have no corresponding test as they are
#~ regular build actions and don't need to show up in the
#~ regression results.
if not test:
##print "??? [%s] %s %s :: %s" %(action_type,name,target,test)
return None
##print "+++ [%s] %s %s :: %s" %(action_type,name,target,test)
#~ Collect some basic info about the action.
action = {
'command' : self.get_action_command(action_node,action_type),
'output' : self.get_action_output(action_node,action_type),
'info' : self.get_action_info(action_node,action_type)
}
#~ For the test result status we find the appropriate node
#~ based on the type of test. Then adjust the result status
#~ accordingly. This makes the result status reflect the
#~ expectation as the result pages post processing does not
#~ account for this inversion.
action['type'] = action_type
if action_type == 'result':
if re.match(r'^compile',test['test-type']):
action['type'] = 'compile'
elif re.match(r'^link',test['test-type']):
action['type'] = 'link'
elif re.match(r'^run',test['test-type']):
action['type'] = 'run'
#~ The result sub-part we will add this result to.
if action_node.getAttribute('status') == '0':
action['result'] = 'succeed'
else:
action['result'] = 'fail'
# Add the action to the test.
test['actions'].append(action)
# Set the test result if this is the result action for the test.
if action_type == 'result':
test['result'] = action['result']
return None | python | def x_build_action( self, node ):
'''
Given a build action log, process into the corresponding test log and
specific test log sub-part.
'''
action_node = node
name = self.get_child(action_node,tag='name')
if name:
name = self.get_data(name)
#~ Based on the action, we decide what sub-section the log
#~ should go into.
action_type = None
if re.match('[^%]+%[^.]+[.](compile)',name):
action_type = 'compile'
elif re.match('[^%]+%[^.]+[.](link|archive)',name):
action_type = 'link'
elif re.match('[^%]+%testing[.](capture-output)',name):
action_type = 'run'
elif re.match('[^%]+%testing[.](expect-failure|expect-success)',name):
action_type = 'result'
else:
# TODO: Enable to see what other actions can be included in the test results.
# action_type = None
action_type = 'other'
#~ print "+ [%s] %s %s :: %s" %(action_type,name,'','')
if action_type:
#~ Get the corresponding test.
(target,test) = self.get_test(action_node,type=action_type)
#~ Skip action that have no corresponding test as they are
#~ regular build actions and don't need to show up in the
#~ regression results.
if not test:
##print "??? [%s] %s %s :: %s" %(action_type,name,target,test)
return None
##print "+++ [%s] %s %s :: %s" %(action_type,name,target,test)
#~ Collect some basic info about the action.
action = {
'command' : self.get_action_command(action_node,action_type),
'output' : self.get_action_output(action_node,action_type),
'info' : self.get_action_info(action_node,action_type)
}
#~ For the test result status we find the appropriate node
#~ based on the type of test. Then adjust the result status
#~ accordingly. This makes the result status reflect the
#~ expectation as the result pages post processing does not
#~ account for this inversion.
action['type'] = action_type
if action_type == 'result':
if re.match(r'^compile',test['test-type']):
action['type'] = 'compile'
elif re.match(r'^link',test['test-type']):
action['type'] = 'link'
elif re.match(r'^run',test['test-type']):
action['type'] = 'run'
#~ The result sub-part we will add this result to.
if action_node.getAttribute('status') == '0':
action['result'] = 'succeed'
else:
action['result'] = 'fail'
# Add the action to the test.
test['actions'].append(action)
# Set the test result if this is the result action for the test.
if action_type == 'result':
test['result'] = action['result']
return None | [
"def",
"x_build_action",
"(",
"self",
",",
"node",
")",
":",
"action_node",
"=",
"node",
"name",
"=",
"self",
".",
"get_child",
"(",
"action_node",
",",
"tag",
"=",
"'name'",
")",
"if",
"name",
":",
"name",
"=",
"self",
".",
"get_data",
"(",
"name",
")",
"#~ Based on the action, we decide what sub-section the log",
"#~ should go into.",
"action_type",
"=",
"None",
"if",
"re",
".",
"match",
"(",
"'[^%]+%[^.]+[.](compile)'",
",",
"name",
")",
":",
"action_type",
"=",
"'compile'",
"elif",
"re",
".",
"match",
"(",
"'[^%]+%[^.]+[.](link|archive)'",
",",
"name",
")",
":",
"action_type",
"=",
"'link'",
"elif",
"re",
".",
"match",
"(",
"'[^%]+%testing[.](capture-output)'",
",",
"name",
")",
":",
"action_type",
"=",
"'run'",
"elif",
"re",
".",
"match",
"(",
"'[^%]+%testing[.](expect-failure|expect-success)'",
",",
"name",
")",
":",
"action_type",
"=",
"'result'",
"else",
":",
"# TODO: Enable to see what other actions can be included in the test results.",
"# action_type = None",
"action_type",
"=",
"'other'",
"#~ print \"+ [%s] %s %s :: %s\" %(action_type,name,'','')",
"if",
"action_type",
":",
"#~ Get the corresponding test.",
"(",
"target",
",",
"test",
")",
"=",
"self",
".",
"get_test",
"(",
"action_node",
",",
"type",
"=",
"action_type",
")",
"#~ Skip action that have no corresponding test as they are",
"#~ regular build actions and don't need to show up in the",
"#~ regression results.",
"if",
"not",
"test",
":",
"##print \"??? [%s] %s %s :: %s\" %(action_type,name,target,test)",
"return",
"None",
"##print \"+++ [%s] %s %s :: %s\" %(action_type,name,target,test)",
"#~ Collect some basic info about the action.",
"action",
"=",
"{",
"'command'",
":",
"self",
".",
"get_action_command",
"(",
"action_node",
",",
"action_type",
")",
",",
"'output'",
":",
"self",
".",
"get_action_output",
"(",
"action_node",
",",
"action_type",
")",
",",
"'info'",
":",
"self",
".",
"get_action_info",
"(",
"action_node",
",",
"action_type",
")",
"}",
"#~ For the test result status we find the appropriate node",
"#~ based on the type of test. Then adjust the result status",
"#~ accordingly. This makes the result status reflect the",
"#~ expectation as the result pages post processing does not",
"#~ account for this inversion.",
"action",
"[",
"'type'",
"]",
"=",
"action_type",
"if",
"action_type",
"==",
"'result'",
":",
"if",
"re",
".",
"match",
"(",
"r'^compile'",
",",
"test",
"[",
"'test-type'",
"]",
")",
":",
"action",
"[",
"'type'",
"]",
"=",
"'compile'",
"elif",
"re",
".",
"match",
"(",
"r'^link'",
",",
"test",
"[",
"'test-type'",
"]",
")",
":",
"action",
"[",
"'type'",
"]",
"=",
"'link'",
"elif",
"re",
".",
"match",
"(",
"r'^run'",
",",
"test",
"[",
"'test-type'",
"]",
")",
":",
"action",
"[",
"'type'",
"]",
"=",
"'run'",
"#~ The result sub-part we will add this result to.",
"if",
"action_node",
".",
"getAttribute",
"(",
"'status'",
")",
"==",
"'0'",
":",
"action",
"[",
"'result'",
"]",
"=",
"'succeed'",
"else",
":",
"action",
"[",
"'result'",
"]",
"=",
"'fail'",
"# Add the action to the test.",
"test",
"[",
"'actions'",
"]",
".",
"append",
"(",
"action",
")",
"# Set the test result if this is the result action for the test.",
"if",
"action_type",
"==",
"'result'",
":",
"test",
"[",
"'result'",
"]",
"=",
"action",
"[",
"'result'",
"]",
"return",
"None"
] | Given a build action log, process into the corresponding test log and
specific test log sub-part. | [
"Given",
"a",
"build",
"action",
"log",
"process",
"into",
"the",
"corresponding",
"test",
"log",
"and",
"specific",
"test",
"log",
"sub",
"-",
"part",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py#L169-L233 | train |
apple/turicreate | deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py | BuildOutputProcessor.x_build_timestamp | def x_build_timestamp( self, node ):
'''
The time-stamp goes to the corresponding attribute in the result.
'''
self.timestamps.append(self.get_data(node).strip())
return None | python | def x_build_timestamp( self, node ):
'''
The time-stamp goes to the corresponding attribute in the result.
'''
self.timestamps.append(self.get_data(node).strip())
return None | [
"def",
"x_build_timestamp",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"timestamps",
".",
"append",
"(",
"self",
".",
"get_data",
"(",
"node",
")",
".",
"strip",
"(",
")",
")",
"return",
"None"
] | The time-stamp goes to the corresponding attribute in the result. | [
"The",
"time",
"-",
"stamp",
"goes",
"to",
"the",
"corresponding",
"attribute",
"in",
"the",
"result",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py#L235-L240 | train |
apple/turicreate | deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py | BuildConsoleSummaryReport.print_action | def print_action(self, test_succeed, action):
'''
Print the detailed info of failed or always print tests.
'''
#self.info_print(">>> {0}",action.keys())
if not test_succeed or action['info']['always_show_run_output']:
output = action['output'].strip()
if output != "":
p = self.fail_print if action['result'] == 'fail' else self.p_print
self.info_print("")
self.info_print("({0}) {1}",action['info']['name'],action['info']['path'])
p("")
p("{0}",action['command'].strip())
p("")
for line in output.splitlines():
p("{0}",line.encode('utf-8')) | python | def print_action(self, test_succeed, action):
'''
Print the detailed info of failed or always print tests.
'''
#self.info_print(">>> {0}",action.keys())
if not test_succeed or action['info']['always_show_run_output']:
output = action['output'].strip()
if output != "":
p = self.fail_print if action['result'] == 'fail' else self.p_print
self.info_print("")
self.info_print("({0}) {1}",action['info']['name'],action['info']['path'])
p("")
p("{0}",action['command'].strip())
p("")
for line in output.splitlines():
p("{0}",line.encode('utf-8')) | [
"def",
"print_action",
"(",
"self",
",",
"test_succeed",
",",
"action",
")",
":",
"#self.info_print(\">>> {0}\",action.keys())",
"if",
"not",
"test_succeed",
"or",
"action",
"[",
"'info'",
"]",
"[",
"'always_show_run_output'",
"]",
":",
"output",
"=",
"action",
"[",
"'output'",
"]",
".",
"strip",
"(",
")",
"if",
"output",
"!=",
"\"\"",
":",
"p",
"=",
"self",
".",
"fail_print",
"if",
"action",
"[",
"'result'",
"]",
"==",
"'fail'",
"else",
"self",
".",
"p_print",
"self",
".",
"info_print",
"(",
"\"\"",
")",
"self",
".",
"info_print",
"(",
"\"({0}) {1}\"",
",",
"action",
"[",
"'info'",
"]",
"[",
"'name'",
"]",
",",
"action",
"[",
"'info'",
"]",
"[",
"'path'",
"]",
")",
"p",
"(",
"\"\"",
")",
"p",
"(",
"\"{0}\"",
",",
"action",
"[",
"'command'",
"]",
".",
"strip",
"(",
")",
")",
"p",
"(",
"\"\"",
")",
"for",
"line",
"in",
"output",
".",
"splitlines",
"(",
")",
":",
"p",
"(",
"\"{0}\"",
",",
"line",
".",
"encode",
"(",
"'utf-8'",
")",
")"
] | Print the detailed info of failed or always print tests. | [
"Print",
"the",
"detailed",
"info",
"of",
"failed",
"or",
"always",
"print",
"tests",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/libs/predef/tools/ci/build_log.py#L363-L378 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/printer.py | _get_weight_param_summary | def _get_weight_param_summary(wp):
"""Get a summary of _NeuralNetwork_pb2.WeightParams
Args:
wp : _NeuralNetwork_pb2.WeightParams - the _NeuralNetwork_pb2.WeightParams message to display
Returns:
a str summary for wp
"""
summary_str = ''
if wp.HasField('quantization'):
nbits = wp.quantization.numberOfBits
quant_type = 'linearly' if wp.quantization.HasField('linearQuantization') else 'lookup-table'
summary_str += '{}-bit {} quantized'.format(nbits, quant_type)
if len(wp.floatValue) > 0:
summary_str += '({} floatValues)'.format(len(wp.floatValue))
if len(wp.float16Value) > 0:
summary_str += '({} bytes float16Values)'.format(len(wp.float16Value))
if len(wp.rawValue) > 0:
summary_str += '({} bytes rawValues)'.format(len(wp.rawValue))
return summary_str | python | def _get_weight_param_summary(wp):
"""Get a summary of _NeuralNetwork_pb2.WeightParams
Args:
wp : _NeuralNetwork_pb2.WeightParams - the _NeuralNetwork_pb2.WeightParams message to display
Returns:
a str summary for wp
"""
summary_str = ''
if wp.HasField('quantization'):
nbits = wp.quantization.numberOfBits
quant_type = 'linearly' if wp.quantization.HasField('linearQuantization') else 'lookup-table'
summary_str += '{}-bit {} quantized'.format(nbits, quant_type)
if len(wp.floatValue) > 0:
summary_str += '({} floatValues)'.format(len(wp.floatValue))
if len(wp.float16Value) > 0:
summary_str += '({} bytes float16Values)'.format(len(wp.float16Value))
if len(wp.rawValue) > 0:
summary_str += '({} bytes rawValues)'.format(len(wp.rawValue))
return summary_str | [
"def",
"_get_weight_param_summary",
"(",
"wp",
")",
":",
"summary_str",
"=",
"''",
"if",
"wp",
".",
"HasField",
"(",
"'quantization'",
")",
":",
"nbits",
"=",
"wp",
".",
"quantization",
".",
"numberOfBits",
"quant_type",
"=",
"'linearly'",
"if",
"wp",
".",
"quantization",
".",
"HasField",
"(",
"'linearQuantization'",
")",
"else",
"'lookup-table'",
"summary_str",
"+=",
"'{}-bit {} quantized'",
".",
"format",
"(",
"nbits",
",",
"quant_type",
")",
"if",
"len",
"(",
"wp",
".",
"floatValue",
")",
">",
"0",
":",
"summary_str",
"+=",
"'({} floatValues)'",
".",
"format",
"(",
"len",
"(",
"wp",
".",
"floatValue",
")",
")",
"if",
"len",
"(",
"wp",
".",
"float16Value",
")",
">",
"0",
":",
"summary_str",
"+=",
"'({} bytes float16Values)'",
".",
"format",
"(",
"len",
"(",
"wp",
".",
"float16Value",
")",
")",
"if",
"len",
"(",
"wp",
".",
"rawValue",
")",
">",
"0",
":",
"summary_str",
"+=",
"'({} bytes rawValues)'",
".",
"format",
"(",
"len",
"(",
"wp",
".",
"rawValue",
")",
")",
"return",
"summary_str"
] | Get a summary of _NeuralNetwork_pb2.WeightParams
Args:
wp : _NeuralNetwork_pb2.WeightParams - the _NeuralNetwork_pb2.WeightParams message to display
Returns:
a str summary for wp | [
"Get",
"a",
"summary",
"of",
"_NeuralNetwork_pb2",
".",
"WeightParams",
"Args",
":",
"wp",
":",
"_NeuralNetwork_pb2",
".",
"WeightParams",
"-",
"the",
"_NeuralNetwork_pb2",
".",
"WeightParams",
"message",
"to",
"display",
"Returns",
":",
"a",
"str",
"summary",
"for",
"wp"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/printer.py#L8-L28 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/printer.py | _summarize_network_layer_info | def _summarize_network_layer_info(layer):
"""
Args:
layer - an MLModel NeuralNetwork Layer protobuf message
Returns:
layer_type : str - type of layer
layer_name : str - name of the layer
layer_inputs : list[str] - a list of strings representing input blobs of the layer
layer_outputs : list[str] - a list of strings representing output blobs of the layer
layer_field_content : list[(str, str)] - a list of two-tuple of (parameter_name, content)
"""
layer_type_str = layer.WhichOneof('layer')
layer_name = layer.name
layer_inputs = list(layer.input)
layer_outputs = list(layer.output)
typed_layer = getattr(layer, layer_type_str)
layer_field_names = [l.name for l in typed_layer.DESCRIPTOR.fields]
layer_field_content = []
for name in layer_field_names:
field = getattr(typed_layer,name)
summary_str = ''
if type(field) == _NeuralNetwork_pb2.LSTMWeightParams:
summary_str = _get_lstm_weight_param_summary(field)
elif type(field) == _NeuralNetwork_pb2.WeightParams:
summary_str = _get_weight_param_summary(field)
else:
field_str = str(field)
if len(field_str) > 0:
summary_str = field_str.replace('\n', ' ')
if len(summary_str) > 0:
layer_field_content.append([name, summary_str])
return layer_type_str, layer_name, layer_inputs, layer_outputs, layer_field_content | python | def _summarize_network_layer_info(layer):
"""
Args:
layer - an MLModel NeuralNetwork Layer protobuf message
Returns:
layer_type : str - type of layer
layer_name : str - name of the layer
layer_inputs : list[str] - a list of strings representing input blobs of the layer
layer_outputs : list[str] - a list of strings representing output blobs of the layer
layer_field_content : list[(str, str)] - a list of two-tuple of (parameter_name, content)
"""
layer_type_str = layer.WhichOneof('layer')
layer_name = layer.name
layer_inputs = list(layer.input)
layer_outputs = list(layer.output)
typed_layer = getattr(layer, layer_type_str)
layer_field_names = [l.name for l in typed_layer.DESCRIPTOR.fields]
layer_field_content = []
for name in layer_field_names:
field = getattr(typed_layer,name)
summary_str = ''
if type(field) == _NeuralNetwork_pb2.LSTMWeightParams:
summary_str = _get_lstm_weight_param_summary(field)
elif type(field) == _NeuralNetwork_pb2.WeightParams:
summary_str = _get_weight_param_summary(field)
else:
field_str = str(field)
if len(field_str) > 0:
summary_str = field_str.replace('\n', ' ')
if len(summary_str) > 0:
layer_field_content.append([name, summary_str])
return layer_type_str, layer_name, layer_inputs, layer_outputs, layer_field_content | [
"def",
"_summarize_network_layer_info",
"(",
"layer",
")",
":",
"layer_type_str",
"=",
"layer",
".",
"WhichOneof",
"(",
"'layer'",
")",
"layer_name",
"=",
"layer",
".",
"name",
"layer_inputs",
"=",
"list",
"(",
"layer",
".",
"input",
")",
"layer_outputs",
"=",
"list",
"(",
"layer",
".",
"output",
")",
"typed_layer",
"=",
"getattr",
"(",
"layer",
",",
"layer_type_str",
")",
"layer_field_names",
"=",
"[",
"l",
".",
"name",
"for",
"l",
"in",
"typed_layer",
".",
"DESCRIPTOR",
".",
"fields",
"]",
"layer_field_content",
"=",
"[",
"]",
"for",
"name",
"in",
"layer_field_names",
":",
"field",
"=",
"getattr",
"(",
"typed_layer",
",",
"name",
")",
"summary_str",
"=",
"''",
"if",
"type",
"(",
"field",
")",
"==",
"_NeuralNetwork_pb2",
".",
"LSTMWeightParams",
":",
"summary_str",
"=",
"_get_lstm_weight_param_summary",
"(",
"field",
")",
"elif",
"type",
"(",
"field",
")",
"==",
"_NeuralNetwork_pb2",
".",
"WeightParams",
":",
"summary_str",
"=",
"_get_weight_param_summary",
"(",
"field",
")",
"else",
":",
"field_str",
"=",
"str",
"(",
"field",
")",
"if",
"len",
"(",
"field_str",
")",
">",
"0",
":",
"summary_str",
"=",
"field_str",
".",
"replace",
"(",
"'\\n'",
",",
"' '",
")",
"if",
"len",
"(",
"summary_str",
")",
">",
"0",
":",
"layer_field_content",
".",
"append",
"(",
"[",
"name",
",",
"summary_str",
"]",
")",
"return",
"layer_type_str",
",",
"layer_name",
",",
"layer_inputs",
",",
"layer_outputs",
",",
"layer_field_content"
] | Args:
layer - an MLModel NeuralNetwork Layer protobuf message
Returns:
layer_type : str - type of layer
layer_name : str - name of the layer
layer_inputs : list[str] - a list of strings representing input blobs of the layer
layer_outputs : list[str] - a list of strings representing output blobs of the layer
layer_field_content : list[(str, str)] - a list of two-tuple of (parameter_name, content) | [
"Args",
":",
"layer",
"-",
"an",
"MLModel",
"NeuralNetwork",
"Layer",
"protobuf",
"message",
"Returns",
":",
"layer_type",
":",
"str",
"-",
"type",
"of",
"layer",
"layer_name",
":",
"str",
"-",
"name",
"of",
"the",
"layer",
"layer_inputs",
":",
"list",
"[",
"str",
"]",
"-",
"a",
"list",
"of",
"strings",
"representing",
"input",
"blobs",
"of",
"the",
"layer",
"layer_outputs",
":",
"list",
"[",
"str",
"]",
"-",
"a",
"list",
"of",
"strings",
"representing",
"output",
"blobs",
"of",
"the",
"layer",
"layer_field_content",
":",
"list",
"[",
"(",
"str",
"str",
")",
"]",
"-",
"a",
"list",
"of",
"two",
"-",
"tuple",
"of",
"(",
"parameter_name",
"content",
")"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/printer.py#L67-L102 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/printer.py | summarize_neural_network_spec | def summarize_neural_network_spec(mlmodel_spec):
""" Summarize network into the following structure.
Args:
mlmodel_spec : mlmodel spec
Returns:
inputs : list[(str, str)] - a list of two tuple (name, descriptor) for each input blob.
outputs : list[(str, str)] - a list of two tuple (name, descriptor) for each output blob
layers : list[(str, list[str], list[str], list[(str, str)])] - a list of layers represented by
layer name, input blobs, output blobs, a list of (parameter name, content)
"""
inputs = [(blob.name, _get_feature_description_summary(blob)) for blob in mlmodel_spec.description.input]
outputs = [(blob.name, _get_feature_description_summary(blob)) for blob in mlmodel_spec.description.output]
nn = None
if mlmodel_spec.HasField('neuralNetwork'):
nn = mlmodel_spec.neuralNetwork
elif mlmodel_spec.HasField('neuralNetworkClassifier'):
nn = mlmodel_spec.neuralNetworkClassifier
elif mlmodel_spec.HasField('neuralNetworkRegressor'):
nn = mlmodel_spec.neuralNetworkRegressor
layers = [_summarize_network_layer_info(layer) for layer in nn.layers] if nn != None else None
return (inputs, outputs, layers) | python | def summarize_neural_network_spec(mlmodel_spec):
""" Summarize network into the following structure.
Args:
mlmodel_spec : mlmodel spec
Returns:
inputs : list[(str, str)] - a list of two tuple (name, descriptor) for each input blob.
outputs : list[(str, str)] - a list of two tuple (name, descriptor) for each output blob
layers : list[(str, list[str], list[str], list[(str, str)])] - a list of layers represented by
layer name, input blobs, output blobs, a list of (parameter name, content)
"""
inputs = [(blob.name, _get_feature_description_summary(blob)) for blob in mlmodel_spec.description.input]
outputs = [(blob.name, _get_feature_description_summary(blob)) for blob in mlmodel_spec.description.output]
nn = None
if mlmodel_spec.HasField('neuralNetwork'):
nn = mlmodel_spec.neuralNetwork
elif mlmodel_spec.HasField('neuralNetworkClassifier'):
nn = mlmodel_spec.neuralNetworkClassifier
elif mlmodel_spec.HasField('neuralNetworkRegressor'):
nn = mlmodel_spec.neuralNetworkRegressor
layers = [_summarize_network_layer_info(layer) for layer in nn.layers] if nn != None else None
return (inputs, outputs, layers) | [
"def",
"summarize_neural_network_spec",
"(",
"mlmodel_spec",
")",
":",
"inputs",
"=",
"[",
"(",
"blob",
".",
"name",
",",
"_get_feature_description_summary",
"(",
"blob",
")",
")",
"for",
"blob",
"in",
"mlmodel_spec",
".",
"description",
".",
"input",
"]",
"outputs",
"=",
"[",
"(",
"blob",
".",
"name",
",",
"_get_feature_description_summary",
"(",
"blob",
")",
")",
"for",
"blob",
"in",
"mlmodel_spec",
".",
"description",
".",
"output",
"]",
"nn",
"=",
"None",
"if",
"mlmodel_spec",
".",
"HasField",
"(",
"'neuralNetwork'",
")",
":",
"nn",
"=",
"mlmodel_spec",
".",
"neuralNetwork",
"elif",
"mlmodel_spec",
".",
"HasField",
"(",
"'neuralNetworkClassifier'",
")",
":",
"nn",
"=",
"mlmodel_spec",
".",
"neuralNetworkClassifier",
"elif",
"mlmodel_spec",
".",
"HasField",
"(",
"'neuralNetworkRegressor'",
")",
":",
"nn",
"=",
"mlmodel_spec",
".",
"neuralNetworkRegressor",
"layers",
"=",
"[",
"_summarize_network_layer_info",
"(",
"layer",
")",
"for",
"layer",
"in",
"nn",
".",
"layers",
"]",
"if",
"nn",
"!=",
"None",
"else",
"None",
"return",
"(",
"inputs",
",",
"outputs",
",",
"layers",
")"
] | Summarize network into the following structure.
Args:
mlmodel_spec : mlmodel spec
Returns:
inputs : list[(str, str)] - a list of two tuple (name, descriptor) for each input blob.
outputs : list[(str, str)] - a list of two tuple (name, descriptor) for each output blob
layers : list[(str, list[str], list[str], list[(str, str)])] - a list of layers represented by
layer name, input blobs, output blobs, a list of (parameter name, content) | [
"Summarize",
"network",
"into",
"the",
"following",
"structure",
".",
"Args",
":",
"mlmodel_spec",
":",
"mlmodel",
"spec",
"Returns",
":",
"inputs",
":",
"list",
"[",
"(",
"str",
"str",
")",
"]",
"-",
"a",
"list",
"of",
"two",
"tuple",
"(",
"name",
"descriptor",
")",
"for",
"each",
"input",
"blob",
".",
"outputs",
":",
"list",
"[",
"(",
"str",
"str",
")",
"]",
"-",
"a",
"list",
"of",
"two",
"tuple",
"(",
"name",
"descriptor",
")",
"for",
"each",
"output",
"blob",
"layers",
":",
"list",
"[",
"(",
"str",
"list",
"[",
"str",
"]",
"list",
"[",
"str",
"]",
"list",
"[",
"(",
"str",
"str",
")",
"]",
")",
"]",
"-",
"a",
"list",
"of",
"layers",
"represented",
"by",
"layer",
"name",
"input",
"blobs",
"output",
"blobs",
"a",
"list",
"of",
"(",
"parameter",
"name",
"content",
")"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/printer.py#L105-L127 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/printer.py | print_network_spec | def print_network_spec(mlmodel_spec, interface_only=False):
""" Print the network information summary.
Args:
mlmodel_spec : the mlmodel spec
interface_only : Shows only the input and output of the network
"""
inputs, outputs, layers_info = summarize_neural_network_spec(mlmodel_spec)
print('Inputs:')
for i in inputs:
name, description = i
print(' {} {}'.format(name, description))
print('Outputs:')
for o in outputs:
name, description = o
print(' {} {}'.format(name, description))
if layers_info is None:
print('\n(This MLModel is not a neural network model or does not contain any layers)')
if layers_info and not interface_only:
print('\nLayers:')
for idx, l in enumerate(layers_info):
layer_type, name, in_blobs, out_blobs, params_info = l
print('[{}] ({}) {}'.format(idx, layer_type, name))
print(' Input blobs: {}'.format(in_blobs))
print(' Output blobs: {}'.format(out_blobs))
if len(params_info) > 0:
print(' Parameters: ')
for param in params_info:
print(' {} = {}'.format(param[0], param[1]))
print('\n') | python | def print_network_spec(mlmodel_spec, interface_only=False):
""" Print the network information summary.
Args:
mlmodel_spec : the mlmodel spec
interface_only : Shows only the input and output of the network
"""
inputs, outputs, layers_info = summarize_neural_network_spec(mlmodel_spec)
print('Inputs:')
for i in inputs:
name, description = i
print(' {} {}'.format(name, description))
print('Outputs:')
for o in outputs:
name, description = o
print(' {} {}'.format(name, description))
if layers_info is None:
print('\n(This MLModel is not a neural network model or does not contain any layers)')
if layers_info and not interface_only:
print('\nLayers:')
for idx, l in enumerate(layers_info):
layer_type, name, in_blobs, out_blobs, params_info = l
print('[{}] ({}) {}'.format(idx, layer_type, name))
print(' Input blobs: {}'.format(in_blobs))
print(' Output blobs: {}'.format(out_blobs))
if len(params_info) > 0:
print(' Parameters: ')
for param in params_info:
print(' {} = {}'.format(param[0], param[1]))
print('\n') | [
"def",
"print_network_spec",
"(",
"mlmodel_spec",
",",
"interface_only",
"=",
"False",
")",
":",
"inputs",
",",
"outputs",
",",
"layers_info",
"=",
"summarize_neural_network_spec",
"(",
"mlmodel_spec",
")",
"print",
"(",
"'Inputs:'",
")",
"for",
"i",
"in",
"inputs",
":",
"name",
",",
"description",
"=",
"i",
"print",
"(",
"' {} {}'",
".",
"format",
"(",
"name",
",",
"description",
")",
")",
"print",
"(",
"'Outputs:'",
")",
"for",
"o",
"in",
"outputs",
":",
"name",
",",
"description",
"=",
"o",
"print",
"(",
"' {} {}'",
".",
"format",
"(",
"name",
",",
"description",
")",
")",
"if",
"layers_info",
"is",
"None",
":",
"print",
"(",
"'\\n(This MLModel is not a neural network model or does not contain any layers)'",
")",
"if",
"layers_info",
"and",
"not",
"interface_only",
":",
"print",
"(",
"'\\nLayers:'",
")",
"for",
"idx",
",",
"l",
"in",
"enumerate",
"(",
"layers_info",
")",
":",
"layer_type",
",",
"name",
",",
"in_blobs",
",",
"out_blobs",
",",
"params_info",
"=",
"l",
"print",
"(",
"'[{}] ({}) {}'",
".",
"format",
"(",
"idx",
",",
"layer_type",
",",
"name",
")",
")",
"print",
"(",
"' Input blobs: {}'",
".",
"format",
"(",
"in_blobs",
")",
")",
"print",
"(",
"' Output blobs: {}'",
".",
"format",
"(",
"out_blobs",
")",
")",
"if",
"len",
"(",
"params_info",
")",
">",
"0",
":",
"print",
"(",
"' Parameters: '",
")",
"for",
"param",
"in",
"params_info",
":",
"print",
"(",
"' {} = {}'",
".",
"format",
"(",
"param",
"[",
"0",
"]",
",",
"param",
"[",
"1",
"]",
")",
")",
"print",
"(",
"'\\n'",
")"
] | Print the network information summary.
Args:
mlmodel_spec : the mlmodel spec
interface_only : Shows only the input and output of the network | [
"Print",
"the",
"network",
"information",
"summary",
".",
"Args",
":",
"mlmodel_spec",
":",
"the",
"mlmodel",
"spec",
"interface_only",
":",
"Shows",
"only",
"the",
"input",
"and",
"output",
"of",
"the",
"network"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/printer.py#L130-L163 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_SVC.py | _generate_base_svm_classifier_spec | def _generate_base_svm_classifier_spec(model):
"""
Takes an SVM classifier produces a starting spec using the parts. that are
shared between all SVMs.
"""
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
check_fitted(model, lambda m: hasattr(m, 'support_vectors_'))
spec = _Model_pb2.Model()
spec.specificationVersion = SPECIFICATION_VERSION
svm = spec.supportVectorClassifier
_set_kernel(model, svm)
for cur_rho in model.intercept_:
if(len(model.classes_) == 2):
# For some reason Scikit Learn doesn't negate for binary classification
svm.rho.append(cur_rho)
else:
svm.rho.append(-cur_rho)
for i in range(len(model._dual_coef_)):
svm.coefficients.add()
for cur_alpha in model._dual_coef_[i]:
svm.coefficients[i].alpha.append(cur_alpha)
for cur_src_vector in model.support_vectors_:
cur_dest_vector = svm.denseSupportVectors.vectors.add()
for i in cur_src_vector:
cur_dest_vector.values.append(i)
return spec | python | def _generate_base_svm_classifier_spec(model):
"""
Takes an SVM classifier produces a starting spec using the parts. that are
shared between all SVMs.
"""
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
check_fitted(model, lambda m: hasattr(m, 'support_vectors_'))
spec = _Model_pb2.Model()
spec.specificationVersion = SPECIFICATION_VERSION
svm = spec.supportVectorClassifier
_set_kernel(model, svm)
for cur_rho in model.intercept_:
if(len(model.classes_) == 2):
# For some reason Scikit Learn doesn't negate for binary classification
svm.rho.append(cur_rho)
else:
svm.rho.append(-cur_rho)
for i in range(len(model._dual_coef_)):
svm.coefficients.add()
for cur_alpha in model._dual_coef_[i]:
svm.coefficients[i].alpha.append(cur_alpha)
for cur_src_vector in model.support_vectors_:
cur_dest_vector = svm.denseSupportVectors.vectors.add()
for i in cur_src_vector:
cur_dest_vector.values.append(i)
return spec | [
"def",
"_generate_base_svm_classifier_spec",
"(",
"model",
")",
":",
"if",
"not",
"(",
"_HAS_SKLEARN",
")",
":",
"raise",
"RuntimeError",
"(",
"'scikit-learn not found. scikit-learn conversion API is disabled.'",
")",
"check_fitted",
"(",
"model",
",",
"lambda",
"m",
":",
"hasattr",
"(",
"m",
",",
"'support_vectors_'",
")",
")",
"spec",
"=",
"_Model_pb2",
".",
"Model",
"(",
")",
"spec",
".",
"specificationVersion",
"=",
"SPECIFICATION_VERSION",
"svm",
"=",
"spec",
".",
"supportVectorClassifier",
"_set_kernel",
"(",
"model",
",",
"svm",
")",
"for",
"cur_rho",
"in",
"model",
".",
"intercept_",
":",
"if",
"(",
"len",
"(",
"model",
".",
"classes_",
")",
"==",
"2",
")",
":",
"# For some reason Scikit Learn doesn't negate for binary classification",
"svm",
".",
"rho",
".",
"append",
"(",
"cur_rho",
")",
"else",
":",
"svm",
".",
"rho",
".",
"append",
"(",
"-",
"cur_rho",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"model",
".",
"_dual_coef_",
")",
")",
":",
"svm",
".",
"coefficients",
".",
"add",
"(",
")",
"for",
"cur_alpha",
"in",
"model",
".",
"_dual_coef_",
"[",
"i",
"]",
":",
"svm",
".",
"coefficients",
"[",
"i",
"]",
".",
"alpha",
".",
"append",
"(",
"cur_alpha",
")",
"for",
"cur_src_vector",
"in",
"model",
".",
"support_vectors_",
":",
"cur_dest_vector",
"=",
"svm",
".",
"denseSupportVectors",
".",
"vectors",
".",
"add",
"(",
")",
"for",
"i",
"in",
"cur_src_vector",
":",
"cur_dest_vector",
".",
"values",
".",
"append",
"(",
"i",
")",
"return",
"spec"
] | Takes an SVM classifier produces a starting spec using the parts. that are
shared between all SVMs. | [
"Takes",
"an",
"SVM",
"classifier",
"produces",
"a",
"starting",
"spec",
"using",
"the",
"parts",
".",
"that",
"are",
"shared",
"between",
"all",
"SVMs",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_SVC.py#L24-L56 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_SVC.py | convert | def convert(model, feature_names, target):
"""Convert a Support Vector Classtion (SVC) model to the protobuf spec.
Parameters
----------
model: SVC
A trained SVC encoder model.
feature_names: [str], optional (default=None)
Name of the input columns.
target: str, optional (default=None)
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model
"""
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
spec = _generate_base_svm_classifier_spec(model)
spec = set_classifier_interface_params(spec, feature_names, model.classes_, 'supportVectorClassifier', output_features = target)
svm = spec.supportVectorClassifier
for i in model.n_support_:
svm.numberOfSupportVectorsPerClass.append(int(i))
if len(model.probA_) != 0 and len(model.classes_) == 2:
print("[WARNING] Scikit Learn uses a technique to normalize pairwise probabilities even for binary classification. "
"This can cause differences in predicted probabilities, usually less than 0.5%.")
# If this is an empty list, then model.probA_ will be an empty list.
if len(model.probA_) != 0:
for i in model.probA_:
svm.probA.append(i)
for i in model.probB_:
svm.probB.append(i)
return _MLModel(spec) | python | def convert(model, feature_names, target):
"""Convert a Support Vector Classtion (SVC) model to the protobuf spec.
Parameters
----------
model: SVC
A trained SVC encoder model.
feature_names: [str], optional (default=None)
Name of the input columns.
target: str, optional (default=None)
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model
"""
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
spec = _generate_base_svm_classifier_spec(model)
spec = set_classifier_interface_params(spec, feature_names, model.classes_, 'supportVectorClassifier', output_features = target)
svm = spec.supportVectorClassifier
for i in model.n_support_:
svm.numberOfSupportVectorsPerClass.append(int(i))
if len(model.probA_) != 0 and len(model.classes_) == 2:
print("[WARNING] Scikit Learn uses a technique to normalize pairwise probabilities even for binary classification. "
"This can cause differences in predicted probabilities, usually less than 0.5%.")
# If this is an empty list, then model.probA_ will be an empty list.
if len(model.probA_) != 0:
for i in model.probA_:
svm.probA.append(i)
for i in model.probB_:
svm.probB.append(i)
return _MLModel(spec) | [
"def",
"convert",
"(",
"model",
",",
"feature_names",
",",
"target",
")",
":",
"if",
"not",
"(",
"_HAS_SKLEARN",
")",
":",
"raise",
"RuntimeError",
"(",
"'scikit-learn not found. scikit-learn conversion API is disabled.'",
")",
"spec",
"=",
"_generate_base_svm_classifier_spec",
"(",
"model",
")",
"spec",
"=",
"set_classifier_interface_params",
"(",
"spec",
",",
"feature_names",
",",
"model",
".",
"classes_",
",",
"'supportVectorClassifier'",
",",
"output_features",
"=",
"target",
")",
"svm",
"=",
"spec",
".",
"supportVectorClassifier",
"for",
"i",
"in",
"model",
".",
"n_support_",
":",
"svm",
".",
"numberOfSupportVectorsPerClass",
".",
"append",
"(",
"int",
"(",
"i",
")",
")",
"if",
"len",
"(",
"model",
".",
"probA_",
")",
"!=",
"0",
"and",
"len",
"(",
"model",
".",
"classes_",
")",
"==",
"2",
":",
"print",
"(",
"\"[WARNING] Scikit Learn uses a technique to normalize pairwise probabilities even for binary classification. \"",
"\"This can cause differences in predicted probabilities, usually less than 0.5%.\"",
")",
"# If this is an empty list, then model.probA_ will be an empty list.",
"if",
"len",
"(",
"model",
".",
"probA_",
")",
"!=",
"0",
":",
"for",
"i",
"in",
"model",
".",
"probA_",
":",
"svm",
".",
"probA",
".",
"append",
"(",
"i",
")",
"for",
"i",
"in",
"model",
".",
"probB_",
":",
"svm",
".",
"probB",
".",
"append",
"(",
"i",
")",
"return",
"_MLModel",
"(",
"spec",
")"
] | Convert a Support Vector Classtion (SVC) model to the protobuf spec.
Parameters
----------
model: SVC
A trained SVC encoder model.
feature_names: [str], optional (default=None)
Name of the input columns.
target: str, optional (default=None)
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
Protobuf representation of the model | [
"Convert",
"a",
"Support",
"Vector",
"Classtion",
"(",
"SVC",
")",
"model",
"to",
"the",
"protobuf",
"spec",
".",
"Parameters",
"----------",
"model",
":",
"SVC",
"A",
"trained",
"SVC",
"encoder",
"model",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_SVC.py#L58-L97 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology.py | NetGraph.make_input_layers | def make_input_layers(self):
"""
Extract the ordering of the input layers.
"""
self.input_layers = []
if hasattr(self.model, 'input_layers'):
input_keras_layers = self.model.input_layers[:]
self.input_layers = [None] * len(input_keras_layers)
for layer in self.layer_list:
keras_layer = self.keras_layer_map[layer]
if isinstance(keras_layer, _keras.engine.topology.InputLayer):
if keras_layer in input_keras_layers:
idx = input_keras_layers.index(keras_layer)
self.input_layers[idx] = layer
elif len(self.model.inbound_nodes) <= 1:
for ts in _to_list(self.model.input):
# search for the InputLayer that matches this ts
for l in self.layer_list:
kl = self.keras_layer_map[l]
if isinstance(kl, _keras.engine.topology.InputLayer) and kl.input == ts:
self.input_layers.append(l)
else:
raise ValueError("Input values cannot be identified.") | python | def make_input_layers(self):
"""
Extract the ordering of the input layers.
"""
self.input_layers = []
if hasattr(self.model, 'input_layers'):
input_keras_layers = self.model.input_layers[:]
self.input_layers = [None] * len(input_keras_layers)
for layer in self.layer_list:
keras_layer = self.keras_layer_map[layer]
if isinstance(keras_layer, _keras.engine.topology.InputLayer):
if keras_layer in input_keras_layers:
idx = input_keras_layers.index(keras_layer)
self.input_layers[idx] = layer
elif len(self.model.inbound_nodes) <= 1:
for ts in _to_list(self.model.input):
# search for the InputLayer that matches this ts
for l in self.layer_list:
kl = self.keras_layer_map[l]
if isinstance(kl, _keras.engine.topology.InputLayer) and kl.input == ts:
self.input_layers.append(l)
else:
raise ValueError("Input values cannot be identified.") | [
"def",
"make_input_layers",
"(",
"self",
")",
":",
"self",
".",
"input_layers",
"=",
"[",
"]",
"if",
"hasattr",
"(",
"self",
".",
"model",
",",
"'input_layers'",
")",
":",
"input_keras_layers",
"=",
"self",
".",
"model",
".",
"input_layers",
"[",
":",
"]",
"self",
".",
"input_layers",
"=",
"[",
"None",
"]",
"*",
"len",
"(",
"input_keras_layers",
")",
"for",
"layer",
"in",
"self",
".",
"layer_list",
":",
"keras_layer",
"=",
"self",
".",
"keras_layer_map",
"[",
"layer",
"]",
"if",
"isinstance",
"(",
"keras_layer",
",",
"_keras",
".",
"engine",
".",
"topology",
".",
"InputLayer",
")",
":",
"if",
"keras_layer",
"in",
"input_keras_layers",
":",
"idx",
"=",
"input_keras_layers",
".",
"index",
"(",
"keras_layer",
")",
"self",
".",
"input_layers",
"[",
"idx",
"]",
"=",
"layer",
"elif",
"len",
"(",
"self",
".",
"model",
".",
"inbound_nodes",
")",
"<=",
"1",
":",
"for",
"ts",
"in",
"_to_list",
"(",
"self",
".",
"model",
".",
"input",
")",
":",
"# search for the InputLayer that matches this ts",
"for",
"l",
"in",
"self",
".",
"layer_list",
":",
"kl",
"=",
"self",
".",
"keras_layer_map",
"[",
"l",
"]",
"if",
"isinstance",
"(",
"kl",
",",
"_keras",
".",
"engine",
".",
"topology",
".",
"InputLayer",
")",
"and",
"kl",
".",
"input",
"==",
"ts",
":",
"self",
".",
"input_layers",
".",
"append",
"(",
"l",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Input values cannot be identified.\"",
")"
] | Extract the ordering of the input layers. | [
"Extract",
"the",
"ordering",
"of",
"the",
"input",
"layers",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology.py#L107-L129 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology.py | NetGraph.make_output_layers | def make_output_layers(self):
"""
Extract the ordering of output layers.
"""
# TODO
# use successors == 0 as the criteria for output layer
# will fail when some intermediate layers also generate output.
# However, because the possibility of having inserted layers,
# it's more difficult to tell which layer is the output layer.
# Once possible way is to keep track of newly added layers...
self.output_layers = []
for layer in self.layer_list:
if len(self.get_successors(layer)) == 0:
self.output_layers.append(layer) | python | def make_output_layers(self):
"""
Extract the ordering of output layers.
"""
# TODO
# use successors == 0 as the criteria for output layer
# will fail when some intermediate layers also generate output.
# However, because the possibility of having inserted layers,
# it's more difficult to tell which layer is the output layer.
# Once possible way is to keep track of newly added layers...
self.output_layers = []
for layer in self.layer_list:
if len(self.get_successors(layer)) == 0:
self.output_layers.append(layer) | [
"def",
"make_output_layers",
"(",
"self",
")",
":",
"# TODO",
"# use successors == 0 as the criteria for output layer",
"# will fail when some intermediate layers also generate output.",
"# However, because the possibility of having inserted layers,",
"# it's more difficult to tell which layer is the output layer.",
"# Once possible way is to keep track of newly added layers...",
"self",
".",
"output_layers",
"=",
"[",
"]",
"for",
"layer",
"in",
"self",
".",
"layer_list",
":",
"if",
"len",
"(",
"self",
".",
"get_successors",
"(",
"layer",
")",
")",
"==",
"0",
":",
"self",
".",
"output_layers",
".",
"append",
"(",
"layer",
")"
] | Extract the ordering of output layers. | [
"Extract",
"the",
"ordering",
"of",
"output",
"layers",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology.py#L131-L144 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology.py | NetGraph.generate_blob_names | def generate_blob_names(self):
"""
Generate blob names for each one of the edge. At this time, Keras does not
support "fork" operation (a layer with more than 1 blob output). So we just
use names of the src layer to identify a blob. We also assume all neural
networks are singly-connected graphs - which should be the case.
"""
# generate blob names that represent edges in blob_name_map
# because of the InputLayers, input blobs are also generated.
# Generate each layer's input / output blob names
for layer in self.layer_list:
keras_layer = self.keras_layer_map[layer]
# no need to generate InputLayers' blobs
if not isinstance(keras_layer, _keras.engine.topology.InputLayer):
# layer's input blob names depend on predecessors
preds = self.get_predecessors(layer)
for pred in preds:
blob_name = pred + '_output'
_insert_to_dict(self.layers_inputs, layer, blob_name)
# layer's output blob is just named after itself
blob_name = layer + '_output'
_insert_to_dict(self.layers_outputs, layer, blob_name) | python | def generate_blob_names(self):
"""
Generate blob names for each one of the edge. At this time, Keras does not
support "fork" operation (a layer with more than 1 blob output). So we just
use names of the src layer to identify a blob. We also assume all neural
networks are singly-connected graphs - which should be the case.
"""
# generate blob names that represent edges in blob_name_map
# because of the InputLayers, input blobs are also generated.
# Generate each layer's input / output blob names
for layer in self.layer_list:
keras_layer = self.keras_layer_map[layer]
# no need to generate InputLayers' blobs
if not isinstance(keras_layer, _keras.engine.topology.InputLayer):
# layer's input blob names depend on predecessors
preds = self.get_predecessors(layer)
for pred in preds:
blob_name = pred + '_output'
_insert_to_dict(self.layers_inputs, layer, blob_name)
# layer's output blob is just named after itself
blob_name = layer + '_output'
_insert_to_dict(self.layers_outputs, layer, blob_name) | [
"def",
"generate_blob_names",
"(",
"self",
")",
":",
"# generate blob names that represent edges in blob_name_map",
"# because of the InputLayers, input blobs are also generated.",
"# Generate each layer's input / output blob names",
"for",
"layer",
"in",
"self",
".",
"layer_list",
":",
"keras_layer",
"=",
"self",
".",
"keras_layer_map",
"[",
"layer",
"]",
"# no need to generate InputLayers' blobs",
"if",
"not",
"isinstance",
"(",
"keras_layer",
",",
"_keras",
".",
"engine",
".",
"topology",
".",
"InputLayer",
")",
":",
"# layer's input blob names depend on predecessors",
"preds",
"=",
"self",
".",
"get_predecessors",
"(",
"layer",
")",
"for",
"pred",
"in",
"preds",
":",
"blob_name",
"=",
"pred",
"+",
"'_output'",
"_insert_to_dict",
"(",
"self",
".",
"layers_inputs",
",",
"layer",
",",
"blob_name",
")",
"# layer's output blob is just named after itself",
"blob_name",
"=",
"layer",
"+",
"'_output'",
"_insert_to_dict",
"(",
"self",
".",
"layers_outputs",
",",
"layer",
",",
"blob_name",
")"
] | Generate blob names for each one of the edge. At this time, Keras does not
support "fork" operation (a layer with more than 1 blob output). So we just
use names of the src layer to identify a blob. We also assume all neural
networks are singly-connected graphs - which should be the case. | [
"Generate",
"blob",
"names",
"for",
"each",
"one",
"of",
"the",
"edge",
".",
"At",
"this",
"time",
"Keras",
"does",
"not",
"support",
"fork",
"operation",
"(",
"a",
"layer",
"with",
"more",
"than",
"1",
"blob",
"output",
")",
".",
"So",
"we",
"just",
"use",
"names",
"of",
"the",
"src",
"layer",
"to",
"identify",
"a",
"blob",
".",
"We",
"also",
"assume",
"all",
"neural",
"networks",
"are",
"singly",
"-",
"connected",
"graphs",
"-",
"which",
"should",
"be",
"the",
"case",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology.py#L152-L174 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology.py | NetGraph._remove_layer | def _remove_layer(self, layer):
"""
remove the layer and its input/output edges
"""
successors = self.get_successors(layer)
predecessors = self.get_predecessors(layer)
# remove all edges
for succ in successors:
self._remove_edge(layer, succ)
for pred in predecessors:
self._remove_edge(pred, layer)
# remove layer in the data structures
self.keras_layer_map.pop(layer)
self.layer_list.remove(layer) | python | def _remove_layer(self, layer):
"""
remove the layer and its input/output edges
"""
successors = self.get_successors(layer)
predecessors = self.get_predecessors(layer)
# remove all edges
for succ in successors:
self._remove_edge(layer, succ)
for pred in predecessors:
self._remove_edge(pred, layer)
# remove layer in the data structures
self.keras_layer_map.pop(layer)
self.layer_list.remove(layer) | [
"def",
"_remove_layer",
"(",
"self",
",",
"layer",
")",
":",
"successors",
"=",
"self",
".",
"get_successors",
"(",
"layer",
")",
"predecessors",
"=",
"self",
".",
"get_predecessors",
"(",
"layer",
")",
"# remove all edges",
"for",
"succ",
"in",
"successors",
":",
"self",
".",
"_remove_edge",
"(",
"layer",
",",
"succ",
")",
"for",
"pred",
"in",
"predecessors",
":",
"self",
".",
"_remove_edge",
"(",
"pred",
",",
"layer",
")",
"# remove layer in the data structures",
"self",
".",
"keras_layer_map",
".",
"pop",
"(",
"layer",
")",
"self",
".",
"layer_list",
".",
"remove",
"(",
"layer",
")"
] | remove the layer and its input/output edges | [
"remove",
"the",
"layer",
"and",
"its",
"input",
"/",
"output",
"edges"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology.py#L295-L308 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology.py | NetGraph._insert_layer_after | def _insert_layer_after(self, layer_idx, new_layer, new_keras_layer):
"""
Insert the new_layer after layer, whose position is layer_idx. The new layer's
parameter is stored in a Keras layer called new_keras_layer
"""
# reminder: new_keras_layer is not part of the original Keras network,
# so it's input / output blob information is missing. It serves only as
# a parameter holder.
layer = self.layer_list[layer_idx]
self.layer_list.insert(layer_idx+1, new_layer)
self.keras_layer_map[new_layer] = new_keras_layer
successors = self.get_successors(layer)
# add edge layer -> new_layer
self._add_edge(layer, new_layer)
# add edges new_layer -> layer_successor, remove layer -> successor
for succ in successors:
self._add_edge(new_layer, succ)
self._remove_edge(layer, succ) | python | def _insert_layer_after(self, layer_idx, new_layer, new_keras_layer):
"""
Insert the new_layer after layer, whose position is layer_idx. The new layer's
parameter is stored in a Keras layer called new_keras_layer
"""
# reminder: new_keras_layer is not part of the original Keras network,
# so it's input / output blob information is missing. It serves only as
# a parameter holder.
layer = self.layer_list[layer_idx]
self.layer_list.insert(layer_idx+1, new_layer)
self.keras_layer_map[new_layer] = new_keras_layer
successors = self.get_successors(layer)
# add edge layer -> new_layer
self._add_edge(layer, new_layer)
# add edges new_layer -> layer_successor, remove layer -> successor
for succ in successors:
self._add_edge(new_layer, succ)
self._remove_edge(layer, succ) | [
"def",
"_insert_layer_after",
"(",
"self",
",",
"layer_idx",
",",
"new_layer",
",",
"new_keras_layer",
")",
":",
"# reminder: new_keras_layer is not part of the original Keras network,",
"# so it's input / output blob information is missing. It serves only as",
"# a parameter holder.",
"layer",
"=",
"self",
".",
"layer_list",
"[",
"layer_idx",
"]",
"self",
".",
"layer_list",
".",
"insert",
"(",
"layer_idx",
"+",
"1",
",",
"new_layer",
")",
"self",
".",
"keras_layer_map",
"[",
"new_layer",
"]",
"=",
"new_keras_layer",
"successors",
"=",
"self",
".",
"get_successors",
"(",
"layer",
")",
"# add edge layer -> new_layer",
"self",
".",
"_add_edge",
"(",
"layer",
",",
"new_layer",
")",
"# add edges new_layer -> layer_successor, remove layer -> successor",
"for",
"succ",
"in",
"successors",
":",
"self",
".",
"_add_edge",
"(",
"new_layer",
",",
"succ",
")",
"self",
".",
"_remove_edge",
"(",
"layer",
",",
"succ",
")"
] | Insert the new_layer after layer, whose position is layer_idx. The new layer's
parameter is stored in a Keras layer called new_keras_layer | [
"Insert",
"the",
"new_layer",
"after",
"layer",
"whose",
"position",
"is",
"layer_idx",
".",
"The",
"new",
"layer",
"s",
"parameter",
"is",
"stored",
"in",
"a",
"Keras",
"layer",
"called",
"new_keras_layer"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology.py#L361-L378 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology.py | NetGraph._insert_layer_between | def _insert_layer_between(self, src, snk, new_layer, new_keras_layer):
"""
Insert the new_layer before layer, whose position is layer_idx. The new layer's
parameter is stored in a Keras layer called new_keras_layer
"""
if snk is None:
insert_pos = self.layer_list.index(src) + 1
else:
insert_pos = self.layer_list.index(snk) # insert position
self.layer_list.insert(insert_pos, new_layer)
self.keras_layer_map[new_layer] = new_keras_layer
if src is None: # snk is an input layer
self._add_edge(new_layer, snk)
elif snk is None: # src is an output layer
self._add_edge(src, new_layer)
else:
self._add_edge(src, new_layer)
self._add_edge(new_layer, snk)
self._remove_edge(src, snk) | python | def _insert_layer_between(self, src, snk, new_layer, new_keras_layer):
"""
Insert the new_layer before layer, whose position is layer_idx. The new layer's
parameter is stored in a Keras layer called new_keras_layer
"""
if snk is None:
insert_pos = self.layer_list.index(src) + 1
else:
insert_pos = self.layer_list.index(snk) # insert position
self.layer_list.insert(insert_pos, new_layer)
self.keras_layer_map[new_layer] = new_keras_layer
if src is None: # snk is an input layer
self._add_edge(new_layer, snk)
elif snk is None: # src is an output layer
self._add_edge(src, new_layer)
else:
self._add_edge(src, new_layer)
self._add_edge(new_layer, snk)
self._remove_edge(src, snk) | [
"def",
"_insert_layer_between",
"(",
"self",
",",
"src",
",",
"snk",
",",
"new_layer",
",",
"new_keras_layer",
")",
":",
"if",
"snk",
"is",
"None",
":",
"insert_pos",
"=",
"self",
".",
"layer_list",
".",
"index",
"(",
"src",
")",
"+",
"1",
"else",
":",
"insert_pos",
"=",
"self",
".",
"layer_list",
".",
"index",
"(",
"snk",
")",
"# insert position",
"self",
".",
"layer_list",
".",
"insert",
"(",
"insert_pos",
",",
"new_layer",
")",
"self",
".",
"keras_layer_map",
"[",
"new_layer",
"]",
"=",
"new_keras_layer",
"if",
"src",
"is",
"None",
":",
"# snk is an input layer",
"self",
".",
"_add_edge",
"(",
"new_layer",
",",
"snk",
")",
"elif",
"snk",
"is",
"None",
":",
"# src is an output layer",
"self",
".",
"_add_edge",
"(",
"src",
",",
"new_layer",
")",
"else",
":",
"self",
".",
"_add_edge",
"(",
"src",
",",
"new_layer",
")",
"self",
".",
"_add_edge",
"(",
"new_layer",
",",
"snk",
")",
"self",
".",
"_remove_edge",
"(",
"src",
",",
"snk",
")"
] | Insert the new_layer before layer, whose position is layer_idx. The new layer's
parameter is stored in a Keras layer called new_keras_layer | [
"Insert",
"the",
"new_layer",
"before",
"layer",
"whose",
"position",
"is",
"layer_idx",
".",
"The",
"new",
"layer",
"s",
"parameter",
"is",
"stored",
"in",
"a",
"Keras",
"layer",
"called",
"new_keras_layer"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology.py#L380-L398 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology.py | NetGraph.defuse_activation | def defuse_activation(self):
"""
Defuse the fused activation layers in the network.
"""
idx, nb_layers = 0, len(self.layer_list)
while idx < nb_layers:
layer = self.layer_list[idx]
k_layer = self.keras_layer_map[layer]
# unwrap time-distributed layers
if (isinstance(k_layer, _keras.layers.TimeDistributed)):
k_layer = k_layer.layer
if (isinstance(k_layer, _keras.layers.convolutional.Convolution2D) or
isinstance(k_layer, _keras.layers.convolutional.Convolution1D) or
isinstance(k_layer, _keras.layers.core.Dense)):
import six
if six.PY2:
func_name = k_layer.activation.func_name
else:
func_name = k_layer.activation.__name__
if (func_name != 'linear'):
# Create new layer
new_layer = layer + '__activation__'
new_keras_layer = _keras.layers.core.Activation(func_name)
# insert new layer after it
self._insert_layer_after(idx, new_layer, new_keras_layer)
idx += 1
nb_layers += 1
idx += 1 | python | def defuse_activation(self):
"""
Defuse the fused activation layers in the network.
"""
idx, nb_layers = 0, len(self.layer_list)
while idx < nb_layers:
layer = self.layer_list[idx]
k_layer = self.keras_layer_map[layer]
# unwrap time-distributed layers
if (isinstance(k_layer, _keras.layers.TimeDistributed)):
k_layer = k_layer.layer
if (isinstance(k_layer, _keras.layers.convolutional.Convolution2D) or
isinstance(k_layer, _keras.layers.convolutional.Convolution1D) or
isinstance(k_layer, _keras.layers.core.Dense)):
import six
if six.PY2:
func_name = k_layer.activation.func_name
else:
func_name = k_layer.activation.__name__
if (func_name != 'linear'):
# Create new layer
new_layer = layer + '__activation__'
new_keras_layer = _keras.layers.core.Activation(func_name)
# insert new layer after it
self._insert_layer_after(idx, new_layer, new_keras_layer)
idx += 1
nb_layers += 1
idx += 1 | [
"def",
"defuse_activation",
"(",
"self",
")",
":",
"idx",
",",
"nb_layers",
"=",
"0",
",",
"len",
"(",
"self",
".",
"layer_list",
")",
"while",
"idx",
"<",
"nb_layers",
":",
"layer",
"=",
"self",
".",
"layer_list",
"[",
"idx",
"]",
"k_layer",
"=",
"self",
".",
"keras_layer_map",
"[",
"layer",
"]",
"# unwrap time-distributed layers",
"if",
"(",
"isinstance",
"(",
"k_layer",
",",
"_keras",
".",
"layers",
".",
"TimeDistributed",
")",
")",
":",
"k_layer",
"=",
"k_layer",
".",
"layer",
"if",
"(",
"isinstance",
"(",
"k_layer",
",",
"_keras",
".",
"layers",
".",
"convolutional",
".",
"Convolution2D",
")",
"or",
"isinstance",
"(",
"k_layer",
",",
"_keras",
".",
"layers",
".",
"convolutional",
".",
"Convolution1D",
")",
"or",
"isinstance",
"(",
"k_layer",
",",
"_keras",
".",
"layers",
".",
"core",
".",
"Dense",
")",
")",
":",
"import",
"six",
"if",
"six",
".",
"PY2",
":",
"func_name",
"=",
"k_layer",
".",
"activation",
".",
"func_name",
"else",
":",
"func_name",
"=",
"k_layer",
".",
"activation",
".",
"__name__",
"if",
"(",
"func_name",
"!=",
"'linear'",
")",
":",
"# Create new layer",
"new_layer",
"=",
"layer",
"+",
"'__activation__'",
"new_keras_layer",
"=",
"_keras",
".",
"layers",
".",
"core",
".",
"Activation",
"(",
"func_name",
")",
"# insert new layer after it",
"self",
".",
"_insert_layer_after",
"(",
"idx",
",",
"new_layer",
",",
"new_keras_layer",
")",
"idx",
"+=",
"1",
"nb_layers",
"+=",
"1",
"idx",
"+=",
"1"
] | Defuse the fused activation layers in the network. | [
"Defuse",
"the",
"fused",
"activation",
"layers",
"in",
"the",
"network",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology.py#L400-L430 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology.py | NetGraph._get_1d_interface_edges | def _get_1d_interface_edges(self):
"""
Get edges that represents transition from not 1D to 1D, and 1D to not 1D
A 'in_edge e(u,v)' means u operates on non-1D blobs, but v operates on 1D blobs.
An 'out_edge e(u,v)' means u operates on 1D blobs, but v operates on non-1D blobs.
"""
in_edges = []
for layer in self.layer_list:
if not self.is_1d_layer(layer):
continue
preds = self.get_predecessors(layer)
if len(preds) == 0:
in_edges.append((None, layer))
else:
# because 1D layers are all 1-input, there should only be 1 predecessor
u, v = preds[0], layer
while (u != None) and (self.is_activation(u) or type(u) in _KERAS_NORMALIZATION_LAYERS):
preds = self.get_predecessors(u)
v = u
u = preds[0] if len(preds) > 0 else None
if u is None or (not self.is_1d_layer(u)):
in_edges.append((u, v))
out_edges = []
for layer in self.layer_list:
if not self.is_1d_layer(layer):
continue
succs = self.get_successors(layer)
if len(succs) == 0:
out_edges.append((layer, None))
elif not self.is_activation(succs[0]):
for succ in succs:
if not self.is_1d_layer(succ):
out_edges.append((layer, succ))
else:
act_layer = succs[0]
succs = self.get_successors(act_layer)
if len(succs) == 0:
out_edges.append((act_layer, None))
else:
for succ in succs:
if not self.is_1d_layer(succ):
out_edges.append((act_layer, succ))
return in_edges, out_edges | python | def _get_1d_interface_edges(self):
"""
Get edges that represents transition from not 1D to 1D, and 1D to not 1D
A 'in_edge e(u,v)' means u operates on non-1D blobs, but v operates on 1D blobs.
An 'out_edge e(u,v)' means u operates on 1D blobs, but v operates on non-1D blobs.
"""
in_edges = []
for layer in self.layer_list:
if not self.is_1d_layer(layer):
continue
preds = self.get_predecessors(layer)
if len(preds) == 0:
in_edges.append((None, layer))
else:
# because 1D layers are all 1-input, there should only be 1 predecessor
u, v = preds[0], layer
while (u != None) and (self.is_activation(u) or type(u) in _KERAS_NORMALIZATION_LAYERS):
preds = self.get_predecessors(u)
v = u
u = preds[0] if len(preds) > 0 else None
if u is None or (not self.is_1d_layer(u)):
in_edges.append((u, v))
out_edges = []
for layer in self.layer_list:
if not self.is_1d_layer(layer):
continue
succs = self.get_successors(layer)
if len(succs) == 0:
out_edges.append((layer, None))
elif not self.is_activation(succs[0]):
for succ in succs:
if not self.is_1d_layer(succ):
out_edges.append((layer, succ))
else:
act_layer = succs[0]
succs = self.get_successors(act_layer)
if len(succs) == 0:
out_edges.append((act_layer, None))
else:
for succ in succs:
if not self.is_1d_layer(succ):
out_edges.append((act_layer, succ))
return in_edges, out_edges | [
"def",
"_get_1d_interface_edges",
"(",
"self",
")",
":",
"in_edges",
"=",
"[",
"]",
"for",
"layer",
"in",
"self",
".",
"layer_list",
":",
"if",
"not",
"self",
".",
"is_1d_layer",
"(",
"layer",
")",
":",
"continue",
"preds",
"=",
"self",
".",
"get_predecessors",
"(",
"layer",
")",
"if",
"len",
"(",
"preds",
")",
"==",
"0",
":",
"in_edges",
".",
"append",
"(",
"(",
"None",
",",
"layer",
")",
")",
"else",
":",
"# because 1D layers are all 1-input, there should only be 1 predecessor",
"u",
",",
"v",
"=",
"preds",
"[",
"0",
"]",
",",
"layer",
"while",
"(",
"u",
"!=",
"None",
")",
"and",
"(",
"self",
".",
"is_activation",
"(",
"u",
")",
"or",
"type",
"(",
"u",
")",
"in",
"_KERAS_NORMALIZATION_LAYERS",
")",
":",
"preds",
"=",
"self",
".",
"get_predecessors",
"(",
"u",
")",
"v",
"=",
"u",
"u",
"=",
"preds",
"[",
"0",
"]",
"if",
"len",
"(",
"preds",
")",
">",
"0",
"else",
"None",
"if",
"u",
"is",
"None",
"or",
"(",
"not",
"self",
".",
"is_1d_layer",
"(",
"u",
")",
")",
":",
"in_edges",
".",
"append",
"(",
"(",
"u",
",",
"v",
")",
")",
"out_edges",
"=",
"[",
"]",
"for",
"layer",
"in",
"self",
".",
"layer_list",
":",
"if",
"not",
"self",
".",
"is_1d_layer",
"(",
"layer",
")",
":",
"continue",
"succs",
"=",
"self",
".",
"get_successors",
"(",
"layer",
")",
"if",
"len",
"(",
"succs",
")",
"==",
"0",
":",
"out_edges",
".",
"append",
"(",
"(",
"layer",
",",
"None",
")",
")",
"elif",
"not",
"self",
".",
"is_activation",
"(",
"succs",
"[",
"0",
"]",
")",
":",
"for",
"succ",
"in",
"succs",
":",
"if",
"not",
"self",
".",
"is_1d_layer",
"(",
"succ",
")",
":",
"out_edges",
".",
"append",
"(",
"(",
"layer",
",",
"succ",
")",
")",
"else",
":",
"act_layer",
"=",
"succs",
"[",
"0",
"]",
"succs",
"=",
"self",
".",
"get_successors",
"(",
"act_layer",
")",
"if",
"len",
"(",
"succs",
")",
"==",
"0",
":",
"out_edges",
".",
"append",
"(",
"(",
"act_layer",
",",
"None",
")",
")",
"else",
":",
"for",
"succ",
"in",
"succs",
":",
"if",
"not",
"self",
".",
"is_1d_layer",
"(",
"succ",
")",
":",
"out_edges",
".",
"append",
"(",
"(",
"act_layer",
",",
"succ",
")",
")",
"return",
"in_edges",
",",
"out_edges"
] | Get edges that represents transition from not 1D to 1D, and 1D to not 1D
A 'in_edge e(u,v)' means u operates on non-1D blobs, but v operates on 1D blobs.
An 'out_edge e(u,v)' means u operates on 1D blobs, but v operates on non-1D blobs. | [
"Get",
"edges",
"that",
"represents",
"transition",
"from",
"not",
"1D",
"to",
"1D",
"and",
"1D",
"to",
"not",
"1D",
"A",
"in_edge",
"e",
"(",
"u",
"v",
")",
"means",
"u",
"operates",
"on",
"non",
"-",
"1D",
"blobs",
"but",
"v",
"operates",
"on",
"1D",
"blobs",
".",
"An",
"out_edge",
"e",
"(",
"u",
"v",
")",
"means",
"u",
"operates",
"on",
"1D",
"blobs",
"but",
"v",
"operates",
"on",
"non",
"-",
"1D",
"blobs",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology.py#L446-L490 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology.py | NetGraph.insert_1d_permute_layers | def insert_1d_permute_layers(self):
"""
Insert permutation layers before a 1D start point or after 1D end point
"""
idx, nb_layers = 0, len(self.layer_list)
in_edges, out_edges = self._get_1d_interface_edges()
# Hacky Warning: (1) use a 4-D permute, which is not likely to happen in Keras,
# to represent actual permutation needed for (seq, c, h, w) in CoreML
# (2) Assume 2-D input shape has meaning (seq, c), and during CoreML runtime,
# it is represented as 4D blob, (seq, c, h, w)
for in_edge in in_edges:
src, snk = in_edge
if src is None:
permute_layer = '_permute_' + snk
else:
permute_layer = src + '_permute_' + snk
keras_permute = _keras.layers.Permute(dims=(3,1,2,0)) # assume w = 1, switch seq and w
self._insert_layer_between(src, snk, permute_layer, keras_permute)
for out_edge in out_edges:
src, snk = out_edge
if snk is None:
permute_layer = src + '_permute_'
else:
permute_layer = src + '_permute_' + snk
keras_permute = _keras.layers.Permute(dims=(3,1,2,0)) # assume w = 1, switch seq and w back
self._insert_layer_between(src, snk, permute_layer, keras_permute) | python | def insert_1d_permute_layers(self):
"""
Insert permutation layers before a 1D start point or after 1D end point
"""
idx, nb_layers = 0, len(self.layer_list)
in_edges, out_edges = self._get_1d_interface_edges()
# Hacky Warning: (1) use a 4-D permute, which is not likely to happen in Keras,
# to represent actual permutation needed for (seq, c, h, w) in CoreML
# (2) Assume 2-D input shape has meaning (seq, c), and during CoreML runtime,
# it is represented as 4D blob, (seq, c, h, w)
for in_edge in in_edges:
src, snk = in_edge
if src is None:
permute_layer = '_permute_' + snk
else:
permute_layer = src + '_permute_' + snk
keras_permute = _keras.layers.Permute(dims=(3,1,2,0)) # assume w = 1, switch seq and w
self._insert_layer_between(src, snk, permute_layer, keras_permute)
for out_edge in out_edges:
src, snk = out_edge
if snk is None:
permute_layer = src + '_permute_'
else:
permute_layer = src + '_permute_' + snk
keras_permute = _keras.layers.Permute(dims=(3,1,2,0)) # assume w = 1, switch seq and w back
self._insert_layer_between(src, snk, permute_layer, keras_permute) | [
"def",
"insert_1d_permute_layers",
"(",
"self",
")",
":",
"idx",
",",
"nb_layers",
"=",
"0",
",",
"len",
"(",
"self",
".",
"layer_list",
")",
"in_edges",
",",
"out_edges",
"=",
"self",
".",
"_get_1d_interface_edges",
"(",
")",
"# Hacky Warning: (1) use a 4-D permute, which is not likely to happen in Keras,",
"# to represent actual permutation needed for (seq, c, h, w) in CoreML",
"# (2) Assume 2-D input shape has meaning (seq, c), and during CoreML runtime,",
"# it is represented as 4D blob, (seq, c, h, w)",
"for",
"in_edge",
"in",
"in_edges",
":",
"src",
",",
"snk",
"=",
"in_edge",
"if",
"src",
"is",
"None",
":",
"permute_layer",
"=",
"'_permute_'",
"+",
"snk",
"else",
":",
"permute_layer",
"=",
"src",
"+",
"'_permute_'",
"+",
"snk",
"keras_permute",
"=",
"_keras",
".",
"layers",
".",
"Permute",
"(",
"dims",
"=",
"(",
"3",
",",
"1",
",",
"2",
",",
"0",
")",
")",
"# assume w = 1, switch seq and w",
"self",
".",
"_insert_layer_between",
"(",
"src",
",",
"snk",
",",
"permute_layer",
",",
"keras_permute",
")",
"for",
"out_edge",
"in",
"out_edges",
":",
"src",
",",
"snk",
"=",
"out_edge",
"if",
"snk",
"is",
"None",
":",
"permute_layer",
"=",
"src",
"+",
"'_permute_'",
"else",
":",
"permute_layer",
"=",
"src",
"+",
"'_permute_'",
"+",
"snk",
"keras_permute",
"=",
"_keras",
".",
"layers",
".",
"Permute",
"(",
"dims",
"=",
"(",
"3",
",",
"1",
",",
"2",
",",
"0",
")",
")",
"# assume w = 1, switch seq and w back",
"self",
".",
"_insert_layer_between",
"(",
"src",
",",
"snk",
",",
"permute_layer",
",",
"keras_permute",
")"
] | Insert permutation layers before a 1D start point or after 1D end point | [
"Insert",
"permutation",
"layers",
"before",
"a",
"1D",
"start",
"point",
"or",
"after",
"1D",
"end",
"point"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_topology.py#L492-L518 | train |
apple/turicreate | src/unity/python/turicreate/meta/asttools/mutators/replace_mutator.py | replace_nodes | def replace_nodes(root, old, new):
'''
Replace the old node with the new one.
Old must be an indirect child of root
:param root: ast node that contains an indirect reference to old
:param old: node to replace
:param new: node to replace `old` with
'''
rep = Replacer(old, new)
rep.visit(root)
return | python | def replace_nodes(root, old, new):
'''
Replace the old node with the new one.
Old must be an indirect child of root
:param root: ast node that contains an indirect reference to old
:param old: node to replace
:param new: node to replace `old` with
'''
rep = Replacer(old, new)
rep.visit(root)
return | [
"def",
"replace_nodes",
"(",
"root",
",",
"old",
",",
"new",
")",
":",
"rep",
"=",
"Replacer",
"(",
"old",
",",
"new",
")",
"rep",
".",
"visit",
"(",
"root",
")",
"return"
] | Replace the old node with the new one.
Old must be an indirect child of root
:param root: ast node that contains an indirect reference to old
:param old: node to replace
:param new: node to replace `old` with | [
"Replace",
"the",
"old",
"node",
"with",
"the",
"new",
"one",
".",
"Old",
"must",
"be",
"an",
"indirect",
"child",
"of",
"root",
":",
"param",
"root",
":",
"ast",
"node",
"that",
"contains",
"an",
"indirect",
"reference",
"to",
"old",
":",
"param",
"old",
":",
"node",
"to",
"replace",
":",
"param",
"new",
":",
"node",
"to",
"replace",
"old",
"with"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/meta/asttools/mutators/replace_mutator.py#L49-L62 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/build/configure.py | log_component_configuration | def log_component_configuration(component, message):
"""Report something about component configuration that the user should better know."""
assert isinstance(component, basestring)
assert isinstance(message, basestring)
__component_logs.setdefault(component, []).append(message) | python | def log_component_configuration(component, message):
"""Report something about component configuration that the user should better know."""
assert isinstance(component, basestring)
assert isinstance(message, basestring)
__component_logs.setdefault(component, []).append(message) | [
"def",
"log_component_configuration",
"(",
"component",
",",
"message",
")",
":",
"assert",
"isinstance",
"(",
"component",
",",
"basestring",
")",
"assert",
"isinstance",
"(",
"message",
",",
"basestring",
")",
"__component_logs",
".",
"setdefault",
"(",
"component",
",",
"[",
"]",
")",
".",
"append",
"(",
"message",
")"
] | Report something about component configuration that the user should better know. | [
"Report",
"something",
"about",
"component",
"configuration",
"that",
"the",
"user",
"should",
"better",
"know",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/build/configure.py#L52-L56 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_feature_engineering/__init__.py | create | def create(dataset, transformers):
"""
Create a Transformer object to transform data for feature engineering.
Parameters
----------
dataset : SFrame
The dataset to use for training the model.
transformers: Transformer | list[Transformer]
An Transformer or a list of Transformers.
See Also
--------
turicreate.toolkits.feature_engineering._feature_engineering._TransformerBase
Examples
--------
.. sourcecode:: python
# Create data.
>>> sf = turicreate.SFrame({'a': [1,2,3], 'b' : [2,3,4]})
>>> from turicreate.feature_engineering import FeatureHasher, \
QuadraticFeatures, OneHotEncoder
# Create a single transformer.
>>> encoder = turicreate.feature_engineering.create(sf,
OneHotEncoder(max_categories = 10))
# Create a chain of transformers.
>>> chain = turicreate.feature_engineering.create(sf, [
QuadraticFeatures(),
FeatureHasher()
])
# Create a chain of transformers with names for each of the steps.
>>> chain = turicreate.feature_engineering.create(sf, [
('quadratic', QuadraticFeatures()),
('hasher', FeatureHasher())
])
"""
err_msg = "The parameters 'transformers' must be a valid Transformer object."
cls = transformers.__class__
_raise_error_if_not_sframe(dataset, "dataset")
# List of transformers.
if (cls == list):
transformers = TransformerChain(transformers)
# Transformer.
else:
if not issubclass(cls, TransformerBase):
raise TypeError(err_msg)
# Fit and return
transformers.fit(dataset)
return transformers | python | def create(dataset, transformers):
"""
Create a Transformer object to transform data for feature engineering.
Parameters
----------
dataset : SFrame
The dataset to use for training the model.
transformers: Transformer | list[Transformer]
An Transformer or a list of Transformers.
See Also
--------
turicreate.toolkits.feature_engineering._feature_engineering._TransformerBase
Examples
--------
.. sourcecode:: python
# Create data.
>>> sf = turicreate.SFrame({'a': [1,2,3], 'b' : [2,3,4]})
>>> from turicreate.feature_engineering import FeatureHasher, \
QuadraticFeatures, OneHotEncoder
# Create a single transformer.
>>> encoder = turicreate.feature_engineering.create(sf,
OneHotEncoder(max_categories = 10))
# Create a chain of transformers.
>>> chain = turicreate.feature_engineering.create(sf, [
QuadraticFeatures(),
FeatureHasher()
])
# Create a chain of transformers with names for each of the steps.
>>> chain = turicreate.feature_engineering.create(sf, [
('quadratic', QuadraticFeatures()),
('hasher', FeatureHasher())
])
"""
err_msg = "The parameters 'transformers' must be a valid Transformer object."
cls = transformers.__class__
_raise_error_if_not_sframe(dataset, "dataset")
# List of transformers.
if (cls == list):
transformers = TransformerChain(transformers)
# Transformer.
else:
if not issubclass(cls, TransformerBase):
raise TypeError(err_msg)
# Fit and return
transformers.fit(dataset)
return transformers | [
"def",
"create",
"(",
"dataset",
",",
"transformers",
")",
":",
"err_msg",
"=",
"\"The parameters 'transformers' must be a valid Transformer object.\"",
"cls",
"=",
"transformers",
".",
"__class__",
"_raise_error_if_not_sframe",
"(",
"dataset",
",",
"\"dataset\"",
")",
"# List of transformers.",
"if",
"(",
"cls",
"==",
"list",
")",
":",
"transformers",
"=",
"TransformerChain",
"(",
"transformers",
")",
"# Transformer.",
"else",
":",
"if",
"not",
"issubclass",
"(",
"cls",
",",
"TransformerBase",
")",
":",
"raise",
"TypeError",
"(",
"err_msg",
")",
"# Fit and return",
"transformers",
".",
"fit",
"(",
"dataset",
")",
"return",
"transformers"
] | Create a Transformer object to transform data for feature engineering.
Parameters
----------
dataset : SFrame
The dataset to use for training the model.
transformers: Transformer | list[Transformer]
An Transformer or a list of Transformers.
See Also
--------
turicreate.toolkits.feature_engineering._feature_engineering._TransformerBase
Examples
--------
.. sourcecode:: python
# Create data.
>>> sf = turicreate.SFrame({'a': [1,2,3], 'b' : [2,3,4]})
>>> from turicreate.feature_engineering import FeatureHasher, \
QuadraticFeatures, OneHotEncoder
# Create a single transformer.
>>> encoder = turicreate.feature_engineering.create(sf,
OneHotEncoder(max_categories = 10))
# Create a chain of transformers.
>>> chain = turicreate.feature_engineering.create(sf, [
QuadraticFeatures(),
FeatureHasher()
])
# Create a chain of transformers with names for each of the steps.
>>> chain = turicreate.feature_engineering.create(sf, [
('quadratic', QuadraticFeatures()),
('hasher', FeatureHasher())
]) | [
"Create",
"a",
"Transformer",
"object",
"to",
"transform",
"data",
"for",
"feature",
"engineering",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_feature_engineering/__init__.py#L47-L106 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/sound_classifier/_audio_feature_extractor.py | VGGishFeatureExtractor._preprocess_data | def _preprocess_data(audio_data, verbose=True):
'''
Preprocess each example, breaking it up into frames.
Returns two numpy arrays: preprocessed frame and their indexes
'''
from .vggish_input import waveform_to_examples
last_progress_update = _time.time()
progress_header_printed = False
# Can't run as a ".apply(...)" due to numba.jit decorator issue:
# https://github.com/apple/turicreate/issues/1216
preprocessed_data, audio_data_index = [], []
for i, audio_dict in enumerate(audio_data):
scaled_data = audio_dict['data'] / 32768.0
data = waveform_to_examples(scaled_data, audio_dict['sample_rate'])
for j in data:
preprocessed_data.append([j])
audio_data_index.append(i)
# If `verbose` is set, print an progress update about every 20s
if verbose and _time.time() - last_progress_update >= 20:
if not progress_header_printed:
print("Preprocessing audio data -")
progress_header_printed = True
print("Preprocessed {} of {} examples".format(i, len(audio_data)))
last_progress_update = _time.time()
if progress_header_printed:
print("Preprocessed {} of {} examples\n".format(len(audio_data), len(audio_data)))
return _np.asarray(preprocessed_data), audio_data_index | python | def _preprocess_data(audio_data, verbose=True):
'''
Preprocess each example, breaking it up into frames.
Returns two numpy arrays: preprocessed frame and their indexes
'''
from .vggish_input import waveform_to_examples
last_progress_update = _time.time()
progress_header_printed = False
# Can't run as a ".apply(...)" due to numba.jit decorator issue:
# https://github.com/apple/turicreate/issues/1216
preprocessed_data, audio_data_index = [], []
for i, audio_dict in enumerate(audio_data):
scaled_data = audio_dict['data'] / 32768.0
data = waveform_to_examples(scaled_data, audio_dict['sample_rate'])
for j in data:
preprocessed_data.append([j])
audio_data_index.append(i)
# If `verbose` is set, print an progress update about every 20s
if verbose and _time.time() - last_progress_update >= 20:
if not progress_header_printed:
print("Preprocessing audio data -")
progress_header_printed = True
print("Preprocessed {} of {} examples".format(i, len(audio_data)))
last_progress_update = _time.time()
if progress_header_printed:
print("Preprocessed {} of {} examples\n".format(len(audio_data), len(audio_data)))
return _np.asarray(preprocessed_data), audio_data_index | [
"def",
"_preprocess_data",
"(",
"audio_data",
",",
"verbose",
"=",
"True",
")",
":",
"from",
".",
"vggish_input",
"import",
"waveform_to_examples",
"last_progress_update",
"=",
"_time",
".",
"time",
"(",
")",
"progress_header_printed",
"=",
"False",
"# Can't run as a \".apply(...)\" due to numba.jit decorator issue:",
"# https://github.com/apple/turicreate/issues/1216",
"preprocessed_data",
",",
"audio_data_index",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"i",
",",
"audio_dict",
"in",
"enumerate",
"(",
"audio_data",
")",
":",
"scaled_data",
"=",
"audio_dict",
"[",
"'data'",
"]",
"/",
"32768.0",
"data",
"=",
"waveform_to_examples",
"(",
"scaled_data",
",",
"audio_dict",
"[",
"'sample_rate'",
"]",
")",
"for",
"j",
"in",
"data",
":",
"preprocessed_data",
".",
"append",
"(",
"[",
"j",
"]",
")",
"audio_data_index",
".",
"append",
"(",
"i",
")",
"# If `verbose` is set, print an progress update about every 20s",
"if",
"verbose",
"and",
"_time",
".",
"time",
"(",
")",
"-",
"last_progress_update",
">=",
"20",
":",
"if",
"not",
"progress_header_printed",
":",
"print",
"(",
"\"Preprocessing audio data -\"",
")",
"progress_header_printed",
"=",
"True",
"print",
"(",
"\"Preprocessed {} of {} examples\"",
".",
"format",
"(",
"i",
",",
"len",
"(",
"audio_data",
")",
")",
")",
"last_progress_update",
"=",
"_time",
".",
"time",
"(",
")",
"if",
"progress_header_printed",
":",
"print",
"(",
"\"Preprocessed {} of {} examples\\n\"",
".",
"format",
"(",
"len",
"(",
"audio_data",
")",
",",
"len",
"(",
"audio_data",
")",
")",
")",
"return",
"_np",
".",
"asarray",
"(",
"preprocessed_data",
")",
",",
"audio_data_index"
] | Preprocess each example, breaking it up into frames.
Returns two numpy arrays: preprocessed frame and their indexes | [
"Preprocess",
"each",
"example",
"breaking",
"it",
"up",
"into",
"frames",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/sound_classifier/_audio_feature_extractor.py#L40-L72 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/sound_classifier/_audio_feature_extractor.py | VGGishFeatureExtractor._extract_features | def _extract_features(self, preprocessed_data, verbose=True):
"""
Parameters
----------
preprocessed_data : SArray
Returns
-------
numpy array containing the deep features
"""
last_progress_update = _time.time()
progress_header_printed = False
deep_features = _tc.SArrayBuilder(_np.ndarray)
from mxnet.gluon import utils
if _mac_ver() < (10, 14):
# Use MXNet
preprocessed_data = mx.nd.array(preprocessed_data)
ctx_list = self.ctx
if len(preprocessed_data) < len(ctx_list):
ctx_list = ctx_list[:len(preprocessed_data)]
batches = utils.split_and_load(preprocessed_data, ctx_list=ctx_list, even_split=False)
for i, cur_batch in enumerate(batches):
y = self.vggish_model.forward(cur_batch).asnumpy()
for j in y:
deep_features.append(j)
# If `verbose` is set, print an progress update about every 20s
if verbose and _time.time() - last_progress_update >= 20:
if not progress_header_printed:
print("Extracting deep features -")
progress_header_printed = True
print("Extracted {} of {} batches".format(i, len(batches)))
last_progress_update = _time.time()
if progress_header_printed:
print("Extracted {} of {} batches\n".format(len(batches), len(batches)))
else:
# Use Core ML
for i, cur_example in enumerate(preprocessed_data):
for cur_frame in cur_example:
x = {'input1': [cur_frame]}
y = self.vggish_model.predict(x)
deep_features.append(y['output1'])
# If `verbose` is set, print an progress update about every 20s
if verbose and _time.time() - last_progress_update >= 20:
if not progress_header_printed:
print("Extracting deep features -")
progress_header_printed = True
print("Extracted {} of {}".format(i, len(preprocessed_data)))
last_progress_update = _time.time()
if progress_header_printed:
print("Extracted {} of {}\n".format(len(preprocessed_data), len(preprocessed_data)))
return deep_features.close() | python | def _extract_features(self, preprocessed_data, verbose=True):
"""
Parameters
----------
preprocessed_data : SArray
Returns
-------
numpy array containing the deep features
"""
last_progress_update = _time.time()
progress_header_printed = False
deep_features = _tc.SArrayBuilder(_np.ndarray)
from mxnet.gluon import utils
if _mac_ver() < (10, 14):
# Use MXNet
preprocessed_data = mx.nd.array(preprocessed_data)
ctx_list = self.ctx
if len(preprocessed_data) < len(ctx_list):
ctx_list = ctx_list[:len(preprocessed_data)]
batches = utils.split_and_load(preprocessed_data, ctx_list=ctx_list, even_split=False)
for i, cur_batch in enumerate(batches):
y = self.vggish_model.forward(cur_batch).asnumpy()
for j in y:
deep_features.append(j)
# If `verbose` is set, print an progress update about every 20s
if verbose and _time.time() - last_progress_update >= 20:
if not progress_header_printed:
print("Extracting deep features -")
progress_header_printed = True
print("Extracted {} of {} batches".format(i, len(batches)))
last_progress_update = _time.time()
if progress_header_printed:
print("Extracted {} of {} batches\n".format(len(batches), len(batches)))
else:
# Use Core ML
for i, cur_example in enumerate(preprocessed_data):
for cur_frame in cur_example:
x = {'input1': [cur_frame]}
y = self.vggish_model.predict(x)
deep_features.append(y['output1'])
# If `verbose` is set, print an progress update about every 20s
if verbose and _time.time() - last_progress_update >= 20:
if not progress_header_printed:
print("Extracting deep features -")
progress_header_printed = True
print("Extracted {} of {}".format(i, len(preprocessed_data)))
last_progress_update = _time.time()
if progress_header_printed:
print("Extracted {} of {}\n".format(len(preprocessed_data), len(preprocessed_data)))
return deep_features.close() | [
"def",
"_extract_features",
"(",
"self",
",",
"preprocessed_data",
",",
"verbose",
"=",
"True",
")",
":",
"last_progress_update",
"=",
"_time",
".",
"time",
"(",
")",
"progress_header_printed",
"=",
"False",
"deep_features",
"=",
"_tc",
".",
"SArrayBuilder",
"(",
"_np",
".",
"ndarray",
")",
"from",
"mxnet",
".",
"gluon",
"import",
"utils",
"if",
"_mac_ver",
"(",
")",
"<",
"(",
"10",
",",
"14",
")",
":",
"# Use MXNet",
"preprocessed_data",
"=",
"mx",
".",
"nd",
".",
"array",
"(",
"preprocessed_data",
")",
"ctx_list",
"=",
"self",
".",
"ctx",
"if",
"len",
"(",
"preprocessed_data",
")",
"<",
"len",
"(",
"ctx_list",
")",
":",
"ctx_list",
"=",
"ctx_list",
"[",
":",
"len",
"(",
"preprocessed_data",
")",
"]",
"batches",
"=",
"utils",
".",
"split_and_load",
"(",
"preprocessed_data",
",",
"ctx_list",
"=",
"ctx_list",
",",
"even_split",
"=",
"False",
")",
"for",
"i",
",",
"cur_batch",
"in",
"enumerate",
"(",
"batches",
")",
":",
"y",
"=",
"self",
".",
"vggish_model",
".",
"forward",
"(",
"cur_batch",
")",
".",
"asnumpy",
"(",
")",
"for",
"j",
"in",
"y",
":",
"deep_features",
".",
"append",
"(",
"j",
")",
"# If `verbose` is set, print an progress update about every 20s",
"if",
"verbose",
"and",
"_time",
".",
"time",
"(",
")",
"-",
"last_progress_update",
">=",
"20",
":",
"if",
"not",
"progress_header_printed",
":",
"print",
"(",
"\"Extracting deep features -\"",
")",
"progress_header_printed",
"=",
"True",
"print",
"(",
"\"Extracted {} of {} batches\"",
".",
"format",
"(",
"i",
",",
"len",
"(",
"batches",
")",
")",
")",
"last_progress_update",
"=",
"_time",
".",
"time",
"(",
")",
"if",
"progress_header_printed",
":",
"print",
"(",
"\"Extracted {} of {} batches\\n\"",
".",
"format",
"(",
"len",
"(",
"batches",
")",
",",
"len",
"(",
"batches",
")",
")",
")",
"else",
":",
"# Use Core ML",
"for",
"i",
",",
"cur_example",
"in",
"enumerate",
"(",
"preprocessed_data",
")",
":",
"for",
"cur_frame",
"in",
"cur_example",
":",
"x",
"=",
"{",
"'input1'",
":",
"[",
"cur_frame",
"]",
"}",
"y",
"=",
"self",
".",
"vggish_model",
".",
"predict",
"(",
"x",
")",
"deep_features",
".",
"append",
"(",
"y",
"[",
"'output1'",
"]",
")",
"# If `verbose` is set, print an progress update about every 20s",
"if",
"verbose",
"and",
"_time",
".",
"time",
"(",
")",
"-",
"last_progress_update",
">=",
"20",
":",
"if",
"not",
"progress_header_printed",
":",
"print",
"(",
"\"Extracting deep features -\"",
")",
"progress_header_printed",
"=",
"True",
"print",
"(",
"\"Extracted {} of {}\"",
".",
"format",
"(",
"i",
",",
"len",
"(",
"preprocessed_data",
")",
")",
")",
"last_progress_update",
"=",
"_time",
".",
"time",
"(",
")",
"if",
"progress_header_printed",
":",
"print",
"(",
"\"Extracted {} of {}\\n\"",
".",
"format",
"(",
"len",
"(",
"preprocessed_data",
")",
",",
"len",
"(",
"preprocessed_data",
")",
")",
")",
"return",
"deep_features",
".",
"close",
"(",
")"
] | Parameters
----------
preprocessed_data : SArray
Returns
-------
numpy array containing the deep features | [
"Parameters",
"----------",
"preprocessed_data",
":",
"SArray"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/sound_classifier/_audio_feature_extractor.py#L112-L170 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/sound_classifier/_audio_feature_extractor.py | VGGishFeatureExtractor.get_deep_features | def get_deep_features(self, audio_data, verbose):
'''
Performs both audio preprocessing and VGGish deep feature extraction.
'''
preprocessed_data, row_ids = self._preprocess_data(audio_data, verbose)
deep_features = self._extract_features(preprocessed_data, verbose)
output = _tc.SFrame({'deep features': deep_features, 'row id': row_ids})
output = output.unstack('deep features')
max_row_id = len(audio_data)
missing_ids = set(range(max_row_id)) - set(output['row id'].unique())
if len(missing_ids) != 0:
empty_rows = _tc.SFrame({'List of deep features': [ [] for _ in range(len(missing_ids)) ],
'row id': missing_ids})
output = output.append(empty_rows)
output = output.sort('row id')
return output['List of deep features'] | python | def get_deep_features(self, audio_data, verbose):
'''
Performs both audio preprocessing and VGGish deep feature extraction.
'''
preprocessed_data, row_ids = self._preprocess_data(audio_data, verbose)
deep_features = self._extract_features(preprocessed_data, verbose)
output = _tc.SFrame({'deep features': deep_features, 'row id': row_ids})
output = output.unstack('deep features')
max_row_id = len(audio_data)
missing_ids = set(range(max_row_id)) - set(output['row id'].unique())
if len(missing_ids) != 0:
empty_rows = _tc.SFrame({'List of deep features': [ [] for _ in range(len(missing_ids)) ],
'row id': missing_ids})
output = output.append(empty_rows)
output = output.sort('row id')
return output['List of deep features'] | [
"def",
"get_deep_features",
"(",
"self",
",",
"audio_data",
",",
"verbose",
")",
":",
"preprocessed_data",
",",
"row_ids",
"=",
"self",
".",
"_preprocess_data",
"(",
"audio_data",
",",
"verbose",
")",
"deep_features",
"=",
"self",
".",
"_extract_features",
"(",
"preprocessed_data",
",",
"verbose",
")",
"output",
"=",
"_tc",
".",
"SFrame",
"(",
"{",
"'deep features'",
":",
"deep_features",
",",
"'row id'",
":",
"row_ids",
"}",
")",
"output",
"=",
"output",
".",
"unstack",
"(",
"'deep features'",
")",
"max_row_id",
"=",
"len",
"(",
"audio_data",
")",
"missing_ids",
"=",
"set",
"(",
"range",
"(",
"max_row_id",
")",
")",
"-",
"set",
"(",
"output",
"[",
"'row id'",
"]",
".",
"unique",
"(",
")",
")",
"if",
"len",
"(",
"missing_ids",
")",
"!=",
"0",
":",
"empty_rows",
"=",
"_tc",
".",
"SFrame",
"(",
"{",
"'List of deep features'",
":",
"[",
"[",
"]",
"for",
"_",
"in",
"range",
"(",
"len",
"(",
"missing_ids",
")",
")",
"]",
",",
"'row id'",
":",
"missing_ids",
"}",
")",
"output",
"=",
"output",
".",
"append",
"(",
"empty_rows",
")",
"output",
"=",
"output",
".",
"sort",
"(",
"'row id'",
")",
"return",
"output",
"[",
"'List of deep features'",
"]"
] | Performs both audio preprocessing and VGGish deep feature extraction. | [
"Performs",
"both",
"audio",
"preprocessing",
"and",
"VGGish",
"deep",
"feature",
"extraction",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/sound_classifier/_audio_feature_extractor.py#L172-L190 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/sound_classifier/_audio_feature_extractor.py | VGGishFeatureExtractor.get_spec | def get_spec(self):
"""
Return the Core ML spec
"""
if _mac_ver() >= (10, 14):
return self.vggish_model.get_spec()
else:
vggish_model_file = VGGish()
coreml_model_path = vggish_model_file.get_model_path(format='coreml')
return MLModel(coreml_model_path).get_spec() | python | def get_spec(self):
"""
Return the Core ML spec
"""
if _mac_ver() >= (10, 14):
return self.vggish_model.get_spec()
else:
vggish_model_file = VGGish()
coreml_model_path = vggish_model_file.get_model_path(format='coreml')
return MLModel(coreml_model_path).get_spec() | [
"def",
"get_spec",
"(",
"self",
")",
":",
"if",
"_mac_ver",
"(",
")",
">=",
"(",
"10",
",",
"14",
")",
":",
"return",
"self",
".",
"vggish_model",
".",
"get_spec",
"(",
")",
"else",
":",
"vggish_model_file",
"=",
"VGGish",
"(",
")",
"coreml_model_path",
"=",
"vggish_model_file",
".",
"get_model_path",
"(",
"format",
"=",
"'coreml'",
")",
"return",
"MLModel",
"(",
"coreml_model_path",
")",
".",
"get_spec",
"(",
")"
] | Return the Core ML spec | [
"Return",
"the",
"Core",
"ML",
"spec"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/sound_classifier/_audio_feature_extractor.py#L192-L201 | train |
apple/turicreate | src/unity/python/turicreate/meta/asttools/mutators/remove_trivial.py | remove_trivial | def remove_trivial(root):
'''
Remove redundant statements.
The statement `a = 1` will be removed::
a = 1
a = 2
The statement `a = 1` will not be removed because `b` depends on it::
a = 1
b = a + 2
a = 2
:param root: ast node
'''
gen = GatherAssignments()
gen.visit(root)
to_remove = []
for symbol, assignments in gen.assign_id_map.items():
if len(assignments) < 2:
continue
for j in range(len(assignments) - 1):
i1 = root.body.index(assignments[j].root)
i2 = root.body.index(assignments[j + 1].root)
body = root.body[i1 + 1:i2]
grapher = GraphGen()
for stmnt in body:
grapher.visit(stmnt)
if symbol not in grapher.used:
to_remove.extend(assignments[j].assignments)
Pass = lambda node: _ast.Pass(lineno=node.lineno, col_offset=node.col_offset)
for old in to_remove:
replace_nodes(root, old, Pass(old)) | python | def remove_trivial(root):
'''
Remove redundant statements.
The statement `a = 1` will be removed::
a = 1
a = 2
The statement `a = 1` will not be removed because `b` depends on it::
a = 1
b = a + 2
a = 2
:param root: ast node
'''
gen = GatherAssignments()
gen.visit(root)
to_remove = []
for symbol, assignments in gen.assign_id_map.items():
if len(assignments) < 2:
continue
for j in range(len(assignments) - 1):
i1 = root.body.index(assignments[j].root)
i2 = root.body.index(assignments[j + 1].root)
body = root.body[i1 + 1:i2]
grapher = GraphGen()
for stmnt in body:
grapher.visit(stmnt)
if symbol not in grapher.used:
to_remove.extend(assignments[j].assignments)
Pass = lambda node: _ast.Pass(lineno=node.lineno, col_offset=node.col_offset)
for old in to_remove:
replace_nodes(root, old, Pass(old)) | [
"def",
"remove_trivial",
"(",
"root",
")",
":",
"gen",
"=",
"GatherAssignments",
"(",
")",
"gen",
".",
"visit",
"(",
"root",
")",
"to_remove",
"=",
"[",
"]",
"for",
"symbol",
",",
"assignments",
"in",
"gen",
".",
"assign_id_map",
".",
"items",
"(",
")",
":",
"if",
"len",
"(",
"assignments",
")",
"<",
"2",
":",
"continue",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"assignments",
")",
"-",
"1",
")",
":",
"i1",
"=",
"root",
".",
"body",
".",
"index",
"(",
"assignments",
"[",
"j",
"]",
".",
"root",
")",
"i2",
"=",
"root",
".",
"body",
".",
"index",
"(",
"assignments",
"[",
"j",
"+",
"1",
"]",
".",
"root",
")",
"body",
"=",
"root",
".",
"body",
"[",
"i1",
"+",
"1",
":",
"i2",
"]",
"grapher",
"=",
"GraphGen",
"(",
")",
"for",
"stmnt",
"in",
"body",
":",
"grapher",
".",
"visit",
"(",
"stmnt",
")",
"if",
"symbol",
"not",
"in",
"grapher",
".",
"used",
":",
"to_remove",
".",
"extend",
"(",
"assignments",
"[",
"j",
"]",
".",
"assignments",
")",
"Pass",
"=",
"lambda",
"node",
":",
"_ast",
".",
"Pass",
"(",
"lineno",
"=",
"node",
".",
"lineno",
",",
"col_offset",
"=",
"node",
".",
"col_offset",
")",
"for",
"old",
"in",
"to_remove",
":",
"replace_nodes",
"(",
"root",
",",
"old",
",",
"Pass",
"(",
"old",
")",
")"
] | Remove redundant statements.
The statement `a = 1` will be removed::
a = 1
a = 2
The statement `a = 1` will not be removed because `b` depends on it::
a = 1
b = a + 2
a = 2
:param root: ast node | [
"Remove",
"redundant",
"statements",
".",
"The",
"statement",
"a",
"=",
"1",
"will",
"be",
"removed",
"::",
"a",
"=",
"1",
"a",
"=",
"2"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/meta/asttools/mutators/remove_trivial.py#L78-L120 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/util/__init__.py | safe_isinstance | def safe_isinstance(value, types=None, class_names=None):
"""To prevent circular imports, this extends isinstance()
by checking also if `value` has a particular class name (or inherits from a
particular class name). This check is safe in that an AttributeError is not
raised in case `value` doesn't have a __class__ attribute.
"""
# inspect is being imported here because I seriously doubt
# that this function will be used outside of the type
# checking below.
import inspect
result = False
if types is not None:
result = result or isinstance(value, types)
if class_names is not None and not result:
# this doesn't work with inheritance, but normally
# either the class will already be imported within the module,
# or the class doesn't have any subclasses. For example: PropertySet
if isinstance(class_names, basestring):
class_names = [class_names]
# this is the part that makes it "safe".
try:
base_names = [class_.__name__ for class_ in inspect.getmro(value.__class__)]
for name in class_names:
if name in base_names:
return True
except AttributeError:
pass
return result | python | def safe_isinstance(value, types=None, class_names=None):
"""To prevent circular imports, this extends isinstance()
by checking also if `value` has a particular class name (or inherits from a
particular class name). This check is safe in that an AttributeError is not
raised in case `value` doesn't have a __class__ attribute.
"""
# inspect is being imported here because I seriously doubt
# that this function will be used outside of the type
# checking below.
import inspect
result = False
if types is not None:
result = result or isinstance(value, types)
if class_names is not None and not result:
# this doesn't work with inheritance, but normally
# either the class will already be imported within the module,
# or the class doesn't have any subclasses. For example: PropertySet
if isinstance(class_names, basestring):
class_names = [class_names]
# this is the part that makes it "safe".
try:
base_names = [class_.__name__ for class_ in inspect.getmro(value.__class__)]
for name in class_names:
if name in base_names:
return True
except AttributeError:
pass
return result | [
"def",
"safe_isinstance",
"(",
"value",
",",
"types",
"=",
"None",
",",
"class_names",
"=",
"None",
")",
":",
"# inspect is being imported here because I seriously doubt",
"# that this function will be used outside of the type",
"# checking below.",
"import",
"inspect",
"result",
"=",
"False",
"if",
"types",
"is",
"not",
"None",
":",
"result",
"=",
"result",
"or",
"isinstance",
"(",
"value",
",",
"types",
")",
"if",
"class_names",
"is",
"not",
"None",
"and",
"not",
"result",
":",
"# this doesn't work with inheritance, but normally",
"# either the class will already be imported within the module,",
"# or the class doesn't have any subclasses. For example: PropertySet",
"if",
"isinstance",
"(",
"class_names",
",",
"basestring",
")",
":",
"class_names",
"=",
"[",
"class_names",
"]",
"# this is the part that makes it \"safe\".",
"try",
":",
"base_names",
"=",
"[",
"class_",
".",
"__name__",
"for",
"class_",
"in",
"inspect",
".",
"getmro",
"(",
"value",
".",
"__class__",
")",
"]",
"for",
"name",
"in",
"class_names",
":",
"if",
"name",
"in",
"base_names",
":",
"return",
"True",
"except",
"AttributeError",
":",
"pass",
"return",
"result"
] | To prevent circular imports, this extends isinstance()
by checking also if `value` has a particular class name (or inherits from a
particular class name). This check is safe in that an AttributeError is not
raised in case `value` doesn't have a __class__ attribute. | [
"To",
"prevent",
"circular",
"imports",
"this",
"extends",
"isinstance",
"()",
"by",
"checking",
"also",
"if",
"value",
"has",
"a",
"particular",
"class",
"name",
"(",
"or",
"inherits",
"from",
"a",
"particular",
"class",
"name",
")",
".",
"This",
"check",
"is",
"safe",
"in",
"that",
"an",
"AttributeError",
"is",
"not",
"raised",
"in",
"case",
"value",
"doesn",
"t",
"have",
"a",
"__class__",
"attribute",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/__init__.py#L9-L36 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/util/__init__.py | value_to_jam | def value_to_jam(value, methods=False):
"""Makes a token to refer to a Python value inside Jam language code.
The token is merely a string that can be passed around in Jam code and
eventually passed back. For example, we might want to pass PropertySet
instance to a tag function and it might eventually call back
to virtual_target.add_suffix_and_prefix, passing the same instance.
For values that are classes, we'll also make class methods callable
from Jam.
Note that this is necessary to make a bit more of existing Jamfiles work.
This trick should not be used to much, or else the performance benefits of
Python port will be eaten.
"""
global __value_id
r = __python_to_jam.get(value, None)
if r:
return r
exported_name = '###_' + str(__value_id)
__value_id = __value_id + 1
__python_to_jam[value] = exported_name
__jam_to_python[exported_name] = value
if methods and type(value) == types.InstanceType:
for field_name in dir(value):
field = getattr(value, field_name)
if callable(field) and not field_name.startswith("__"):
bjam.import_rule("", exported_name + "." + field_name, field)
return exported_name | python | def value_to_jam(value, methods=False):
"""Makes a token to refer to a Python value inside Jam language code.
The token is merely a string that can be passed around in Jam code and
eventually passed back. For example, we might want to pass PropertySet
instance to a tag function and it might eventually call back
to virtual_target.add_suffix_and_prefix, passing the same instance.
For values that are classes, we'll also make class methods callable
from Jam.
Note that this is necessary to make a bit more of existing Jamfiles work.
This trick should not be used to much, or else the performance benefits of
Python port will be eaten.
"""
global __value_id
r = __python_to_jam.get(value, None)
if r:
return r
exported_name = '###_' + str(__value_id)
__value_id = __value_id + 1
__python_to_jam[value] = exported_name
__jam_to_python[exported_name] = value
if methods and type(value) == types.InstanceType:
for field_name in dir(value):
field = getattr(value, field_name)
if callable(field) and not field_name.startswith("__"):
bjam.import_rule("", exported_name + "." + field_name, field)
return exported_name | [
"def",
"value_to_jam",
"(",
"value",
",",
"methods",
"=",
"False",
")",
":",
"global",
"__value_id",
"r",
"=",
"__python_to_jam",
".",
"get",
"(",
"value",
",",
"None",
")",
"if",
"r",
":",
"return",
"r",
"exported_name",
"=",
"'###_'",
"+",
"str",
"(",
"__value_id",
")",
"__value_id",
"=",
"__value_id",
"+",
"1",
"__python_to_jam",
"[",
"value",
"]",
"=",
"exported_name",
"__jam_to_python",
"[",
"exported_name",
"]",
"=",
"value",
"if",
"methods",
"and",
"type",
"(",
"value",
")",
"==",
"types",
".",
"InstanceType",
":",
"for",
"field_name",
"in",
"dir",
"(",
"value",
")",
":",
"field",
"=",
"getattr",
"(",
"value",
",",
"field_name",
")",
"if",
"callable",
"(",
"field",
")",
"and",
"not",
"field_name",
".",
"startswith",
"(",
"\"__\"",
")",
":",
"bjam",
".",
"import_rule",
"(",
"\"\"",
",",
"exported_name",
"+",
"\".\"",
"+",
"field_name",
",",
"field",
")",
"return",
"exported_name"
] | Makes a token to refer to a Python value inside Jam language code.
The token is merely a string that can be passed around in Jam code and
eventually passed back. For example, we might want to pass PropertySet
instance to a tag function and it might eventually call back
to virtual_target.add_suffix_and_prefix, passing the same instance.
For values that are classes, we'll also make class methods callable
from Jam.
Note that this is necessary to make a bit more of existing Jamfiles work.
This trick should not be used to much, or else the performance benefits of
Python port will be eaten. | [
"Makes",
"a",
"token",
"to",
"refer",
"to",
"a",
"Python",
"value",
"inside",
"Jam",
"language",
"code",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/__init__.py#L228-L261 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/util/__init__.py | abbreviate_dashed | def abbreviate_dashed(s):
"""Abbreviates each part of string that is delimited by a '-'."""
r = []
for part in s.split('-'):
r.append(abbreviate(part))
return '-'.join(r) | python | def abbreviate_dashed(s):
"""Abbreviates each part of string that is delimited by a '-'."""
r = []
for part in s.split('-'):
r.append(abbreviate(part))
return '-'.join(r) | [
"def",
"abbreviate_dashed",
"(",
"s",
")",
":",
"r",
"=",
"[",
"]",
"for",
"part",
"in",
"s",
".",
"split",
"(",
"'-'",
")",
":",
"r",
".",
"append",
"(",
"abbreviate",
"(",
"part",
")",
")",
"return",
"'-'",
".",
"join",
"(",
"r",
")"
] | Abbreviates each part of string that is delimited by a '-'. | [
"Abbreviates",
"each",
"part",
"of",
"string",
"that",
"is",
"delimited",
"by",
"a",
"-",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/__init__.py#L281-L286 | train |
apple/turicreate | deps/src/boost_1_68_0/tools/build/src/util/__init__.py | abbreviate | def abbreviate(s):
"""Apply a set of standard transformations to string to produce an
abbreviation no more than 4 characters long.
"""
if not s:
return ''
# check the cache
if s in abbreviate.abbreviations:
return abbreviate.abbreviations[s]
# anything less than 4 characters doesn't need
# an abbreviation
if len(s) < 4:
# update cache
abbreviate.abbreviations[s] = s
return s
# save the first character in case it's a vowel
s1 = s[0]
s2 = s[1:]
if s.endswith('ing'):
# strip off the 'ing'
s2 = s2[:-3]
# reduce all doubled characters to one
s2 = ''.join(c for c, _ in groupby(s2))
# remove all vowels
s2 = s2.translate(None, "AEIOUaeiou")
# shorten remaining consonants to 4 characters
# and add the first char back to the front
s2 = s1 + s2[:4]
# update cache
abbreviate.abbreviations[s] = s2
return s2 | python | def abbreviate(s):
"""Apply a set of standard transformations to string to produce an
abbreviation no more than 4 characters long.
"""
if not s:
return ''
# check the cache
if s in abbreviate.abbreviations:
return abbreviate.abbreviations[s]
# anything less than 4 characters doesn't need
# an abbreviation
if len(s) < 4:
# update cache
abbreviate.abbreviations[s] = s
return s
# save the first character in case it's a vowel
s1 = s[0]
s2 = s[1:]
if s.endswith('ing'):
# strip off the 'ing'
s2 = s2[:-3]
# reduce all doubled characters to one
s2 = ''.join(c for c, _ in groupby(s2))
# remove all vowels
s2 = s2.translate(None, "AEIOUaeiou")
# shorten remaining consonants to 4 characters
# and add the first char back to the front
s2 = s1 + s2[:4]
# update cache
abbreviate.abbreviations[s] = s2
return s2 | [
"def",
"abbreviate",
"(",
"s",
")",
":",
"if",
"not",
"s",
":",
"return",
"''",
"# check the cache",
"if",
"s",
"in",
"abbreviate",
".",
"abbreviations",
":",
"return",
"abbreviate",
".",
"abbreviations",
"[",
"s",
"]",
"# anything less than 4 characters doesn't need",
"# an abbreviation",
"if",
"len",
"(",
"s",
")",
"<",
"4",
":",
"# update cache",
"abbreviate",
".",
"abbreviations",
"[",
"s",
"]",
"=",
"s",
"return",
"s",
"# save the first character in case it's a vowel",
"s1",
"=",
"s",
"[",
"0",
"]",
"s2",
"=",
"s",
"[",
"1",
":",
"]",
"if",
"s",
".",
"endswith",
"(",
"'ing'",
")",
":",
"# strip off the 'ing'",
"s2",
"=",
"s2",
"[",
":",
"-",
"3",
"]",
"# reduce all doubled characters to one",
"s2",
"=",
"''",
".",
"join",
"(",
"c",
"for",
"c",
",",
"_",
"in",
"groupby",
"(",
"s2",
")",
")",
"# remove all vowels",
"s2",
"=",
"s2",
".",
"translate",
"(",
"None",
",",
"\"AEIOUaeiou\"",
")",
"# shorten remaining consonants to 4 characters",
"# and add the first char back to the front",
"s2",
"=",
"s1",
"+",
"s2",
"[",
":",
"4",
"]",
"# update cache",
"abbreviate",
".",
"abbreviations",
"[",
"s",
"]",
"=",
"s2",
"return",
"s2"
] | Apply a set of standard transformations to string to produce an
abbreviation no more than 4 characters long. | [
"Apply",
"a",
"set",
"of",
"standard",
"transformations",
"to",
"string",
"to",
"produce",
"an",
"abbreviation",
"no",
"more",
"than",
"4",
"characters",
"long",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/util/__init__.py#L289-L319 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_decision_tree.py | Node.get_decision | def get_decision(self, child, is_missing = False):
"""
Get the decision from this node to a child node.
Parameters
----------
child: Node
A child node of this node.
Returns
-------
dict: A dictionary that describes how to get from this node to the
child node.
"""
# Child does exist and there is a path to the child.
value = self.value
feature = self.split_feature_column
index = self.split_feature_index
if not is_missing:
if self.left_id == child.node_id:
if self.node_type in ["float", "integer"]:
sign = "<"
else:
sign = "="
else:
if self.node_type in ["float", "integer"]:
sign = ">="
else:
sign = "!="
else:
sign = "missing"
value = None
return {
"node_id" : self.node_id,
"node_type" : self.node_type,
"feature" : feature,
"index" : index,
"sign" : sign,
"value" : value,
"child_id" : child.node_id,
"is_missing" : is_missing
} | python | def get_decision(self, child, is_missing = False):
"""
Get the decision from this node to a child node.
Parameters
----------
child: Node
A child node of this node.
Returns
-------
dict: A dictionary that describes how to get from this node to the
child node.
"""
# Child does exist and there is a path to the child.
value = self.value
feature = self.split_feature_column
index = self.split_feature_index
if not is_missing:
if self.left_id == child.node_id:
if self.node_type in ["float", "integer"]:
sign = "<"
else:
sign = "="
else:
if self.node_type in ["float", "integer"]:
sign = ">="
else:
sign = "!="
else:
sign = "missing"
value = None
return {
"node_id" : self.node_id,
"node_type" : self.node_type,
"feature" : feature,
"index" : index,
"sign" : sign,
"value" : value,
"child_id" : child.node_id,
"is_missing" : is_missing
} | [
"def",
"get_decision",
"(",
"self",
",",
"child",
",",
"is_missing",
"=",
"False",
")",
":",
"# Child does exist and there is a path to the child.",
"value",
"=",
"self",
".",
"value",
"feature",
"=",
"self",
".",
"split_feature_column",
"index",
"=",
"self",
".",
"split_feature_index",
"if",
"not",
"is_missing",
":",
"if",
"self",
".",
"left_id",
"==",
"child",
".",
"node_id",
":",
"if",
"self",
".",
"node_type",
"in",
"[",
"\"float\"",
",",
"\"integer\"",
"]",
":",
"sign",
"=",
"\"<\"",
"else",
":",
"sign",
"=",
"\"=\"",
"else",
":",
"if",
"self",
".",
"node_type",
"in",
"[",
"\"float\"",
",",
"\"integer\"",
"]",
":",
"sign",
"=",
"\">=\"",
"else",
":",
"sign",
"=",
"\"!=\"",
"else",
":",
"sign",
"=",
"\"missing\"",
"value",
"=",
"None",
"return",
"{",
"\"node_id\"",
":",
"self",
".",
"node_id",
",",
"\"node_type\"",
":",
"self",
".",
"node_type",
",",
"\"feature\"",
":",
"feature",
",",
"\"index\"",
":",
"index",
",",
"\"sign\"",
":",
"sign",
",",
"\"value\"",
":",
"value",
",",
"\"child_id\"",
":",
"child",
".",
"node_id",
",",
"\"is_missing\"",
":",
"is_missing",
"}"
] | Get the decision from this node to a child node.
Parameters
----------
child: Node
A child node of this node.
Returns
-------
dict: A dictionary that describes how to get from this node to the
child node. | [
"Get",
"the",
"decision",
"from",
"this",
"node",
"to",
"a",
"child",
"node",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_decision_tree.py#L80-L123 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_decision_tree.py | Node.to_dict | def to_dict(self):
"""
Return the node as a dictionary.
Returns
-------
dict: All the attributes of this node as a dictionary (minus the left
and right).
"""
out = {}
for key in self.__dict__.keys():
if key not in ['left', 'right', 'missing', 'parent']:
out[key] = self.__dict__[key]
return out | python | def to_dict(self):
"""
Return the node as a dictionary.
Returns
-------
dict: All the attributes of this node as a dictionary (minus the left
and right).
"""
out = {}
for key in self.__dict__.keys():
if key not in ['left', 'right', 'missing', 'parent']:
out[key] = self.__dict__[key]
return out | [
"def",
"to_dict",
"(",
"self",
")",
":",
"out",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"__dict__",
".",
"keys",
"(",
")",
":",
"if",
"key",
"not",
"in",
"[",
"'left'",
",",
"'right'",
",",
"'missing'",
",",
"'parent'",
"]",
":",
"out",
"[",
"key",
"]",
"=",
"self",
".",
"__dict__",
"[",
"key",
"]",
"return",
"out"
] | Return the node as a dictionary.
Returns
-------
dict: All the attributes of this node as a dictionary (minus the left
and right). | [
"Return",
"the",
"node",
"as",
"a",
"dictionary",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_decision_tree.py#L125-L138 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_decision_tree.py | DecisionTree.to_json | def to_json(self, root_id = 0, output = {}):
"""
Recursive function to dump this tree as a json blob.
Parameters
----------
root_id: Root id of the sub-tree
output: Carry over output from the previous sub-trees.
Returns
-------
dict: A tree in JSON format. Starts at the root node and recursively
represents each node in JSON.
- node_id : ID of the node.
- left_id : ID of left child (None if it doesn't exist).
- right_id : ID of right child (None if it doesn't exist).
- split_feature_column : Feature column on which a decision is made.
- split_feature_index : Feature index (within that column) on which the
decision is made.
- is_leaf : Is this node a leaf node?
- node_type : Node type (categorical, numerical, leaf etc.)
- value : Prediction (if leaf), decision split point
(if not leaf).
- left : JSON representation of the left node.
- right : JSON representation of the right node.
Examples
--------
.. sourcecode:: python
>>> tree.to_json() # Leaf node
{'is_leaf': False,
'left': {'is_leaf': True,
'left_id': None,
'node_id': 115,
'node_type': u'leaf',
'parent_id': 60,
'right_id': None,
'split_feature_column': None,
'split_feature_index': None,
'value': 0.436364},
'left_id': 115,
'node_id': 60,
'node_type': u'float',
'parent_id': 29,
'right': {'is_leaf': True,
'left_id': None,
'node_id': 116,
'node_type': u'leaf',
'parent_id': 60,
'right_id': None,
'split_feature_column': None,
'split_feature_index': None,
'value': -0.105882},
'right_id': 116,
'split_feature_column': 'Quantity_features_14',
'split_feature_index': 'count_sum',
'value': 22.5}
"""
_raise_error_if_not_of_type(root_id, [int,long], "root_id")
_numeric_param_check_range("root_id", root_id, 0, self.num_nodes - 1)
node = self.nodes[root_id]
output = node.to_dict()
if node.left_id is not None:
j = node.left_id
output['left'] = self.to_json(j, output)
if node.right_id is not None:
j = node.right_id
output['right'] = self.to_json(j, output)
return output | python | def to_json(self, root_id = 0, output = {}):
"""
Recursive function to dump this tree as a json blob.
Parameters
----------
root_id: Root id of the sub-tree
output: Carry over output from the previous sub-trees.
Returns
-------
dict: A tree in JSON format. Starts at the root node and recursively
represents each node in JSON.
- node_id : ID of the node.
- left_id : ID of left child (None if it doesn't exist).
- right_id : ID of right child (None if it doesn't exist).
- split_feature_column : Feature column on which a decision is made.
- split_feature_index : Feature index (within that column) on which the
decision is made.
- is_leaf : Is this node a leaf node?
- node_type : Node type (categorical, numerical, leaf etc.)
- value : Prediction (if leaf), decision split point
(if not leaf).
- left : JSON representation of the left node.
- right : JSON representation of the right node.
Examples
--------
.. sourcecode:: python
>>> tree.to_json() # Leaf node
{'is_leaf': False,
'left': {'is_leaf': True,
'left_id': None,
'node_id': 115,
'node_type': u'leaf',
'parent_id': 60,
'right_id': None,
'split_feature_column': None,
'split_feature_index': None,
'value': 0.436364},
'left_id': 115,
'node_id': 60,
'node_type': u'float',
'parent_id': 29,
'right': {'is_leaf': True,
'left_id': None,
'node_id': 116,
'node_type': u'leaf',
'parent_id': 60,
'right_id': None,
'split_feature_column': None,
'split_feature_index': None,
'value': -0.105882},
'right_id': 116,
'split_feature_column': 'Quantity_features_14',
'split_feature_index': 'count_sum',
'value': 22.5}
"""
_raise_error_if_not_of_type(root_id, [int,long], "root_id")
_numeric_param_check_range("root_id", root_id, 0, self.num_nodes - 1)
node = self.nodes[root_id]
output = node.to_dict()
if node.left_id is not None:
j = node.left_id
output['left'] = self.to_json(j, output)
if node.right_id is not None:
j = node.right_id
output['right'] = self.to_json(j, output)
return output | [
"def",
"to_json",
"(",
"self",
",",
"root_id",
"=",
"0",
",",
"output",
"=",
"{",
"}",
")",
":",
"_raise_error_if_not_of_type",
"(",
"root_id",
",",
"[",
"int",
",",
"long",
"]",
",",
"\"root_id\"",
")",
"_numeric_param_check_range",
"(",
"\"root_id\"",
",",
"root_id",
",",
"0",
",",
"self",
".",
"num_nodes",
"-",
"1",
")",
"node",
"=",
"self",
".",
"nodes",
"[",
"root_id",
"]",
"output",
"=",
"node",
".",
"to_dict",
"(",
")",
"if",
"node",
".",
"left_id",
"is",
"not",
"None",
":",
"j",
"=",
"node",
".",
"left_id",
"output",
"[",
"'left'",
"]",
"=",
"self",
".",
"to_json",
"(",
"j",
",",
"output",
")",
"if",
"node",
".",
"right_id",
"is",
"not",
"None",
":",
"j",
"=",
"node",
".",
"right_id",
"output",
"[",
"'right'",
"]",
"=",
"self",
".",
"to_json",
"(",
"j",
",",
"output",
")",
"return",
"output"
] | Recursive function to dump this tree as a json blob.
Parameters
----------
root_id: Root id of the sub-tree
output: Carry over output from the previous sub-trees.
Returns
-------
dict: A tree in JSON format. Starts at the root node and recursively
represents each node in JSON.
- node_id : ID of the node.
- left_id : ID of left child (None if it doesn't exist).
- right_id : ID of right child (None if it doesn't exist).
- split_feature_column : Feature column on which a decision is made.
- split_feature_index : Feature index (within that column) on which the
decision is made.
- is_leaf : Is this node a leaf node?
- node_type : Node type (categorical, numerical, leaf etc.)
- value : Prediction (if leaf), decision split point
(if not leaf).
- left : JSON representation of the left node.
- right : JSON representation of the right node.
Examples
--------
.. sourcecode:: python
>>> tree.to_json() # Leaf node
{'is_leaf': False,
'left': {'is_leaf': True,
'left_id': None,
'node_id': 115,
'node_type': u'leaf',
'parent_id': 60,
'right_id': None,
'split_feature_column': None,
'split_feature_index': None,
'value': 0.436364},
'left_id': 115,
'node_id': 60,
'node_type': u'float',
'parent_id': 29,
'right': {'is_leaf': True,
'left_id': None,
'node_id': 116,
'node_type': u'leaf',
'parent_id': 60,
'right_id': None,
'split_feature_column': None,
'split_feature_index': None,
'value': -0.105882},
'right_id': 116,
'split_feature_column': 'Quantity_features_14',
'split_feature_index': 'count_sum',
'value': 22.5} | [
"Recursive",
"function",
"to",
"dump",
"this",
"tree",
"as",
"a",
"json",
"blob",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_decision_tree.py#L300-L371 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_decision_tree.py | DecisionTree.get_prediction_score | def get_prediction_score(self, node_id):
"""
Return the prediction score (if leaf node) or None if its an
intermediate node.
Parameters
----------
node_id: id of the node to get the prediction value.
Returns
-------
float or None: returns float value of prediction if leaf node and None
if not.
Examples
--------
.. sourcecode:: python
>>> tree.get_prediction_score(120) # Leaf node
0.251092
>>> tree.get_prediction_score(120) # Not a leaf node
None
"""
_raise_error_if_not_of_type(node_id, [int,long], "node_id")
_numeric_param_check_range("node_id", node_id, 0, self.num_nodes - 1)
node = self.nodes[node_id]
return None if node.is_leaf is False else node.value | python | def get_prediction_score(self, node_id):
"""
Return the prediction score (if leaf node) or None if its an
intermediate node.
Parameters
----------
node_id: id of the node to get the prediction value.
Returns
-------
float or None: returns float value of prediction if leaf node and None
if not.
Examples
--------
.. sourcecode:: python
>>> tree.get_prediction_score(120) # Leaf node
0.251092
>>> tree.get_prediction_score(120) # Not a leaf node
None
"""
_raise_error_if_not_of_type(node_id, [int,long], "node_id")
_numeric_param_check_range("node_id", node_id, 0, self.num_nodes - 1)
node = self.nodes[node_id]
return None if node.is_leaf is False else node.value | [
"def",
"get_prediction_score",
"(",
"self",
",",
"node_id",
")",
":",
"_raise_error_if_not_of_type",
"(",
"node_id",
",",
"[",
"int",
",",
"long",
"]",
",",
"\"node_id\"",
")",
"_numeric_param_check_range",
"(",
"\"node_id\"",
",",
"node_id",
",",
"0",
",",
"self",
".",
"num_nodes",
"-",
"1",
")",
"node",
"=",
"self",
".",
"nodes",
"[",
"node_id",
"]",
"return",
"None",
"if",
"node",
".",
"is_leaf",
"is",
"False",
"else",
"node",
".",
"value"
] | Return the prediction score (if leaf node) or None if its an
intermediate node.
Parameters
----------
node_id: id of the node to get the prediction value.
Returns
-------
float or None: returns float value of prediction if leaf node and None
if not.
Examples
--------
.. sourcecode:: python
>>> tree.get_prediction_score(120) # Leaf node
0.251092
>>> tree.get_prediction_score(120) # Not a leaf node
None | [
"Return",
"the",
"prediction",
"score",
"(",
"if",
"leaf",
"node",
")",
"or",
"None",
"if",
"its",
"an",
"intermediate",
"node",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_decision_tree.py#L373-L401 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/_decision_tree.py | DecisionTree.get_prediction_path | def get_prediction_path(self, node_id, missing_id = []):
"""
Return the prediction path from this node to the parent node.
Parameters
----------
node_id : id of the node to get the prediction path.
missing_id : Additional info that contains nodes with missing features.
Returns
-------
list: The list of decisions (top to bottom) from the root to this node.
Examples
--------
.. sourcecode:: python
>>> tree.get_prediction_score(5) # Any node
[{'child_id': 2,
'feature': 'Quantity_features_90',
'index': 'sum_timegaplast_gap',
'node_id': 0,
'sign': '>',
'value': 53.5},
{'child_id': 5,
'feature': 'Quantity_features_90',
'index': 'sum_sum',
'node_id': 2,
'sign': '<=',
'value': 146.5}]
"""
_raise_error_if_not_of_type(node_id, [int,long], "node_id")
_numeric_param_check_range("node_id", node_id, 0, self.num_nodes - 1)
def _deduplicate_path(path):
s_nodes = {} # super_nodes
s_path = [] # paths of super nodes.
for node in path:
feature = node['feature']
index = node['index']
if (feature, index) not in s_nodes:
s_nodes[feature, index] = node
s_path.append(node)
else:
s_node = s_nodes[feature, index]
s_sign = s_node['sign']
sign = node['sign']
value = node['value']
# Supernode has no range.
if s_sign == "<":
if sign == ">=":
s_node["value"] = [value, s_node["value"]]
s_node["sign"] = "in"
elif sign == "<":
s_node["value"] = value
elif s_sign == ">=":
if sign == ">=":
s_node["value"] = value
elif sign == "<":
s_node["value"] = [s_node["value"], value]
s_node["sign"] = "in"
# Supernode has a range.
elif s_sign == "in":
if sign == ">=":
s_node["value"][0] = value
elif sign == "<":
s_node["value"][1] = value
# Return super node path.
return s_path
path = []
node = self.nodes[node_id]
while node.parent is not None:
parent = node.parent
is_missing = node.node_id in missing_id
path.insert(0, parent.get_decision(node, is_missing))
node = node.parent
return _deduplicate_path(path) | python | def get_prediction_path(self, node_id, missing_id = []):
"""
Return the prediction path from this node to the parent node.
Parameters
----------
node_id : id of the node to get the prediction path.
missing_id : Additional info that contains nodes with missing features.
Returns
-------
list: The list of decisions (top to bottom) from the root to this node.
Examples
--------
.. sourcecode:: python
>>> tree.get_prediction_score(5) # Any node
[{'child_id': 2,
'feature': 'Quantity_features_90',
'index': 'sum_timegaplast_gap',
'node_id': 0,
'sign': '>',
'value': 53.5},
{'child_id': 5,
'feature': 'Quantity_features_90',
'index': 'sum_sum',
'node_id': 2,
'sign': '<=',
'value': 146.5}]
"""
_raise_error_if_not_of_type(node_id, [int,long], "node_id")
_numeric_param_check_range("node_id", node_id, 0, self.num_nodes - 1)
def _deduplicate_path(path):
s_nodes = {} # super_nodes
s_path = [] # paths of super nodes.
for node in path:
feature = node['feature']
index = node['index']
if (feature, index) not in s_nodes:
s_nodes[feature, index] = node
s_path.append(node)
else:
s_node = s_nodes[feature, index]
s_sign = s_node['sign']
sign = node['sign']
value = node['value']
# Supernode has no range.
if s_sign == "<":
if sign == ">=":
s_node["value"] = [value, s_node["value"]]
s_node["sign"] = "in"
elif sign == "<":
s_node["value"] = value
elif s_sign == ">=":
if sign == ">=":
s_node["value"] = value
elif sign == "<":
s_node["value"] = [s_node["value"], value]
s_node["sign"] = "in"
# Supernode has a range.
elif s_sign == "in":
if sign == ">=":
s_node["value"][0] = value
elif sign == "<":
s_node["value"][1] = value
# Return super node path.
return s_path
path = []
node = self.nodes[node_id]
while node.parent is not None:
parent = node.parent
is_missing = node.node_id in missing_id
path.insert(0, parent.get_decision(node, is_missing))
node = node.parent
return _deduplicate_path(path) | [
"def",
"get_prediction_path",
"(",
"self",
",",
"node_id",
",",
"missing_id",
"=",
"[",
"]",
")",
":",
"_raise_error_if_not_of_type",
"(",
"node_id",
",",
"[",
"int",
",",
"long",
"]",
",",
"\"node_id\"",
")",
"_numeric_param_check_range",
"(",
"\"node_id\"",
",",
"node_id",
",",
"0",
",",
"self",
".",
"num_nodes",
"-",
"1",
")",
"def",
"_deduplicate_path",
"(",
"path",
")",
":",
"s_nodes",
"=",
"{",
"}",
"# super_nodes",
"s_path",
"=",
"[",
"]",
"# paths of super nodes.",
"for",
"node",
"in",
"path",
":",
"feature",
"=",
"node",
"[",
"'feature'",
"]",
"index",
"=",
"node",
"[",
"'index'",
"]",
"if",
"(",
"feature",
",",
"index",
")",
"not",
"in",
"s_nodes",
":",
"s_nodes",
"[",
"feature",
",",
"index",
"]",
"=",
"node",
"s_path",
".",
"append",
"(",
"node",
")",
"else",
":",
"s_node",
"=",
"s_nodes",
"[",
"feature",
",",
"index",
"]",
"s_sign",
"=",
"s_node",
"[",
"'sign'",
"]",
"sign",
"=",
"node",
"[",
"'sign'",
"]",
"value",
"=",
"node",
"[",
"'value'",
"]",
"# Supernode has no range.",
"if",
"s_sign",
"==",
"\"<\"",
":",
"if",
"sign",
"==",
"\">=\"",
":",
"s_node",
"[",
"\"value\"",
"]",
"=",
"[",
"value",
",",
"s_node",
"[",
"\"value\"",
"]",
"]",
"s_node",
"[",
"\"sign\"",
"]",
"=",
"\"in\"",
"elif",
"sign",
"==",
"\"<\"",
":",
"s_node",
"[",
"\"value\"",
"]",
"=",
"value",
"elif",
"s_sign",
"==",
"\">=\"",
":",
"if",
"sign",
"==",
"\">=\"",
":",
"s_node",
"[",
"\"value\"",
"]",
"=",
"value",
"elif",
"sign",
"==",
"\"<\"",
":",
"s_node",
"[",
"\"value\"",
"]",
"=",
"[",
"s_node",
"[",
"\"value\"",
"]",
",",
"value",
"]",
"s_node",
"[",
"\"sign\"",
"]",
"=",
"\"in\"",
"# Supernode has a range.",
"elif",
"s_sign",
"==",
"\"in\"",
":",
"if",
"sign",
"==",
"\">=\"",
":",
"s_node",
"[",
"\"value\"",
"]",
"[",
"0",
"]",
"=",
"value",
"elif",
"sign",
"==",
"\"<\"",
":",
"s_node",
"[",
"\"value\"",
"]",
"[",
"1",
"]",
"=",
"value",
"# Return super node path.",
"return",
"s_path",
"path",
"=",
"[",
"]",
"node",
"=",
"self",
".",
"nodes",
"[",
"node_id",
"]",
"while",
"node",
".",
"parent",
"is",
"not",
"None",
":",
"parent",
"=",
"node",
".",
"parent",
"is_missing",
"=",
"node",
".",
"node_id",
"in",
"missing_id",
"path",
".",
"insert",
"(",
"0",
",",
"parent",
".",
"get_decision",
"(",
"node",
",",
"is_missing",
")",
")",
"node",
"=",
"node",
".",
"parent",
"return",
"_deduplicate_path",
"(",
"path",
")"
] | Return the prediction path from this node to the parent node.
Parameters
----------
node_id : id of the node to get the prediction path.
missing_id : Additional info that contains nodes with missing features.
Returns
-------
list: The list of decisions (top to bottom) from the root to this node.
Examples
--------
.. sourcecode:: python
>>> tree.get_prediction_score(5) # Any node
[{'child_id': 2,
'feature': 'Quantity_features_90',
'index': 'sum_timegaplast_gap',
'node_id': 0,
'sign': '>',
'value': 53.5},
{'child_id': 5,
'feature': 'Quantity_features_90',
'index': 'sum_sum',
'node_id': 2,
'sign': '<=',
'value': 146.5}] | [
"Return",
"the",
"prediction",
"path",
"from",
"this",
"node",
"to",
"the",
"parent",
"node",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_decision_tree.py#L403-L484 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/graph_analytics/label_propagation.py | create | def create(graph, label_field,
threshold=1e-3,
weight_field='',
self_weight=1.0,
undirected=False,
max_iterations=None,
_single_precision=False,
_distributed='auto',
verbose=True):
"""
Given a weighted graph with observed class labels of a subset of vertices,
infer the label probability for the unobserved vertices using the
"label propagation" algorithm.
The algorithm iteratively updates the label probability of current vertex
as a weighted sum of label probability of self and the neighboring vertices
until converge. See
:class:`turicreate.label_propagation.LabelPropagationModel` for the details
of the algorithm.
Notes: label propagation works well with small number of labels, i.e. binary
labels, or less than 1000 classes. The toolkit will throw error
if the number of classes exceeds the maximum value (1000).
Parameters
----------
graph : SGraph
The graph on which to compute the label propagation.
label_field: str
Vertex field storing the initial vertex labels. The values in
must be [0, num_classes). None values indicate unobserved vertex labels.
threshold : float, optional
Threshold for convergence, measured in the average L2 norm
(the sum of squared values) of the delta of each vertex's
label probability vector.
max_iterations: int, optional
The max number of iterations to run. Default is unlimited.
If set, the algorithm terminates when either max_iterations
or convergence threshold is reached.
weight_field: str, optional
Vertex field for edge weight. If empty, all edges are assumed
to have unit weight.
self_weight: float, optional
The weight for self edge.
undirected: bool, optional
If true, treat each edge as undirected, and propagates label in
both directions.
_single_precision : bool, optional
If true, running label propagation in single precision. The resulting
probability values may less accurate, but should run faster
and use less memory.
_distributed : distributed environment, internal
verbose : bool, optional
If True, print progress updates.
Returns
-------
out : LabelPropagationModel
References
----------
- Zhu, X., & Ghahramani, Z. (2002). `Learning from labeled and unlabeled data
with label propagation <http://www.cs.cmu.edu/~zhuxj/pub/CMU-CALD-02-107.pdf>`_.
Examples
--------
If given an :class:`~turicreate.SGraph` ``g``, we can create
a :class:`~turicreate.label_propagation.LabelPropagationModel` as follows:
>>> g = turicreate.load_sgraph('http://snap.stanford.edu/data/email-Enron.txt.gz',
... format='snap')
# Initialize random classes for a subset of vertices
# Leave the unobserved vertices with None label.
>>> import random
>>> def init_label(vid):
... x = random.random()
... if x < 0.2:
... return 0
... elif x > 0.9:
... return 1
... else:
... return None
>>> g.vertices['label'] = g.vertices['__id'].apply(init_label, int)
>>> m = turicreate.label_propagation.create(g, label_field='label')
We can obtain for each vertex the predicted label and the probability of
each label in the graph ``g`` using:
>>> labels = m['labels'] # SFrame
>>> labels
+------+-------+-----------------+-------------------+----------------+
| __id | label | predicted_label | P0 | P1 |
+------+-------+-----------------+-------------------+----------------+
| 5 | 1 | 1 | 0.0 | 1.0 |
| 7 | None | 0 | 0.8213214997 | 0.1786785003 |
| 8 | None | 1 | 5.96046447754e-08 | 0.999999940395 |
| 10 | None | 0 | 0.534984718273 | 0.465015281727 |
| 27 | None | 0 | 0.752801638549 | 0.247198361451 |
| 29 | None | 1 | 5.96046447754e-08 | 0.999999940395 |
| 33 | None | 1 | 5.96046447754e-08 | 0.999999940395 |
| 47 | 0 | 0 | 1.0 | 0.0 |
| 50 | None | 0 | 0.788279032657 | 0.211720967343 |
| 52 | None | 0 | 0.666666666667 | 0.333333333333 |
+------+-------+-----------------+-------------------+----------------+
[36692 rows x 5 columns]
See Also
--------
LabelPropagationModel
"""
from turicreate._cython.cy_server import QuietProgress
_raise_error_if_not_of_type(label_field, str)
_raise_error_if_not_of_type(weight_field, str)
if not isinstance(graph, _SGraph):
raise TypeError('graph input must be a SGraph object.')
if graph.vertices[label_field].dtype != int:
raise TypeError('label_field %s must be integer typed.' % label_field)
opts = {'label_field': label_field,
'threshold': threshold,
'weight_field': weight_field,
'self_weight': self_weight,
'undirected': undirected,
'max_iterations': max_iterations,
'single_precision': _single_precision,
'graph': graph.__proxy__}
with QuietProgress(verbose):
params = _tc.extensions._toolkits.graph.label_propagation.create(opts)
model = params['model']
return LabelPropagationModel(model) | python | def create(graph, label_field,
threshold=1e-3,
weight_field='',
self_weight=1.0,
undirected=False,
max_iterations=None,
_single_precision=False,
_distributed='auto',
verbose=True):
"""
Given a weighted graph with observed class labels of a subset of vertices,
infer the label probability for the unobserved vertices using the
"label propagation" algorithm.
The algorithm iteratively updates the label probability of current vertex
as a weighted sum of label probability of self and the neighboring vertices
until converge. See
:class:`turicreate.label_propagation.LabelPropagationModel` for the details
of the algorithm.
Notes: label propagation works well with small number of labels, i.e. binary
labels, or less than 1000 classes. The toolkit will throw error
if the number of classes exceeds the maximum value (1000).
Parameters
----------
graph : SGraph
The graph on which to compute the label propagation.
label_field: str
Vertex field storing the initial vertex labels. The values in
must be [0, num_classes). None values indicate unobserved vertex labels.
threshold : float, optional
Threshold for convergence, measured in the average L2 norm
(the sum of squared values) of the delta of each vertex's
label probability vector.
max_iterations: int, optional
The max number of iterations to run. Default is unlimited.
If set, the algorithm terminates when either max_iterations
or convergence threshold is reached.
weight_field: str, optional
Vertex field for edge weight. If empty, all edges are assumed
to have unit weight.
self_weight: float, optional
The weight for self edge.
undirected: bool, optional
If true, treat each edge as undirected, and propagates label in
both directions.
_single_precision : bool, optional
If true, running label propagation in single precision. The resulting
probability values may less accurate, but should run faster
and use less memory.
_distributed : distributed environment, internal
verbose : bool, optional
If True, print progress updates.
Returns
-------
out : LabelPropagationModel
References
----------
- Zhu, X., & Ghahramani, Z. (2002). `Learning from labeled and unlabeled data
with label propagation <http://www.cs.cmu.edu/~zhuxj/pub/CMU-CALD-02-107.pdf>`_.
Examples
--------
If given an :class:`~turicreate.SGraph` ``g``, we can create
a :class:`~turicreate.label_propagation.LabelPropagationModel` as follows:
>>> g = turicreate.load_sgraph('http://snap.stanford.edu/data/email-Enron.txt.gz',
... format='snap')
# Initialize random classes for a subset of vertices
# Leave the unobserved vertices with None label.
>>> import random
>>> def init_label(vid):
... x = random.random()
... if x < 0.2:
... return 0
... elif x > 0.9:
... return 1
... else:
... return None
>>> g.vertices['label'] = g.vertices['__id'].apply(init_label, int)
>>> m = turicreate.label_propagation.create(g, label_field='label')
We can obtain for each vertex the predicted label and the probability of
each label in the graph ``g`` using:
>>> labels = m['labels'] # SFrame
>>> labels
+------+-------+-----------------+-------------------+----------------+
| __id | label | predicted_label | P0 | P1 |
+------+-------+-----------------+-------------------+----------------+
| 5 | 1 | 1 | 0.0 | 1.0 |
| 7 | None | 0 | 0.8213214997 | 0.1786785003 |
| 8 | None | 1 | 5.96046447754e-08 | 0.999999940395 |
| 10 | None | 0 | 0.534984718273 | 0.465015281727 |
| 27 | None | 0 | 0.752801638549 | 0.247198361451 |
| 29 | None | 1 | 5.96046447754e-08 | 0.999999940395 |
| 33 | None | 1 | 5.96046447754e-08 | 0.999999940395 |
| 47 | 0 | 0 | 1.0 | 0.0 |
| 50 | None | 0 | 0.788279032657 | 0.211720967343 |
| 52 | None | 0 | 0.666666666667 | 0.333333333333 |
+------+-------+-----------------+-------------------+----------------+
[36692 rows x 5 columns]
See Also
--------
LabelPropagationModel
"""
from turicreate._cython.cy_server import QuietProgress
_raise_error_if_not_of_type(label_field, str)
_raise_error_if_not_of_type(weight_field, str)
if not isinstance(graph, _SGraph):
raise TypeError('graph input must be a SGraph object.')
if graph.vertices[label_field].dtype != int:
raise TypeError('label_field %s must be integer typed.' % label_field)
opts = {'label_field': label_field,
'threshold': threshold,
'weight_field': weight_field,
'self_weight': self_weight,
'undirected': undirected,
'max_iterations': max_iterations,
'single_precision': _single_precision,
'graph': graph.__proxy__}
with QuietProgress(verbose):
params = _tc.extensions._toolkits.graph.label_propagation.create(opts)
model = params['model']
return LabelPropagationModel(model) | [
"def",
"create",
"(",
"graph",
",",
"label_field",
",",
"threshold",
"=",
"1e-3",
",",
"weight_field",
"=",
"''",
",",
"self_weight",
"=",
"1.0",
",",
"undirected",
"=",
"False",
",",
"max_iterations",
"=",
"None",
",",
"_single_precision",
"=",
"False",
",",
"_distributed",
"=",
"'auto'",
",",
"verbose",
"=",
"True",
")",
":",
"from",
"turicreate",
".",
"_cython",
".",
"cy_server",
"import",
"QuietProgress",
"_raise_error_if_not_of_type",
"(",
"label_field",
",",
"str",
")",
"_raise_error_if_not_of_type",
"(",
"weight_field",
",",
"str",
")",
"if",
"not",
"isinstance",
"(",
"graph",
",",
"_SGraph",
")",
":",
"raise",
"TypeError",
"(",
"'graph input must be a SGraph object.'",
")",
"if",
"graph",
".",
"vertices",
"[",
"label_field",
"]",
".",
"dtype",
"!=",
"int",
":",
"raise",
"TypeError",
"(",
"'label_field %s must be integer typed.'",
"%",
"label_field",
")",
"opts",
"=",
"{",
"'label_field'",
":",
"label_field",
",",
"'threshold'",
":",
"threshold",
",",
"'weight_field'",
":",
"weight_field",
",",
"'self_weight'",
":",
"self_weight",
",",
"'undirected'",
":",
"undirected",
",",
"'max_iterations'",
":",
"max_iterations",
",",
"'single_precision'",
":",
"_single_precision",
",",
"'graph'",
":",
"graph",
".",
"__proxy__",
"}",
"with",
"QuietProgress",
"(",
"verbose",
")",
":",
"params",
"=",
"_tc",
".",
"extensions",
".",
"_toolkits",
".",
"graph",
".",
"label_propagation",
".",
"create",
"(",
"opts",
")",
"model",
"=",
"params",
"[",
"'model'",
"]",
"return",
"LabelPropagationModel",
"(",
"model",
")"
] | Given a weighted graph with observed class labels of a subset of vertices,
infer the label probability for the unobserved vertices using the
"label propagation" algorithm.
The algorithm iteratively updates the label probability of current vertex
as a weighted sum of label probability of self and the neighboring vertices
until converge. See
:class:`turicreate.label_propagation.LabelPropagationModel` for the details
of the algorithm.
Notes: label propagation works well with small number of labels, i.e. binary
labels, or less than 1000 classes. The toolkit will throw error
if the number of classes exceeds the maximum value (1000).
Parameters
----------
graph : SGraph
The graph on which to compute the label propagation.
label_field: str
Vertex field storing the initial vertex labels. The values in
must be [0, num_classes). None values indicate unobserved vertex labels.
threshold : float, optional
Threshold for convergence, measured in the average L2 norm
(the sum of squared values) of the delta of each vertex's
label probability vector.
max_iterations: int, optional
The max number of iterations to run. Default is unlimited.
If set, the algorithm terminates when either max_iterations
or convergence threshold is reached.
weight_field: str, optional
Vertex field for edge weight. If empty, all edges are assumed
to have unit weight.
self_weight: float, optional
The weight for self edge.
undirected: bool, optional
If true, treat each edge as undirected, and propagates label in
both directions.
_single_precision : bool, optional
If true, running label propagation in single precision. The resulting
probability values may less accurate, but should run faster
and use less memory.
_distributed : distributed environment, internal
verbose : bool, optional
If True, print progress updates.
Returns
-------
out : LabelPropagationModel
References
----------
- Zhu, X., & Ghahramani, Z. (2002). `Learning from labeled and unlabeled data
with label propagation <http://www.cs.cmu.edu/~zhuxj/pub/CMU-CALD-02-107.pdf>`_.
Examples
--------
If given an :class:`~turicreate.SGraph` ``g``, we can create
a :class:`~turicreate.label_propagation.LabelPropagationModel` as follows:
>>> g = turicreate.load_sgraph('http://snap.stanford.edu/data/email-Enron.txt.gz',
... format='snap')
# Initialize random classes for a subset of vertices
# Leave the unobserved vertices with None label.
>>> import random
>>> def init_label(vid):
... x = random.random()
... if x < 0.2:
... return 0
... elif x > 0.9:
... return 1
... else:
... return None
>>> g.vertices['label'] = g.vertices['__id'].apply(init_label, int)
>>> m = turicreate.label_propagation.create(g, label_field='label')
We can obtain for each vertex the predicted label and the probability of
each label in the graph ``g`` using:
>>> labels = m['labels'] # SFrame
>>> labels
+------+-------+-----------------+-------------------+----------------+
| __id | label | predicted_label | P0 | P1 |
+------+-------+-----------------+-------------------+----------------+
| 5 | 1 | 1 | 0.0 | 1.0 |
| 7 | None | 0 | 0.8213214997 | 0.1786785003 |
| 8 | None | 1 | 5.96046447754e-08 | 0.999999940395 |
| 10 | None | 0 | 0.534984718273 | 0.465015281727 |
| 27 | None | 0 | 0.752801638549 | 0.247198361451 |
| 29 | None | 1 | 5.96046447754e-08 | 0.999999940395 |
| 33 | None | 1 | 5.96046447754e-08 | 0.999999940395 |
| 47 | 0 | 0 | 1.0 | 0.0 |
| 50 | None | 0 | 0.788279032657 | 0.211720967343 |
| 52 | None | 0 | 0.666666666667 | 0.333333333333 |
+------+-------+-----------------+-------------------+----------------+
[36692 rows x 5 columns]
See Also
--------
LabelPropagationModel | [
"Given",
"a",
"weighted",
"graph",
"with",
"observed",
"class",
"labels",
"of",
"a",
"subset",
"of",
"vertices",
"infer",
"the",
"label",
"probability",
"for",
"the",
"unobserved",
"vertices",
"using",
"the",
"label",
"propagation",
"algorithm",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/graph_analytics/label_propagation.py#L131-L274 | train |
apple/turicreate | src/unity/python/turicreate/_gl_pickle.py | _is_not_pickle_safe_gl_model_class | def _is_not_pickle_safe_gl_model_class(obj_class):
"""
Check if a Turi create model is pickle safe.
The function does it by checking that _CustomModel is the base class.
Parameters
----------
obj_class : Class to be checked.
Returns
----------
True if the GLC class is a model and is pickle safe.
"""
if issubclass(obj_class, _toolkits._model.CustomModel):
return not obj_class._is_gl_pickle_safe()
return False | python | def _is_not_pickle_safe_gl_model_class(obj_class):
"""
Check if a Turi create model is pickle safe.
The function does it by checking that _CustomModel is the base class.
Parameters
----------
obj_class : Class to be checked.
Returns
----------
True if the GLC class is a model and is pickle safe.
"""
if issubclass(obj_class, _toolkits._model.CustomModel):
return not obj_class._is_gl_pickle_safe()
return False | [
"def",
"_is_not_pickle_safe_gl_model_class",
"(",
"obj_class",
")",
":",
"if",
"issubclass",
"(",
"obj_class",
",",
"_toolkits",
".",
"_model",
".",
"CustomModel",
")",
":",
"return",
"not",
"obj_class",
".",
"_is_gl_pickle_safe",
"(",
")",
"return",
"False"
] | Check if a Turi create model is pickle safe.
The function does it by checking that _CustomModel is the base class.
Parameters
----------
obj_class : Class to be checked.
Returns
----------
True if the GLC class is a model and is pickle safe. | [
"Check",
"if",
"a",
"Turi",
"create",
"model",
"is",
"pickle",
"safe",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/_gl_pickle.py#L33-L50 | train |
apple/turicreate | src/unity/python/turicreate/_gl_pickle.py | _is_not_pickle_safe_gl_class | def _is_not_pickle_safe_gl_class(obj_class):
"""
Check if class is a Turi create model.
The function does it by checking the method resolution order (MRO) of the
class and verifies that _Model is the base class.
Parameters
----------
obj_class : Class to be checked.
Returns
----------
True if the class is a GLC Model.
"""
gl_ds = [_SFrame, _SArray, _SGraph]
# Object is GLC-DS or GLC-Model
return (obj_class in gl_ds) or _is_not_pickle_safe_gl_model_class(obj_class) | python | def _is_not_pickle_safe_gl_class(obj_class):
"""
Check if class is a Turi create model.
The function does it by checking the method resolution order (MRO) of the
class and verifies that _Model is the base class.
Parameters
----------
obj_class : Class to be checked.
Returns
----------
True if the class is a GLC Model.
"""
gl_ds = [_SFrame, _SArray, _SGraph]
# Object is GLC-DS or GLC-Model
return (obj_class in gl_ds) or _is_not_pickle_safe_gl_model_class(obj_class) | [
"def",
"_is_not_pickle_safe_gl_class",
"(",
"obj_class",
")",
":",
"gl_ds",
"=",
"[",
"_SFrame",
",",
"_SArray",
",",
"_SGraph",
"]",
"# Object is GLC-DS or GLC-Model",
"return",
"(",
"obj_class",
"in",
"gl_ds",
")",
"or",
"_is_not_pickle_safe_gl_model_class",
"(",
"obj_class",
")"
] | Check if class is a Turi create model.
The function does it by checking the method resolution order (MRO) of the
class and verifies that _Model is the base class.
Parameters
----------
obj_class : Class to be checked.
Returns
----------
True if the class is a GLC Model. | [
"Check",
"if",
"class",
"is",
"a",
"Turi",
"create",
"model",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/_gl_pickle.py#L52-L71 | train |
apple/turicreate | src/unity/python/turicreate/_gl_pickle.py | _get_gl_class_type | def _get_gl_class_type(obj_class):
"""
Internal util to get the type of the GLC class. The pickle file stores
this name so that it knows how to construct the object on unpickling.
Parameters
----------
obj_class : Class which has to be categorized.
Returns
----------
A class type for the pickle file to save.
"""
if obj_class == _SFrame:
return "SFrame"
elif obj_class == _SGraph:
return "SGraph"
elif obj_class == _SArray:
return "SArray"
elif _is_not_pickle_safe_gl_model_class(obj_class):
return "Model"
else:
return None | python | def _get_gl_class_type(obj_class):
"""
Internal util to get the type of the GLC class. The pickle file stores
this name so that it knows how to construct the object on unpickling.
Parameters
----------
obj_class : Class which has to be categorized.
Returns
----------
A class type for the pickle file to save.
"""
if obj_class == _SFrame:
return "SFrame"
elif obj_class == _SGraph:
return "SGraph"
elif obj_class == _SArray:
return "SArray"
elif _is_not_pickle_safe_gl_model_class(obj_class):
return "Model"
else:
return None | [
"def",
"_get_gl_class_type",
"(",
"obj_class",
")",
":",
"if",
"obj_class",
"==",
"_SFrame",
":",
"return",
"\"SFrame\"",
"elif",
"obj_class",
"==",
"_SGraph",
":",
"return",
"\"SGraph\"",
"elif",
"obj_class",
"==",
"_SArray",
":",
"return",
"\"SArray\"",
"elif",
"_is_not_pickle_safe_gl_model_class",
"(",
"obj_class",
")",
":",
"return",
"\"Model\"",
"else",
":",
"return",
"None"
] | Internal util to get the type of the GLC class. The pickle file stores
this name so that it knows how to construct the object on unpickling.
Parameters
----------
obj_class : Class which has to be categorized.
Returns
----------
A class type for the pickle file to save. | [
"Internal",
"util",
"to",
"get",
"the",
"type",
"of",
"the",
"GLC",
"class",
".",
"The",
"pickle",
"file",
"stores",
"this",
"name",
"so",
"that",
"it",
"knows",
"how",
"to",
"construct",
"the",
"object",
"on",
"unpickling",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/_gl_pickle.py#L73-L97 | train |
apple/turicreate | src/unity/python/turicreate/_gl_pickle.py | _get_gl_object_from_persistent_id | def _get_gl_object_from_persistent_id(type_tag, gl_archive_abs_path):
"""
Internal util to get a GLC object from a persistent ID in the pickle file.
Parameters
----------
type_tag : The name of the glc class as saved in the GLC pickler.
gl_archive_abs_path: An absolute path to the GLC archive where the
object was saved.
Returns
----------
The GLC object.
"""
if type_tag == "SFrame":
obj = _SFrame(gl_archive_abs_path)
elif type_tag == "SGraph":
obj = _load_graph(gl_archive_abs_path)
elif type_tag == "SArray":
obj = _SArray(gl_archive_abs_path)
elif type_tag == "Model":
from . import load_model as _load_model
obj = _load_model(gl_archive_abs_path)
else:
raise _pickle.UnpicklingError("Turi pickling Error: Unsupported object."
" Only SFrames, SGraphs, SArrays, and Models are supported.")
return obj | python | def _get_gl_object_from_persistent_id(type_tag, gl_archive_abs_path):
"""
Internal util to get a GLC object from a persistent ID in the pickle file.
Parameters
----------
type_tag : The name of the glc class as saved in the GLC pickler.
gl_archive_abs_path: An absolute path to the GLC archive where the
object was saved.
Returns
----------
The GLC object.
"""
if type_tag == "SFrame":
obj = _SFrame(gl_archive_abs_path)
elif type_tag == "SGraph":
obj = _load_graph(gl_archive_abs_path)
elif type_tag == "SArray":
obj = _SArray(gl_archive_abs_path)
elif type_tag == "Model":
from . import load_model as _load_model
obj = _load_model(gl_archive_abs_path)
else:
raise _pickle.UnpicklingError("Turi pickling Error: Unsupported object."
" Only SFrames, SGraphs, SArrays, and Models are supported.")
return obj | [
"def",
"_get_gl_object_from_persistent_id",
"(",
"type_tag",
",",
"gl_archive_abs_path",
")",
":",
"if",
"type_tag",
"==",
"\"SFrame\"",
":",
"obj",
"=",
"_SFrame",
"(",
"gl_archive_abs_path",
")",
"elif",
"type_tag",
"==",
"\"SGraph\"",
":",
"obj",
"=",
"_load_graph",
"(",
"gl_archive_abs_path",
")",
"elif",
"type_tag",
"==",
"\"SArray\"",
":",
"obj",
"=",
"_SArray",
"(",
"gl_archive_abs_path",
")",
"elif",
"type_tag",
"==",
"\"Model\"",
":",
"from",
".",
"import",
"load_model",
"as",
"_load_model",
"obj",
"=",
"_load_model",
"(",
"gl_archive_abs_path",
")",
"else",
":",
"raise",
"_pickle",
".",
"UnpicklingError",
"(",
"\"Turi pickling Error: Unsupported object.\"",
"\" Only SFrames, SGraphs, SArrays, and Models are supported.\"",
")",
"return",
"obj"
] | Internal util to get a GLC object from a persistent ID in the pickle file.
Parameters
----------
type_tag : The name of the glc class as saved in the GLC pickler.
gl_archive_abs_path: An absolute path to the GLC archive where the
object was saved.
Returns
----------
The GLC object. | [
"Internal",
"util",
"to",
"get",
"a",
"GLC",
"object",
"from",
"a",
"persistent",
"ID",
"in",
"the",
"pickle",
"file",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/_gl_pickle.py#L99-L127 | train |
apple/turicreate | src/unity/python/turicreate/_gl_pickle.py | GLPickler.persistent_id | def persistent_id(self, obj):
"""
Provide a persistent ID for "saving" GLC objects by reference. Return
None for all non GLC objects.
Parameters
----------
obj: Name of the object whose persistent ID is extracted.
Returns
--------
None if the object is not a GLC object. (ClassName, relative path)
if the object is a GLC object.
Notes
-----
Borrowed from pickle docs (https://docs.python.org/2/library/_pickle.html)
For the benefit of object persistence, the pickle module supports the
notion of a reference to an object outside the pickled data stream.
To pickle objects that have an external persistent id, the pickler must
have a custom persistent_id() method that takes an object as an argument and
returns either None or the persistent id for that object.
For GLC objects, the persistent_id is merely a relative file path (within
the ZIP archive) to the GLC archive where the GLC object is saved. For
example:
(SFrame, 'sframe-save-path')
(SGraph, 'sgraph-save-path')
(Model, 'model-save-path')
"""
# Get the class of the object (if it can be done)
obj_class = None if not hasattr(obj, '__class__') else obj.__class__
if obj_class is None:
return None
# If the object is a GLC class.
if _is_not_pickle_safe_gl_class(obj_class):
if (id(obj) in self.gl_object_memo):
# has already been pickled
return (None, None, id(obj))
else:
# Save the location of the GLC object's archive to the pickle file.
relative_filename = str(_uuid.uuid4())
filename = _os.path.join(self.gl_temp_storage_path, relative_filename)
self.mark_for_delete -= set([filename])
# Save the GLC object
obj.save(filename)
# Memoize.
self.gl_object_memo.add(id(obj))
# Return the tuple (class_name, relative_filename) in archive.
return (_get_gl_class_type(obj.__class__), relative_filename, id(obj))
# Not a GLC object. Default to cloud pickle
else:
return None | python | def persistent_id(self, obj):
"""
Provide a persistent ID for "saving" GLC objects by reference. Return
None for all non GLC objects.
Parameters
----------
obj: Name of the object whose persistent ID is extracted.
Returns
--------
None if the object is not a GLC object. (ClassName, relative path)
if the object is a GLC object.
Notes
-----
Borrowed from pickle docs (https://docs.python.org/2/library/_pickle.html)
For the benefit of object persistence, the pickle module supports the
notion of a reference to an object outside the pickled data stream.
To pickle objects that have an external persistent id, the pickler must
have a custom persistent_id() method that takes an object as an argument and
returns either None or the persistent id for that object.
For GLC objects, the persistent_id is merely a relative file path (within
the ZIP archive) to the GLC archive where the GLC object is saved. For
example:
(SFrame, 'sframe-save-path')
(SGraph, 'sgraph-save-path')
(Model, 'model-save-path')
"""
# Get the class of the object (if it can be done)
obj_class = None if not hasattr(obj, '__class__') else obj.__class__
if obj_class is None:
return None
# If the object is a GLC class.
if _is_not_pickle_safe_gl_class(obj_class):
if (id(obj) in self.gl_object_memo):
# has already been pickled
return (None, None, id(obj))
else:
# Save the location of the GLC object's archive to the pickle file.
relative_filename = str(_uuid.uuid4())
filename = _os.path.join(self.gl_temp_storage_path, relative_filename)
self.mark_for_delete -= set([filename])
# Save the GLC object
obj.save(filename)
# Memoize.
self.gl_object_memo.add(id(obj))
# Return the tuple (class_name, relative_filename) in archive.
return (_get_gl_class_type(obj.__class__), relative_filename, id(obj))
# Not a GLC object. Default to cloud pickle
else:
return None | [
"def",
"persistent_id",
"(",
"self",
",",
"obj",
")",
":",
"# Get the class of the object (if it can be done)",
"obj_class",
"=",
"None",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"'__class__'",
")",
"else",
"obj",
".",
"__class__",
"if",
"obj_class",
"is",
"None",
":",
"return",
"None",
"# If the object is a GLC class.",
"if",
"_is_not_pickle_safe_gl_class",
"(",
"obj_class",
")",
":",
"if",
"(",
"id",
"(",
"obj",
")",
"in",
"self",
".",
"gl_object_memo",
")",
":",
"# has already been pickled",
"return",
"(",
"None",
",",
"None",
",",
"id",
"(",
"obj",
")",
")",
"else",
":",
"# Save the location of the GLC object's archive to the pickle file.",
"relative_filename",
"=",
"str",
"(",
"_uuid",
".",
"uuid4",
"(",
")",
")",
"filename",
"=",
"_os",
".",
"path",
".",
"join",
"(",
"self",
".",
"gl_temp_storage_path",
",",
"relative_filename",
")",
"self",
".",
"mark_for_delete",
"-=",
"set",
"(",
"[",
"filename",
"]",
")",
"# Save the GLC object",
"obj",
".",
"save",
"(",
"filename",
")",
"# Memoize.",
"self",
".",
"gl_object_memo",
".",
"add",
"(",
"id",
"(",
"obj",
")",
")",
"# Return the tuple (class_name, relative_filename) in archive.",
"return",
"(",
"_get_gl_class_type",
"(",
"obj",
".",
"__class__",
")",
",",
"relative_filename",
",",
"id",
"(",
"obj",
")",
")",
"# Not a GLC object. Default to cloud pickle",
"else",
":",
"return",
"None"
] | Provide a persistent ID for "saving" GLC objects by reference. Return
None for all non GLC objects.
Parameters
----------
obj: Name of the object whose persistent ID is extracted.
Returns
--------
None if the object is not a GLC object. (ClassName, relative path)
if the object is a GLC object.
Notes
-----
Borrowed from pickle docs (https://docs.python.org/2/library/_pickle.html)
For the benefit of object persistence, the pickle module supports the
notion of a reference to an object outside the pickled data stream.
To pickle objects that have an external persistent id, the pickler must
have a custom persistent_id() method that takes an object as an argument and
returns either None or the persistent id for that object.
For GLC objects, the persistent_id is merely a relative file path (within
the ZIP archive) to the GLC archive where the GLC object is saved. For
example:
(SFrame, 'sframe-save-path')
(SGraph, 'sgraph-save-path')
(Model, 'model-save-path') | [
"Provide",
"a",
"persistent",
"ID",
"for",
"saving",
"GLC",
"objects",
"by",
"reference",
".",
"Return",
"None",
"for",
"all",
"non",
"GLC",
"objects",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/_gl_pickle.py#L287-L351 | train |
apple/turicreate | src/unity/python/turicreate/_gl_pickle.py | GLPickler.close | def close(self):
"""
Close the pickle file, and the zip archive file. The single zip archive
file can now be shipped around to be loaded by the unpickler.
"""
if self.file is None:
return
# Close the pickle file.
self.file.close()
self.file = None
for f in self.mark_for_delete:
error = [False]
def register_error(*args):
error[0] = True
_shutil.rmtree(f, onerror = register_error)
if error[0]:
_atexit.register(_shutil.rmtree, f, ignore_errors=True) | python | def close(self):
"""
Close the pickle file, and the zip archive file. The single zip archive
file can now be shipped around to be loaded by the unpickler.
"""
if self.file is None:
return
# Close the pickle file.
self.file.close()
self.file = None
for f in self.mark_for_delete:
error = [False]
def register_error(*args):
error[0] = True
_shutil.rmtree(f, onerror = register_error)
if error[0]:
_atexit.register(_shutil.rmtree, f, ignore_errors=True) | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"file",
"is",
"None",
":",
"return",
"# Close the pickle file.",
"self",
".",
"file",
".",
"close",
"(",
")",
"self",
".",
"file",
"=",
"None",
"for",
"f",
"in",
"self",
".",
"mark_for_delete",
":",
"error",
"=",
"[",
"False",
"]",
"def",
"register_error",
"(",
"*",
"args",
")",
":",
"error",
"[",
"0",
"]",
"=",
"True",
"_shutil",
".",
"rmtree",
"(",
"f",
",",
"onerror",
"=",
"register_error",
")",
"if",
"error",
"[",
"0",
"]",
":",
"_atexit",
".",
"register",
"(",
"_shutil",
".",
"rmtree",
",",
"f",
",",
"ignore_errors",
"=",
"True",
")"
] | Close the pickle file, and the zip archive file. The single zip archive
file can now be shipped around to be loaded by the unpickler. | [
"Close",
"the",
"pickle",
"file",
"and",
"the",
"zip",
"archive",
"file",
".",
"The",
"single",
"zip",
"archive",
"file",
"can",
"now",
"be",
"shipped",
"around",
"to",
"be",
"loaded",
"by",
"the",
"unpickler",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/_gl_pickle.py#L353-L374 | train |
apple/turicreate | src/unity/python/turicreate/_gl_pickle.py | GLUnpickler.persistent_load | def persistent_load(self, pid):
"""
Reconstruct a GLC object using the persistent ID.
This method should not be used externally. It is required by the unpickler super class.
Parameters
----------
pid : The persistent ID used in pickle file to save the GLC object.
Returns
----------
The GLC object.
"""
if len(pid) == 2:
# Pre GLC-1.3 release behavior, without memorization
type_tag, filename = pid
abs_path = _os.path.join(self.gl_temp_storage_path, filename)
return _get_gl_object_from_persistent_id(type_tag, abs_path)
else:
# Post GLC-1.3 release behavior, with memorization
type_tag, filename, object_id = pid
if object_id in self.gl_object_memo:
return self.gl_object_memo[object_id]
else:
abs_path = _os.path.join(self.gl_temp_storage_path, filename)
obj = _get_gl_object_from_persistent_id(type_tag, abs_path)
self.gl_object_memo[object_id] = obj
return obj | python | def persistent_load(self, pid):
"""
Reconstruct a GLC object using the persistent ID.
This method should not be used externally. It is required by the unpickler super class.
Parameters
----------
pid : The persistent ID used in pickle file to save the GLC object.
Returns
----------
The GLC object.
"""
if len(pid) == 2:
# Pre GLC-1.3 release behavior, without memorization
type_tag, filename = pid
abs_path = _os.path.join(self.gl_temp_storage_path, filename)
return _get_gl_object_from_persistent_id(type_tag, abs_path)
else:
# Post GLC-1.3 release behavior, with memorization
type_tag, filename, object_id = pid
if object_id in self.gl_object_memo:
return self.gl_object_memo[object_id]
else:
abs_path = _os.path.join(self.gl_temp_storage_path, filename)
obj = _get_gl_object_from_persistent_id(type_tag, abs_path)
self.gl_object_memo[object_id] = obj
return obj | [
"def",
"persistent_load",
"(",
"self",
",",
"pid",
")",
":",
"if",
"len",
"(",
"pid",
")",
"==",
"2",
":",
"# Pre GLC-1.3 release behavior, without memorization",
"type_tag",
",",
"filename",
"=",
"pid",
"abs_path",
"=",
"_os",
".",
"path",
".",
"join",
"(",
"self",
".",
"gl_temp_storage_path",
",",
"filename",
")",
"return",
"_get_gl_object_from_persistent_id",
"(",
"type_tag",
",",
"abs_path",
")",
"else",
":",
"# Post GLC-1.3 release behavior, with memorization",
"type_tag",
",",
"filename",
",",
"object_id",
"=",
"pid",
"if",
"object_id",
"in",
"self",
".",
"gl_object_memo",
":",
"return",
"self",
".",
"gl_object_memo",
"[",
"object_id",
"]",
"else",
":",
"abs_path",
"=",
"_os",
".",
"path",
".",
"join",
"(",
"self",
".",
"gl_temp_storage_path",
",",
"filename",
")",
"obj",
"=",
"_get_gl_object_from_persistent_id",
"(",
"type_tag",
",",
"abs_path",
")",
"self",
".",
"gl_object_memo",
"[",
"object_id",
"]",
"=",
"obj",
"return",
"obj"
] | Reconstruct a GLC object using the persistent ID.
This method should not be used externally. It is required by the unpickler super class.
Parameters
----------
pid : The persistent ID used in pickle file to save the GLC object.
Returns
----------
The GLC object. | [
"Reconstruct",
"a",
"GLC",
"object",
"using",
"the",
"persistent",
"ID",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/_gl_pickle.py#L472-L500 | train |
apple/turicreate | src/unity/python/turicreate/_gl_pickle.py | GLUnpickler.close | def close(self):
"""
Clean up files that were created.
"""
if self.file:
self.file.close()
self.file = None
# If temp_file is a folder, we do not remove it because we may
# still need it after the unpickler is disposed
if self.tmp_file and _os.path.isfile(self.tmp_file):
_os.remove(self.tmp_file)
self.tmp_file = None | python | def close(self):
"""
Clean up files that were created.
"""
if self.file:
self.file.close()
self.file = None
# If temp_file is a folder, we do not remove it because we may
# still need it after the unpickler is disposed
if self.tmp_file and _os.path.isfile(self.tmp_file):
_os.remove(self.tmp_file)
self.tmp_file = None | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"file",
":",
"self",
".",
"file",
".",
"close",
"(",
")",
"self",
".",
"file",
"=",
"None",
"# If temp_file is a folder, we do not remove it because we may",
"# still need it after the unpickler is disposed",
"if",
"self",
".",
"tmp_file",
"and",
"_os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"tmp_file",
")",
":",
"_os",
".",
"remove",
"(",
"self",
".",
"tmp_file",
")",
"self",
".",
"tmp_file",
"=",
"None"
] | Clean up files that were created. | [
"Clean",
"up",
"files",
"that",
"were",
"created",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/_gl_pickle.py#L502-L514 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_converter.py | convert | def convert(sk_obj, input_features = None,
output_feature_names = None):
"""
Convert scikit-learn pipeline, classifier, or regressor to Core ML format.
Parameters
----------
sk_obj: model | [model] of scikit-learn format.
Scikit learn model(s) to convert to a Core ML format.
The input model may be a single scikit learn model, a scikit learn
pipeline model, or a list of scikit learn models.
Currently supported scikit learn models are:
- Linear and Logistic Regression
- LinearSVC and LinearSVR
- SVC and SVR
- NuSVC and NuSVR
- Gradient Boosting Classifier and Regressor
- Decision Tree Classifier and Regressor
- Random Forest Classifier and Regressor
- Normalizer
- Imputer
- Standard Scaler
- DictVectorizer
- One Hot Encoder
The input model, or the last model in a pipeline or list of models,
determines whether this is exposed as a Transformer, Regressor,
or Classifier.
Note that there may not be a one-to-one correspondence between scikit
learn models and which Core ML models are used to represent them. For
example, many scikit learn models are embedded in a pipeline to handle
processing of input features.
input_features: str | dict | list
Optional name(s) that can be given to the inputs of the scikit-learn
model. Defaults to 'input'.
Input features can be specified in a number of forms.
- Single string: In this case, the input is assumed to be a single
array, with the number of dimensions set using num_dimensions.
- List of strings: In this case, the overall input dimensions to the
scikit-learn model is assumed to be the length of the list. If
neighboring names are identical, they are assumed to be an input
array of that length. For example:
["a", "b", "c"]
resolves to
[("a", Double), ("b", Double), ("c", Double)].
And:
["a", "a", "b"]
resolves to
[("a", Array(2)), ("b", Double)].
- Dictionary: Where the keys are the names and the indices or ranges of
feature indices.
In this case, it's presented as a mapping from keys to indices or
ranges of contiguous indices. For example,
{"a" : 0, "b" : [2,3], "c" : 1}
Resolves to
[("a", Double), ("c", Double), ("b", Array(2))].
Note that the ordering is determined by the indices.
- List of tuples of the form `(name, datatype)`. Here, `name` is the
name of the exposed feature, and `datatype` is an instance of
`String`, `Double`, `Int64`, `Array`, or `Dictionary`.
output_feature_names: string or list of strings
Optional name(s) that can be given to the inputs of the scikit-learn
model.
The output_feature_names is interpreted according to the model type:
- If the scikit-learn model is a transformer, it is the name of the
array feature output by the final sequence of the transformer
(defaults to "output").
- If it is a classifier, it should be a 2-tuple of names giving the top
class prediction and the array of scores for each class (defaults to
"classLabel" and "classScores").
- If it is a regressor, it should give the name of the prediction value
(defaults to "prediction").
Returns
-------
model:MLModel
Returns an MLModel instance representing a Core ML model.
Examples
--------
.. sourcecode:: python
>>> from sklearn.linear_model import LinearRegression
>>> import pandas as pd
# Load data
>>> data = pd.read_csv('houses.csv')
# Train a model
>>> model = LinearRegression()
>>> model.fit(data[["bedroom", "bath", "size"]], data["price"])
# Convert and save the scikit-learn model
>>> import coremltools
>>> coreml_model = coremltools.converters.sklearn.convert(model,
["bedroom", "bath", "size"],
"price")
>>> coreml_model.save('HousePricer.mlmodel')
"""
# This function is just a thin wrapper around the internal converter so
# that sklearn isn't actually imported unless this function is called
from ...models import MLModel
# NOTE: Providing user-defined class labels will be enabled when
# several issues with the ordering of the classes are worked out. For now,
# to use custom class labels, directly import the internal function below.
from ._converter_internal import _convert_sklearn_model
spec = _convert_sklearn_model(
sk_obj, input_features, output_feature_names, class_labels = None)
return MLModel(spec) | python | def convert(sk_obj, input_features = None,
output_feature_names = None):
"""
Convert scikit-learn pipeline, classifier, or regressor to Core ML format.
Parameters
----------
sk_obj: model | [model] of scikit-learn format.
Scikit learn model(s) to convert to a Core ML format.
The input model may be a single scikit learn model, a scikit learn
pipeline model, or a list of scikit learn models.
Currently supported scikit learn models are:
- Linear and Logistic Regression
- LinearSVC and LinearSVR
- SVC and SVR
- NuSVC and NuSVR
- Gradient Boosting Classifier and Regressor
- Decision Tree Classifier and Regressor
- Random Forest Classifier and Regressor
- Normalizer
- Imputer
- Standard Scaler
- DictVectorizer
- One Hot Encoder
The input model, or the last model in a pipeline or list of models,
determines whether this is exposed as a Transformer, Regressor,
or Classifier.
Note that there may not be a one-to-one correspondence between scikit
learn models and which Core ML models are used to represent them. For
example, many scikit learn models are embedded in a pipeline to handle
processing of input features.
input_features: str | dict | list
Optional name(s) that can be given to the inputs of the scikit-learn
model. Defaults to 'input'.
Input features can be specified in a number of forms.
- Single string: In this case, the input is assumed to be a single
array, with the number of dimensions set using num_dimensions.
- List of strings: In this case, the overall input dimensions to the
scikit-learn model is assumed to be the length of the list. If
neighboring names are identical, they are assumed to be an input
array of that length. For example:
["a", "b", "c"]
resolves to
[("a", Double), ("b", Double), ("c", Double)].
And:
["a", "a", "b"]
resolves to
[("a", Array(2)), ("b", Double)].
- Dictionary: Where the keys are the names and the indices or ranges of
feature indices.
In this case, it's presented as a mapping from keys to indices or
ranges of contiguous indices. For example,
{"a" : 0, "b" : [2,3], "c" : 1}
Resolves to
[("a", Double), ("c", Double), ("b", Array(2))].
Note that the ordering is determined by the indices.
- List of tuples of the form `(name, datatype)`. Here, `name` is the
name of the exposed feature, and `datatype` is an instance of
`String`, `Double`, `Int64`, `Array`, or `Dictionary`.
output_feature_names: string or list of strings
Optional name(s) that can be given to the inputs of the scikit-learn
model.
The output_feature_names is interpreted according to the model type:
- If the scikit-learn model is a transformer, it is the name of the
array feature output by the final sequence of the transformer
(defaults to "output").
- If it is a classifier, it should be a 2-tuple of names giving the top
class prediction and the array of scores for each class (defaults to
"classLabel" and "classScores").
- If it is a regressor, it should give the name of the prediction value
(defaults to "prediction").
Returns
-------
model:MLModel
Returns an MLModel instance representing a Core ML model.
Examples
--------
.. sourcecode:: python
>>> from sklearn.linear_model import LinearRegression
>>> import pandas as pd
# Load data
>>> data = pd.read_csv('houses.csv')
# Train a model
>>> model = LinearRegression()
>>> model.fit(data[["bedroom", "bath", "size"]], data["price"])
# Convert and save the scikit-learn model
>>> import coremltools
>>> coreml_model = coremltools.converters.sklearn.convert(model,
["bedroom", "bath", "size"],
"price")
>>> coreml_model.save('HousePricer.mlmodel')
"""
# This function is just a thin wrapper around the internal converter so
# that sklearn isn't actually imported unless this function is called
from ...models import MLModel
# NOTE: Providing user-defined class labels will be enabled when
# several issues with the ordering of the classes are worked out. For now,
# to use custom class labels, directly import the internal function below.
from ._converter_internal import _convert_sklearn_model
spec = _convert_sklearn_model(
sk_obj, input_features, output_feature_names, class_labels = None)
return MLModel(spec) | [
"def",
"convert",
"(",
"sk_obj",
",",
"input_features",
"=",
"None",
",",
"output_feature_names",
"=",
"None",
")",
":",
"# This function is just a thin wrapper around the internal converter so",
"# that sklearn isn't actually imported unless this function is called",
"from",
".",
".",
".",
"models",
"import",
"MLModel",
"# NOTE: Providing user-defined class labels will be enabled when",
"# several issues with the ordering of the classes are worked out. For now,",
"# to use custom class labels, directly import the internal function below.",
"from",
".",
"_converter_internal",
"import",
"_convert_sklearn_model",
"spec",
"=",
"_convert_sklearn_model",
"(",
"sk_obj",
",",
"input_features",
",",
"output_feature_names",
",",
"class_labels",
"=",
"None",
")",
"return",
"MLModel",
"(",
"spec",
")"
] | Convert scikit-learn pipeline, classifier, or regressor to Core ML format.
Parameters
----------
sk_obj: model | [model] of scikit-learn format.
Scikit learn model(s) to convert to a Core ML format.
The input model may be a single scikit learn model, a scikit learn
pipeline model, or a list of scikit learn models.
Currently supported scikit learn models are:
- Linear and Logistic Regression
- LinearSVC and LinearSVR
- SVC and SVR
- NuSVC and NuSVR
- Gradient Boosting Classifier and Regressor
- Decision Tree Classifier and Regressor
- Random Forest Classifier and Regressor
- Normalizer
- Imputer
- Standard Scaler
- DictVectorizer
- One Hot Encoder
The input model, or the last model in a pipeline or list of models,
determines whether this is exposed as a Transformer, Regressor,
or Classifier.
Note that there may not be a one-to-one correspondence between scikit
learn models and which Core ML models are used to represent them. For
example, many scikit learn models are embedded in a pipeline to handle
processing of input features.
input_features: str | dict | list
Optional name(s) that can be given to the inputs of the scikit-learn
model. Defaults to 'input'.
Input features can be specified in a number of forms.
- Single string: In this case, the input is assumed to be a single
array, with the number of dimensions set using num_dimensions.
- List of strings: In this case, the overall input dimensions to the
scikit-learn model is assumed to be the length of the list. If
neighboring names are identical, they are assumed to be an input
array of that length. For example:
["a", "b", "c"]
resolves to
[("a", Double), ("b", Double), ("c", Double)].
And:
["a", "a", "b"]
resolves to
[("a", Array(2)), ("b", Double)].
- Dictionary: Where the keys are the names and the indices or ranges of
feature indices.
In this case, it's presented as a mapping from keys to indices or
ranges of contiguous indices. For example,
{"a" : 0, "b" : [2,3], "c" : 1}
Resolves to
[("a", Double), ("c", Double), ("b", Array(2))].
Note that the ordering is determined by the indices.
- List of tuples of the form `(name, datatype)`. Here, `name` is the
name of the exposed feature, and `datatype` is an instance of
`String`, `Double`, `Int64`, `Array`, or `Dictionary`.
output_feature_names: string or list of strings
Optional name(s) that can be given to the inputs of the scikit-learn
model.
The output_feature_names is interpreted according to the model type:
- If the scikit-learn model is a transformer, it is the name of the
array feature output by the final sequence of the transformer
(defaults to "output").
- If it is a classifier, it should be a 2-tuple of names giving the top
class prediction and the array of scores for each class (defaults to
"classLabel" and "classScores").
- If it is a regressor, it should give the name of the prediction value
(defaults to "prediction").
Returns
-------
model:MLModel
Returns an MLModel instance representing a Core ML model.
Examples
--------
.. sourcecode:: python
>>> from sklearn.linear_model import LinearRegression
>>> import pandas as pd
# Load data
>>> data = pd.read_csv('houses.csv')
# Train a model
>>> model = LinearRegression()
>>> model.fit(data[["bedroom", "bath", "size"]], data["price"])
# Convert and save the scikit-learn model
>>> import coremltools
>>> coreml_model = coremltools.converters.sklearn.convert(model,
["bedroom", "bath", "size"],
"price")
>>> coreml_model.save('HousePricer.mlmodel') | [
"Convert",
"scikit",
"-",
"learn",
"pipeline",
"classifier",
"or",
"regressor",
"to",
"Core",
"ML",
"format",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/sklearn/_converter.py#L10-L148 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/reflection.py | ParseMessage | def ParseMessage(descriptor, byte_str):
"""Generate a new Message instance from this Descriptor and a byte string.
Args:
descriptor: Protobuf Descriptor object
byte_str: Serialized protocol buffer byte string
Returns:
Newly created protobuf Message object.
"""
result_class = MakeClass(descriptor)
new_msg = result_class()
new_msg.ParseFromString(byte_str)
return new_msg | python | def ParseMessage(descriptor, byte_str):
"""Generate a new Message instance from this Descriptor and a byte string.
Args:
descriptor: Protobuf Descriptor object
byte_str: Serialized protocol buffer byte string
Returns:
Newly created protobuf Message object.
"""
result_class = MakeClass(descriptor)
new_msg = result_class()
new_msg.ParseFromString(byte_str)
return new_msg | [
"def",
"ParseMessage",
"(",
"descriptor",
",",
"byte_str",
")",
":",
"result_class",
"=",
"MakeClass",
"(",
"descriptor",
")",
"new_msg",
"=",
"result_class",
"(",
")",
"new_msg",
".",
"ParseFromString",
"(",
"byte_str",
")",
"return",
"new_msg"
] | Generate a new Message instance from this Descriptor and a byte string.
Args:
descriptor: Protobuf Descriptor object
byte_str: Serialized protocol buffer byte string
Returns:
Newly created protobuf Message object. | [
"Generate",
"a",
"new",
"Message",
"instance",
"from",
"this",
"Descriptor",
"and",
"a",
"byte",
"string",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/reflection.py#L67-L80 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/reflection.py | MakeClass | def MakeClass(descriptor):
"""Construct a class object for a protobuf described by descriptor.
Composite descriptors are handled by defining the new class as a member of the
parent class, recursing as deep as necessary.
This is the dynamic equivalent to:
class Parent(message.Message):
__metaclass__ = GeneratedProtocolMessageType
DESCRIPTOR = descriptor
class Child(message.Message):
__metaclass__ = GeneratedProtocolMessageType
DESCRIPTOR = descriptor.nested_types[0]
Sample usage:
file_descriptor = descriptor_pb2.FileDescriptorProto()
file_descriptor.ParseFromString(proto2_string)
msg_descriptor = descriptor.MakeDescriptor(file_descriptor.message_type[0])
msg_class = reflection.MakeClass(msg_descriptor)
msg = msg_class()
Args:
descriptor: A descriptor.Descriptor object describing the protobuf.
Returns:
The Message class object described by the descriptor.
"""
if descriptor in MESSAGE_CLASS_CACHE:
return MESSAGE_CLASS_CACHE[descriptor]
attributes = {}
for name, nested_type in descriptor.nested_types_by_name.items():
attributes[name] = MakeClass(nested_type)
attributes[GeneratedProtocolMessageType._DESCRIPTOR_KEY] = descriptor
result = GeneratedProtocolMessageType(
str(descriptor.name), (message.Message,), attributes)
MESSAGE_CLASS_CACHE[descriptor] = result
return result | python | def MakeClass(descriptor):
"""Construct a class object for a protobuf described by descriptor.
Composite descriptors are handled by defining the new class as a member of the
parent class, recursing as deep as necessary.
This is the dynamic equivalent to:
class Parent(message.Message):
__metaclass__ = GeneratedProtocolMessageType
DESCRIPTOR = descriptor
class Child(message.Message):
__metaclass__ = GeneratedProtocolMessageType
DESCRIPTOR = descriptor.nested_types[0]
Sample usage:
file_descriptor = descriptor_pb2.FileDescriptorProto()
file_descriptor.ParseFromString(proto2_string)
msg_descriptor = descriptor.MakeDescriptor(file_descriptor.message_type[0])
msg_class = reflection.MakeClass(msg_descriptor)
msg = msg_class()
Args:
descriptor: A descriptor.Descriptor object describing the protobuf.
Returns:
The Message class object described by the descriptor.
"""
if descriptor in MESSAGE_CLASS_CACHE:
return MESSAGE_CLASS_CACHE[descriptor]
attributes = {}
for name, nested_type in descriptor.nested_types_by_name.items():
attributes[name] = MakeClass(nested_type)
attributes[GeneratedProtocolMessageType._DESCRIPTOR_KEY] = descriptor
result = GeneratedProtocolMessageType(
str(descriptor.name), (message.Message,), attributes)
MESSAGE_CLASS_CACHE[descriptor] = result
return result | [
"def",
"MakeClass",
"(",
"descriptor",
")",
":",
"if",
"descriptor",
"in",
"MESSAGE_CLASS_CACHE",
":",
"return",
"MESSAGE_CLASS_CACHE",
"[",
"descriptor",
"]",
"attributes",
"=",
"{",
"}",
"for",
"name",
",",
"nested_type",
"in",
"descriptor",
".",
"nested_types_by_name",
".",
"items",
"(",
")",
":",
"attributes",
"[",
"name",
"]",
"=",
"MakeClass",
"(",
"nested_type",
")",
"attributes",
"[",
"GeneratedProtocolMessageType",
".",
"_DESCRIPTOR_KEY",
"]",
"=",
"descriptor",
"result",
"=",
"GeneratedProtocolMessageType",
"(",
"str",
"(",
"descriptor",
".",
"name",
")",
",",
"(",
"message",
".",
"Message",
",",
")",
",",
"attributes",
")",
"MESSAGE_CLASS_CACHE",
"[",
"descriptor",
"]",
"=",
"result",
"return",
"result"
] | Construct a class object for a protobuf described by descriptor.
Composite descriptors are handled by defining the new class as a member of the
parent class, recursing as deep as necessary.
This is the dynamic equivalent to:
class Parent(message.Message):
__metaclass__ = GeneratedProtocolMessageType
DESCRIPTOR = descriptor
class Child(message.Message):
__metaclass__ = GeneratedProtocolMessageType
DESCRIPTOR = descriptor.nested_types[0]
Sample usage:
file_descriptor = descriptor_pb2.FileDescriptorProto()
file_descriptor.ParseFromString(proto2_string)
msg_descriptor = descriptor.MakeDescriptor(file_descriptor.message_type[0])
msg_class = reflection.MakeClass(msg_descriptor)
msg = msg_class()
Args:
descriptor: A descriptor.Descriptor object describing the protobuf.
Returns:
The Message class object described by the descriptor. | [
"Construct",
"a",
"class",
"object",
"for",
"a",
"protobuf",
"described",
"by",
"descriptor",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/reflection.py#L83-L121 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/image_analysis/image_analysis.py | load_images | def load_images(url, format='auto', with_path=True, recursive=True, ignore_failure=True, random_order=False):
"""
Loads images from a directory. JPEG and PNG images are supported.
Parameters
----------
url : str
The string of the path where all the images are stored.
format : {'PNG' | 'JPG' | 'auto'}, optional
The format of the images in the directory. The default 'auto' parameter
value tries to infer the image type from the file extension. If a
format is specified, all images must be of that format.
with_path : bool, optional
Indicates whether a path column is added to the SFrame. If 'with_path'
is set to True, the returned SFrame contains a 'path' column, which
holds a path string for each Image object.
recursive : bool, optional
Indicates whether 'load_images' should do recursive directory traversal,
or a flat directory traversal.
ignore_failure : bool, optional
If true, prints warning for failed images and keep loading the rest of
the images.
random_order : bool, optional
Load images in random order.
Returns
-------
out : SFrame
Returns an SFrame with either an 'image' column or both an 'image' and
a 'path' column. The 'image' column is a column of Image objects. If
with_path is True, there is also a 'path' column which contains the image
path for each of each corresponding Image object.
Examples
--------
>>> url ='https://static.turi.com/datasets/images/nested'
>>> image_sframe = turicreate.image_analysis.load_images(url, "auto", with_path=False,
... recursive=True)
"""
from ... import extensions as _extensions
from ...util import _make_internal_url
return _extensions.load_images(url, format, with_path,
recursive, ignore_failure, random_order) | python | def load_images(url, format='auto', with_path=True, recursive=True, ignore_failure=True, random_order=False):
"""
Loads images from a directory. JPEG and PNG images are supported.
Parameters
----------
url : str
The string of the path where all the images are stored.
format : {'PNG' | 'JPG' | 'auto'}, optional
The format of the images in the directory. The default 'auto' parameter
value tries to infer the image type from the file extension. If a
format is specified, all images must be of that format.
with_path : bool, optional
Indicates whether a path column is added to the SFrame. If 'with_path'
is set to True, the returned SFrame contains a 'path' column, which
holds a path string for each Image object.
recursive : bool, optional
Indicates whether 'load_images' should do recursive directory traversal,
or a flat directory traversal.
ignore_failure : bool, optional
If true, prints warning for failed images and keep loading the rest of
the images.
random_order : bool, optional
Load images in random order.
Returns
-------
out : SFrame
Returns an SFrame with either an 'image' column or both an 'image' and
a 'path' column. The 'image' column is a column of Image objects. If
with_path is True, there is also a 'path' column which contains the image
path for each of each corresponding Image object.
Examples
--------
>>> url ='https://static.turi.com/datasets/images/nested'
>>> image_sframe = turicreate.image_analysis.load_images(url, "auto", with_path=False,
... recursive=True)
"""
from ... import extensions as _extensions
from ...util import _make_internal_url
return _extensions.load_images(url, format, with_path,
recursive, ignore_failure, random_order) | [
"def",
"load_images",
"(",
"url",
",",
"format",
"=",
"'auto'",
",",
"with_path",
"=",
"True",
",",
"recursive",
"=",
"True",
",",
"ignore_failure",
"=",
"True",
",",
"random_order",
"=",
"False",
")",
":",
"from",
".",
".",
".",
"import",
"extensions",
"as",
"_extensions",
"from",
".",
".",
".",
"util",
"import",
"_make_internal_url",
"return",
"_extensions",
".",
"load_images",
"(",
"url",
",",
"format",
",",
"with_path",
",",
"recursive",
",",
"ignore_failure",
",",
"random_order",
")"
] | Loads images from a directory. JPEG and PNG images are supported.
Parameters
----------
url : str
The string of the path where all the images are stored.
format : {'PNG' | 'JPG' | 'auto'}, optional
The format of the images in the directory. The default 'auto' parameter
value tries to infer the image type from the file extension. If a
format is specified, all images must be of that format.
with_path : bool, optional
Indicates whether a path column is added to the SFrame. If 'with_path'
is set to True, the returned SFrame contains a 'path' column, which
holds a path string for each Image object.
recursive : bool, optional
Indicates whether 'load_images' should do recursive directory traversal,
or a flat directory traversal.
ignore_failure : bool, optional
If true, prints warning for failed images and keep loading the rest of
the images.
random_order : bool, optional
Load images in random order.
Returns
-------
out : SFrame
Returns an SFrame with either an 'image' column or both an 'image' and
a 'path' column. The 'image' column is a column of Image objects. If
with_path is True, there is also a 'path' column which contains the image
path for each of each corresponding Image object.
Examples
--------
>>> url ='https://static.turi.com/datasets/images/nested'
>>> image_sframe = turicreate.image_analysis.load_images(url, "auto", with_path=False,
... recursive=True) | [
"Loads",
"images",
"from",
"a",
"directory",
".",
"JPEG",
"and",
"PNG",
"images",
"are",
"supported",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/image_analysis/image_analysis.py#L12-L60 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/image_analysis/image_analysis.py | _decode | def _decode(image_data):
"""
Internal helper function for decoding a single Image or an SArray of Images
"""
from ...data_structures.sarray import SArray as _SArray
from ... import extensions as _extensions
if type(image_data) is _SArray:
return _extensions.decode_image_sarray(image_data)
elif type(image_data) is _Image:
return _extensions.decode_image(image_data) | python | def _decode(image_data):
"""
Internal helper function for decoding a single Image or an SArray of Images
"""
from ...data_structures.sarray import SArray as _SArray
from ... import extensions as _extensions
if type(image_data) is _SArray:
return _extensions.decode_image_sarray(image_data)
elif type(image_data) is _Image:
return _extensions.decode_image(image_data) | [
"def",
"_decode",
"(",
"image_data",
")",
":",
"from",
".",
".",
".",
"data_structures",
".",
"sarray",
"import",
"SArray",
"as",
"_SArray",
"from",
".",
".",
".",
"import",
"extensions",
"as",
"_extensions",
"if",
"type",
"(",
"image_data",
")",
"is",
"_SArray",
":",
"return",
"_extensions",
".",
"decode_image_sarray",
"(",
"image_data",
")",
"elif",
"type",
"(",
"image_data",
")",
"is",
"_Image",
":",
"return",
"_extensions",
".",
"decode_image",
"(",
"image_data",
")"
] | Internal helper function for decoding a single Image or an SArray of Images | [
"Internal",
"helper",
"function",
"for",
"decoding",
"a",
"single",
"Image",
"or",
"an",
"SArray",
"of",
"Images"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/image_analysis/image_analysis.py#L63-L72 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/image_analysis/image_analysis.py | resize | def resize(image, width, height, channels=None, decode=False,
resample='nearest'):
"""
Resizes the image or SArray of Images to a specific width, height, and
number of channels.
Parameters
----------
image : turicreate.Image | SArray
The image or SArray of images to be resized.
width : int
The width the image is resized to.
height : int
The height the image is resized to.
channels : int, optional
The number of channels the image is resized to. 1 channel
corresponds to grayscale, 3 channels corresponds to RGB, and 4
channels corresponds to RGBA images.
decode : bool, optional
Whether to store the resized image in decoded format. Decoded takes
more space, but makes the resize and future operations on the image faster.
resample : 'nearest' or 'bilinear'
Specify the resampling filter:
- ``'nearest'``: Nearest neigbhor, extremely fast
- ``'bilinear'``: Bilinear, fast and with less aliasing artifacts
Returns
-------
out : turicreate.Image
Returns a resized Image object.
Notes
-----
Grayscale Images -> Images with one channel, representing a scale from
white to black
RGB Images -> Images with 3 channels, with each pixel having Green, Red,
and Blue values.
RGBA Images -> An RGB image with an opacity channel.
Examples
--------
Resize a single image
>>> img = turicreate.Image('https://static.turi.com/datasets/images/sample.jpg')
>>> resized_img = turicreate.image_analysis.resize(img,100,100,1)
Resize an SArray of images
>>> url ='https://static.turi.com/datasets/images/nested'
>>> image_sframe = turicreate.image_analysis.load_images(url, "auto", with_path=False,
... recursive=True)
>>> image_sarray = image_sframe["image"]
>>> resized_images = turicreate.image_analysis.resize(image_sarray, 100, 100, 1)
"""
if height < 0 or width < 0:
raise ValueError("Cannot resize to negative sizes")
if resample == 'nearest':
resample_method = 0
elif resample == 'bilinear':
resample_method = 1
else:
raise ValueError("Unknown resample option: '%s'" % resample)
from ...data_structures.sarray import SArray as _SArray
from ... import extensions as _extensions
if type(image) is _Image:
if channels is None:
channels = image.channels
if channels <= 0:
raise ValueError("cannot resize images to 0 or fewer channels")
return _extensions.resize_image(image, width, height, channels, decode, resample_method)
elif type(image) is _SArray:
if channels is None:
channels = 3
if channels <= 0:
raise ValueError("cannot resize images to 0 or fewer channels")
return image.apply(lambda x: _extensions.resize_image(x, width, height, channels, decode, resample_method))
else:
raise ValueError("Cannot call 'resize' on objects that are not either an Image or SArray of Images") | python | def resize(image, width, height, channels=None, decode=False,
resample='nearest'):
"""
Resizes the image or SArray of Images to a specific width, height, and
number of channels.
Parameters
----------
image : turicreate.Image | SArray
The image or SArray of images to be resized.
width : int
The width the image is resized to.
height : int
The height the image is resized to.
channels : int, optional
The number of channels the image is resized to. 1 channel
corresponds to grayscale, 3 channels corresponds to RGB, and 4
channels corresponds to RGBA images.
decode : bool, optional
Whether to store the resized image in decoded format. Decoded takes
more space, but makes the resize and future operations on the image faster.
resample : 'nearest' or 'bilinear'
Specify the resampling filter:
- ``'nearest'``: Nearest neigbhor, extremely fast
- ``'bilinear'``: Bilinear, fast and with less aliasing artifacts
Returns
-------
out : turicreate.Image
Returns a resized Image object.
Notes
-----
Grayscale Images -> Images with one channel, representing a scale from
white to black
RGB Images -> Images with 3 channels, with each pixel having Green, Red,
and Blue values.
RGBA Images -> An RGB image with an opacity channel.
Examples
--------
Resize a single image
>>> img = turicreate.Image('https://static.turi.com/datasets/images/sample.jpg')
>>> resized_img = turicreate.image_analysis.resize(img,100,100,1)
Resize an SArray of images
>>> url ='https://static.turi.com/datasets/images/nested'
>>> image_sframe = turicreate.image_analysis.load_images(url, "auto", with_path=False,
... recursive=True)
>>> image_sarray = image_sframe["image"]
>>> resized_images = turicreate.image_analysis.resize(image_sarray, 100, 100, 1)
"""
if height < 0 or width < 0:
raise ValueError("Cannot resize to negative sizes")
if resample == 'nearest':
resample_method = 0
elif resample == 'bilinear':
resample_method = 1
else:
raise ValueError("Unknown resample option: '%s'" % resample)
from ...data_structures.sarray import SArray as _SArray
from ... import extensions as _extensions
if type(image) is _Image:
if channels is None:
channels = image.channels
if channels <= 0:
raise ValueError("cannot resize images to 0 or fewer channels")
return _extensions.resize_image(image, width, height, channels, decode, resample_method)
elif type(image) is _SArray:
if channels is None:
channels = 3
if channels <= 0:
raise ValueError("cannot resize images to 0 or fewer channels")
return image.apply(lambda x: _extensions.resize_image(x, width, height, channels, decode, resample_method))
else:
raise ValueError("Cannot call 'resize' on objects that are not either an Image or SArray of Images") | [
"def",
"resize",
"(",
"image",
",",
"width",
",",
"height",
",",
"channels",
"=",
"None",
",",
"decode",
"=",
"False",
",",
"resample",
"=",
"'nearest'",
")",
":",
"if",
"height",
"<",
"0",
"or",
"width",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Cannot resize to negative sizes\"",
")",
"if",
"resample",
"==",
"'nearest'",
":",
"resample_method",
"=",
"0",
"elif",
"resample",
"==",
"'bilinear'",
":",
"resample_method",
"=",
"1",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown resample option: '%s'\"",
"%",
"resample",
")",
"from",
".",
".",
".",
"data_structures",
".",
"sarray",
"import",
"SArray",
"as",
"_SArray",
"from",
".",
".",
".",
"import",
"extensions",
"as",
"_extensions",
"if",
"type",
"(",
"image",
")",
"is",
"_Image",
":",
"if",
"channels",
"is",
"None",
":",
"channels",
"=",
"image",
".",
"channels",
"if",
"channels",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"cannot resize images to 0 or fewer channels\"",
")",
"return",
"_extensions",
".",
"resize_image",
"(",
"image",
",",
"width",
",",
"height",
",",
"channels",
",",
"decode",
",",
"resample_method",
")",
"elif",
"type",
"(",
"image",
")",
"is",
"_SArray",
":",
"if",
"channels",
"is",
"None",
":",
"channels",
"=",
"3",
"if",
"channels",
"<=",
"0",
":",
"raise",
"ValueError",
"(",
"\"cannot resize images to 0 or fewer channels\"",
")",
"return",
"image",
".",
"apply",
"(",
"lambda",
"x",
":",
"_extensions",
".",
"resize_image",
"(",
"x",
",",
"width",
",",
"height",
",",
"channels",
",",
"decode",
",",
"resample_method",
")",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Cannot call 'resize' on objects that are not either an Image or SArray of Images\"",
")"
] | Resizes the image or SArray of Images to a specific width, height, and
number of channels.
Parameters
----------
image : turicreate.Image | SArray
The image or SArray of images to be resized.
width : int
The width the image is resized to.
height : int
The height the image is resized to.
channels : int, optional
The number of channels the image is resized to. 1 channel
corresponds to grayscale, 3 channels corresponds to RGB, and 4
channels corresponds to RGBA images.
decode : bool, optional
Whether to store the resized image in decoded format. Decoded takes
more space, but makes the resize and future operations on the image faster.
resample : 'nearest' or 'bilinear'
Specify the resampling filter:
- ``'nearest'``: Nearest neigbhor, extremely fast
- ``'bilinear'``: Bilinear, fast and with less aliasing artifacts
Returns
-------
out : turicreate.Image
Returns a resized Image object.
Notes
-----
Grayscale Images -> Images with one channel, representing a scale from
white to black
RGB Images -> Images with 3 channels, with each pixel having Green, Red,
and Blue values.
RGBA Images -> An RGB image with an opacity channel.
Examples
--------
Resize a single image
>>> img = turicreate.Image('https://static.turi.com/datasets/images/sample.jpg')
>>> resized_img = turicreate.image_analysis.resize(img,100,100,1)
Resize an SArray of images
>>> url ='https://static.turi.com/datasets/images/nested'
>>> image_sframe = turicreate.image_analysis.load_images(url, "auto", with_path=False,
... recursive=True)
>>> image_sarray = image_sframe["image"]
>>> resized_images = turicreate.image_analysis.resize(image_sarray, 100, 100, 1) | [
"Resizes",
"the",
"image",
"or",
"SArray",
"of",
"Images",
"to",
"a",
"specific",
"width",
"height",
"and",
"number",
"of",
"channels",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/image_analysis/image_analysis.py#L76-L161 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py | _convert_1bit_array_to_byte_array | def _convert_1bit_array_to_byte_array(arr):
"""
Convert bit array to byte array.
:param arr: list
Bits as a list where each element is an integer of 0 or 1
Returns
-------
numpy.array
1D numpy array of type uint8
"""
# Padding if necessary
while len(arr) < 8 or len(arr) % 8:
arr.append(0)
arr = _np.array(arr, dtype='uint8')
bit_arr = []
idx = 0
# Iterate and combine 8-bits into a uint8
for arr_idx in range(int(len(arr) / 8)):
bit_arr.append(((arr[idx] << 7) & (1 << 7)) |
((arr[idx+1] << 6) & (1 << 6)) |
((arr[idx+2] << 5) & (1 << 5)) |
((arr[idx+3] << 4) & (1 << 4)) |
((arr[idx+4] << 3) & (1 << 3)) |
((arr[idx+5] << 2) & (1 << 2)) |
((arr[idx+6] << 1) & (1 << 1)) |
((arr[idx+7] << 0) & (1 << 0))
)
idx += 8
return _np.array(bit_arr, dtype='uint8') | python | def _convert_1bit_array_to_byte_array(arr):
"""
Convert bit array to byte array.
:param arr: list
Bits as a list where each element is an integer of 0 or 1
Returns
-------
numpy.array
1D numpy array of type uint8
"""
# Padding if necessary
while len(arr) < 8 or len(arr) % 8:
arr.append(0)
arr = _np.array(arr, dtype='uint8')
bit_arr = []
idx = 0
# Iterate and combine 8-bits into a uint8
for arr_idx in range(int(len(arr) / 8)):
bit_arr.append(((arr[idx] << 7) & (1 << 7)) |
((arr[idx+1] << 6) & (1 << 6)) |
((arr[idx+2] << 5) & (1 << 5)) |
((arr[idx+3] << 4) & (1 << 4)) |
((arr[idx+4] << 3) & (1 << 3)) |
((arr[idx+5] << 2) & (1 << 2)) |
((arr[idx+6] << 1) & (1 << 1)) |
((arr[idx+7] << 0) & (1 << 0))
)
idx += 8
return _np.array(bit_arr, dtype='uint8') | [
"def",
"_convert_1bit_array_to_byte_array",
"(",
"arr",
")",
":",
"# Padding if necessary",
"while",
"len",
"(",
"arr",
")",
"<",
"8",
"or",
"len",
"(",
"arr",
")",
"%",
"8",
":",
"arr",
".",
"append",
"(",
"0",
")",
"arr",
"=",
"_np",
".",
"array",
"(",
"arr",
",",
"dtype",
"=",
"'uint8'",
")",
"bit_arr",
"=",
"[",
"]",
"idx",
"=",
"0",
"# Iterate and combine 8-bits into a uint8",
"for",
"arr_idx",
"in",
"range",
"(",
"int",
"(",
"len",
"(",
"arr",
")",
"/",
"8",
")",
")",
":",
"bit_arr",
".",
"append",
"(",
"(",
"(",
"arr",
"[",
"idx",
"]",
"<<",
"7",
")",
"&",
"(",
"1",
"<<",
"7",
")",
")",
"|",
"(",
"(",
"arr",
"[",
"idx",
"+",
"1",
"]",
"<<",
"6",
")",
"&",
"(",
"1",
"<<",
"6",
")",
")",
"|",
"(",
"(",
"arr",
"[",
"idx",
"+",
"2",
"]",
"<<",
"5",
")",
"&",
"(",
"1",
"<<",
"5",
")",
")",
"|",
"(",
"(",
"arr",
"[",
"idx",
"+",
"3",
"]",
"<<",
"4",
")",
"&",
"(",
"1",
"<<",
"4",
")",
")",
"|",
"(",
"(",
"arr",
"[",
"idx",
"+",
"4",
"]",
"<<",
"3",
")",
"&",
"(",
"1",
"<<",
"3",
")",
")",
"|",
"(",
"(",
"arr",
"[",
"idx",
"+",
"5",
"]",
"<<",
"2",
")",
"&",
"(",
"1",
"<<",
"2",
")",
")",
"|",
"(",
"(",
"arr",
"[",
"idx",
"+",
"6",
"]",
"<<",
"1",
")",
"&",
"(",
"1",
"<<",
"1",
")",
")",
"|",
"(",
"(",
"arr",
"[",
"idx",
"+",
"7",
"]",
"<<",
"0",
")",
"&",
"(",
"1",
"<<",
"0",
")",
")",
")",
"idx",
"+=",
"8",
"return",
"_np",
".",
"array",
"(",
"bit_arr",
",",
"dtype",
"=",
"'uint8'",
")"
] | Convert bit array to byte array.
:param arr: list
Bits as a list where each element is an integer of 0 or 1
Returns
-------
numpy.array
1D numpy array of type uint8 | [
"Convert",
"bit",
"array",
"to",
"byte",
"array",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py#L34-L65 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py | _decompose_bytes_to_bit_arr | def _decompose_bytes_to_bit_arr(arr):
"""
Unpack bytes to bits
:param arr: list
Byte Stream, as a list of uint8 values
Returns
-------
bit_arr: list
Decomposed bit stream as a list of 0/1s of length (len(arr) * 8)
"""
bit_arr = []
for idx in range(len(arr)):
for i in reversed(range(8)):
bit_arr.append((arr[idx] >> i) & (1 << 0))
return bit_arr | python | def _decompose_bytes_to_bit_arr(arr):
"""
Unpack bytes to bits
:param arr: list
Byte Stream, as a list of uint8 values
Returns
-------
bit_arr: list
Decomposed bit stream as a list of 0/1s of length (len(arr) * 8)
"""
bit_arr = []
for idx in range(len(arr)):
for i in reversed(range(8)):
bit_arr.append((arr[idx] >> i) & (1 << 0))
return bit_arr | [
"def",
"_decompose_bytes_to_bit_arr",
"(",
"arr",
")",
":",
"bit_arr",
"=",
"[",
"]",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"arr",
")",
")",
":",
"for",
"i",
"in",
"reversed",
"(",
"range",
"(",
"8",
")",
")",
":",
"bit_arr",
".",
"append",
"(",
"(",
"arr",
"[",
"idx",
"]",
">>",
"i",
")",
"&",
"(",
"1",
"<<",
"0",
")",
")",
"return",
"bit_arr"
] | Unpack bytes to bits
:param arr: list
Byte Stream, as a list of uint8 values
Returns
-------
bit_arr: list
Decomposed bit stream as a list of 0/1s of length (len(arr) * 8) | [
"Unpack",
"bytes",
"to",
"bits"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py#L77-L93 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py | _get_linear_lookup_table_and_weight | def _get_linear_lookup_table_and_weight(nbits, wp):
"""
Generate a linear lookup table.
:param nbits: int
Number of bits to represent a quantized weight value
:param wp: numpy.array
Weight blob to be quantized
Returns
-------
lookup_table: numpy.array
Lookup table of shape (2^nbits, )
qw: numpy.array
Decomposed bit stream as a list of 0/1s of length (len(arr) * 8)
"""
w = wp.reshape(1, -1)
qw, scales, biases = _quantize_channelwise_linear(w, nbits, axis=0)
indices = _np.array(range(0, 2**nbits))
lookup_table = indices * scales[0] + biases[0]
return lookup_table, qw | python | def _get_linear_lookup_table_and_weight(nbits, wp):
"""
Generate a linear lookup table.
:param nbits: int
Number of bits to represent a quantized weight value
:param wp: numpy.array
Weight blob to be quantized
Returns
-------
lookup_table: numpy.array
Lookup table of shape (2^nbits, )
qw: numpy.array
Decomposed bit stream as a list of 0/1s of length (len(arr) * 8)
"""
w = wp.reshape(1, -1)
qw, scales, biases = _quantize_channelwise_linear(w, nbits, axis=0)
indices = _np.array(range(0, 2**nbits))
lookup_table = indices * scales[0] + biases[0]
return lookup_table, qw | [
"def",
"_get_linear_lookup_table_and_weight",
"(",
"nbits",
",",
"wp",
")",
":",
"w",
"=",
"wp",
".",
"reshape",
"(",
"1",
",",
"-",
"1",
")",
"qw",
",",
"scales",
",",
"biases",
"=",
"_quantize_channelwise_linear",
"(",
"w",
",",
"nbits",
",",
"axis",
"=",
"0",
")",
"indices",
"=",
"_np",
".",
"array",
"(",
"range",
"(",
"0",
",",
"2",
"**",
"nbits",
")",
")",
"lookup_table",
"=",
"indices",
"*",
"scales",
"[",
"0",
"]",
"+",
"biases",
"[",
"0",
"]",
"return",
"lookup_table",
",",
"qw"
] | Generate a linear lookup table.
:param nbits: int
Number of bits to represent a quantized weight value
:param wp: numpy.array
Weight blob to be quantized
Returns
-------
lookup_table: numpy.array
Lookup table of shape (2^nbits, )
qw: numpy.array
Decomposed bit stream as a list of 0/1s of length (len(arr) * 8) | [
"Generate",
"a",
"linear",
"lookup",
"table",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py#L96-L117 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py | _get_kmeans_lookup_table_and_weight | def _get_kmeans_lookup_table_and_weight(nbits, w, init='k-means++', tol=1e-2, n_init=1, rand_seed=0):
"""
Generate K-Means lookup table given a weight parameter field
:param nbits:
Number of bits for quantization
:param w:
Weight as numpy array
Returns
-------
lut: numpy.array
Lookup table, numpy array of shape (1 << nbits, );
wq: numpy.array
Quantized weight of type numpy.uint8
"""
if _HAS_SKLEARN:
from sklearn.cluster import KMeans
else:
raise Exception('sklearn package required for k-means quantization')
units = _np.prod(w.shape)
lut_len = 1 << nbits
n_clusters = units if (units < lut_len) else lut_len
wf = w.reshape(-1, 1)
kmeans = KMeans(n_clusters=n_clusters, init=init, tol=tol, n_init=n_init, random_state=rand_seed).fit(wf)
wq = kmeans.labels_[:units]
lut = _np.zeros(lut_len)
lut[:n_clusters] = kmeans.cluster_centers_.flatten()
return lut, wq | python | def _get_kmeans_lookup_table_and_weight(nbits, w, init='k-means++', tol=1e-2, n_init=1, rand_seed=0):
"""
Generate K-Means lookup table given a weight parameter field
:param nbits:
Number of bits for quantization
:param w:
Weight as numpy array
Returns
-------
lut: numpy.array
Lookup table, numpy array of shape (1 << nbits, );
wq: numpy.array
Quantized weight of type numpy.uint8
"""
if _HAS_SKLEARN:
from sklearn.cluster import KMeans
else:
raise Exception('sklearn package required for k-means quantization')
units = _np.prod(w.shape)
lut_len = 1 << nbits
n_clusters = units if (units < lut_len) else lut_len
wf = w.reshape(-1, 1)
kmeans = KMeans(n_clusters=n_clusters, init=init, tol=tol, n_init=n_init, random_state=rand_seed).fit(wf)
wq = kmeans.labels_[:units]
lut = _np.zeros(lut_len)
lut[:n_clusters] = kmeans.cluster_centers_.flatten()
return lut, wq | [
"def",
"_get_kmeans_lookup_table_and_weight",
"(",
"nbits",
",",
"w",
",",
"init",
"=",
"'k-means++'",
",",
"tol",
"=",
"1e-2",
",",
"n_init",
"=",
"1",
",",
"rand_seed",
"=",
"0",
")",
":",
"if",
"_HAS_SKLEARN",
":",
"from",
"sklearn",
".",
"cluster",
"import",
"KMeans",
"else",
":",
"raise",
"Exception",
"(",
"'sklearn package required for k-means quantization'",
")",
"units",
"=",
"_np",
".",
"prod",
"(",
"w",
".",
"shape",
")",
"lut_len",
"=",
"1",
"<<",
"nbits",
"n_clusters",
"=",
"units",
"if",
"(",
"units",
"<",
"lut_len",
")",
"else",
"lut_len",
"wf",
"=",
"w",
".",
"reshape",
"(",
"-",
"1",
",",
"1",
")",
"kmeans",
"=",
"KMeans",
"(",
"n_clusters",
"=",
"n_clusters",
",",
"init",
"=",
"init",
",",
"tol",
"=",
"tol",
",",
"n_init",
"=",
"n_init",
",",
"random_state",
"=",
"rand_seed",
")",
".",
"fit",
"(",
"wf",
")",
"wq",
"=",
"kmeans",
".",
"labels_",
"[",
":",
"units",
"]",
"lut",
"=",
"_np",
".",
"zeros",
"(",
"lut_len",
")",
"lut",
"[",
":",
"n_clusters",
"]",
"=",
"kmeans",
".",
"cluster_centers_",
".",
"flatten",
"(",
")",
"return",
"lut",
",",
"wq"
] | Generate K-Means lookup table given a weight parameter field
:param nbits:
Number of bits for quantization
:param w:
Weight as numpy array
Returns
-------
lut: numpy.array
Lookup table, numpy array of shape (1 << nbits, );
wq: numpy.array
Quantized weight of type numpy.uint8 | [
"Generate",
"K",
"-",
"Means",
"lookup",
"table",
"given",
"a",
"weight",
"parameter",
"field"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py#L120-L149 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py | _quantize_channelwise_linear | def _quantize_channelwise_linear(weight, nbits, axis=0):
"""
Linearly quantize weight blob.
:param weight: numpy.array
Weight to be quantized.
:param nbits: int
Number of bits per weight element
:param axis: int
Axis of the weight blob to compute channel-wise quantization, can be 0 or 1
Returns
-------
quantized_weight: numpy.array
quantized weight as float numpy array, with the same shape as weight
scale: numpy.array
per channel scale
bias: numpy.array
per channel bias
"""
if len(weight.shape) == 1: # vector situation, treat as 1 channel
weight = weight.reshape((1, weight.shape[0]))
rank = len(weight.shape)
if axis == 1:
transposed_axis_order = (1,0) + tuple(range(2,rank))
weight = _np.transpose(weight, transposed_axis_order)
num_channels = weight.shape[0]
shape = weight.shape
weight = weight.reshape((num_channels, -1)) # [C, L]
a = _np.amin(weight, axis=-1) # [C,]
b = _np.amax(weight, axis=-1) # [C,]
# Quantize weights to full range [0, (1 << nbits) - 1]
qa = 0
qb = (1 << nbits) - 1
# Use a mask to filter out channels with very close weight values
mask = (b - a) > 1e-5 # [C,1] (normal channels)
r_mask = ~mask # (all-same-value) channels
qw = _np.zeros_like(weight) # [C, L]
scale = _np.ones((num_channels,))
bias = _np.zeros((num_channels,))
if _np.any(mask): # normal channels
qw[mask] = (weight[mask] - a[mask][:,None]) / (b[mask] - a[mask])[:,None] * (qb - qa) + qa
scale[mask] = (b[mask] - a[mask]) / (qb - qa)
bias[mask] = - scale[mask] * qa + a[mask]
if _np.any(r_mask): # singular channels
qw[r_mask] = qa
scale[r_mask] = 0
bias[r_mask] = a[r_mask]
# Reshape
quantized_weight = qw.reshape(shape)
if axis == 1:
quantized_weight = _np.transpose(quantized_weight, transposed_axis_order)
return (quantized_weight, scale, bias) | python | def _quantize_channelwise_linear(weight, nbits, axis=0):
"""
Linearly quantize weight blob.
:param weight: numpy.array
Weight to be quantized.
:param nbits: int
Number of bits per weight element
:param axis: int
Axis of the weight blob to compute channel-wise quantization, can be 0 or 1
Returns
-------
quantized_weight: numpy.array
quantized weight as float numpy array, with the same shape as weight
scale: numpy.array
per channel scale
bias: numpy.array
per channel bias
"""
if len(weight.shape) == 1: # vector situation, treat as 1 channel
weight = weight.reshape((1, weight.shape[0]))
rank = len(weight.shape)
if axis == 1:
transposed_axis_order = (1,0) + tuple(range(2,rank))
weight = _np.transpose(weight, transposed_axis_order)
num_channels = weight.shape[0]
shape = weight.shape
weight = weight.reshape((num_channels, -1)) # [C, L]
a = _np.amin(weight, axis=-1) # [C,]
b = _np.amax(weight, axis=-1) # [C,]
# Quantize weights to full range [0, (1 << nbits) - 1]
qa = 0
qb = (1 << nbits) - 1
# Use a mask to filter out channels with very close weight values
mask = (b - a) > 1e-5 # [C,1] (normal channels)
r_mask = ~mask # (all-same-value) channels
qw = _np.zeros_like(weight) # [C, L]
scale = _np.ones((num_channels,))
bias = _np.zeros((num_channels,))
if _np.any(mask): # normal channels
qw[mask] = (weight[mask] - a[mask][:,None]) / (b[mask] - a[mask])[:,None] * (qb - qa) + qa
scale[mask] = (b[mask] - a[mask]) / (qb - qa)
bias[mask] = - scale[mask] * qa + a[mask]
if _np.any(r_mask): # singular channels
qw[r_mask] = qa
scale[r_mask] = 0
bias[r_mask] = a[r_mask]
# Reshape
quantized_weight = qw.reshape(shape)
if axis == 1:
quantized_weight = _np.transpose(quantized_weight, transposed_axis_order)
return (quantized_weight, scale, bias) | [
"def",
"_quantize_channelwise_linear",
"(",
"weight",
",",
"nbits",
",",
"axis",
"=",
"0",
")",
":",
"if",
"len",
"(",
"weight",
".",
"shape",
")",
"==",
"1",
":",
"# vector situation, treat as 1 channel",
"weight",
"=",
"weight",
".",
"reshape",
"(",
"(",
"1",
",",
"weight",
".",
"shape",
"[",
"0",
"]",
")",
")",
"rank",
"=",
"len",
"(",
"weight",
".",
"shape",
")",
"if",
"axis",
"==",
"1",
":",
"transposed_axis_order",
"=",
"(",
"1",
",",
"0",
")",
"+",
"tuple",
"(",
"range",
"(",
"2",
",",
"rank",
")",
")",
"weight",
"=",
"_np",
".",
"transpose",
"(",
"weight",
",",
"transposed_axis_order",
")",
"num_channels",
"=",
"weight",
".",
"shape",
"[",
"0",
"]",
"shape",
"=",
"weight",
".",
"shape",
"weight",
"=",
"weight",
".",
"reshape",
"(",
"(",
"num_channels",
",",
"-",
"1",
")",
")",
"# [C, L]",
"a",
"=",
"_np",
".",
"amin",
"(",
"weight",
",",
"axis",
"=",
"-",
"1",
")",
"# [C,]",
"b",
"=",
"_np",
".",
"amax",
"(",
"weight",
",",
"axis",
"=",
"-",
"1",
")",
"# [C,]",
"# Quantize weights to full range [0, (1 << nbits) - 1]",
"qa",
"=",
"0",
"qb",
"=",
"(",
"1",
"<<",
"nbits",
")",
"-",
"1",
"# Use a mask to filter out channels with very close weight values",
"mask",
"=",
"(",
"b",
"-",
"a",
")",
">",
"1e-5",
"# [C,1] (normal channels)",
"r_mask",
"=",
"~",
"mask",
"# (all-same-value) channels",
"qw",
"=",
"_np",
".",
"zeros_like",
"(",
"weight",
")",
"# [C, L]",
"scale",
"=",
"_np",
".",
"ones",
"(",
"(",
"num_channels",
",",
")",
")",
"bias",
"=",
"_np",
".",
"zeros",
"(",
"(",
"num_channels",
",",
")",
")",
"if",
"_np",
".",
"any",
"(",
"mask",
")",
":",
"# normal channels",
"qw",
"[",
"mask",
"]",
"=",
"(",
"weight",
"[",
"mask",
"]",
"-",
"a",
"[",
"mask",
"]",
"[",
":",
",",
"None",
"]",
")",
"/",
"(",
"b",
"[",
"mask",
"]",
"-",
"a",
"[",
"mask",
"]",
")",
"[",
":",
",",
"None",
"]",
"*",
"(",
"qb",
"-",
"qa",
")",
"+",
"qa",
"scale",
"[",
"mask",
"]",
"=",
"(",
"b",
"[",
"mask",
"]",
"-",
"a",
"[",
"mask",
"]",
")",
"/",
"(",
"qb",
"-",
"qa",
")",
"bias",
"[",
"mask",
"]",
"=",
"-",
"scale",
"[",
"mask",
"]",
"*",
"qa",
"+",
"a",
"[",
"mask",
"]",
"if",
"_np",
".",
"any",
"(",
"r_mask",
")",
":",
"# singular channels",
"qw",
"[",
"r_mask",
"]",
"=",
"qa",
"scale",
"[",
"r_mask",
"]",
"=",
"0",
"bias",
"[",
"r_mask",
"]",
"=",
"a",
"[",
"r_mask",
"]",
"# Reshape",
"quantized_weight",
"=",
"qw",
".",
"reshape",
"(",
"shape",
")",
"if",
"axis",
"==",
"1",
":",
"quantized_weight",
"=",
"_np",
".",
"transpose",
"(",
"quantized_weight",
",",
"transposed_axis_order",
")",
"return",
"(",
"quantized_weight",
",",
"scale",
",",
"bias",
")"
] | Linearly quantize weight blob.
:param weight: numpy.array
Weight to be quantized.
:param nbits: int
Number of bits per weight element
:param axis: int
Axis of the weight blob to compute channel-wise quantization, can be 0 or 1
Returns
-------
quantized_weight: numpy.array
quantized weight as float numpy array, with the same shape as weight
scale: numpy.array
per channel scale
bias: numpy.array
per channel bias | [
"Linearly",
"quantize",
"weight",
"blob",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py#L151-L212 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py | _quantize_wp | def _quantize_wp(wp, nbits, qm, axis=0, **kwargs):
"""
Quantize the weight blob
:param wp: numpy.array
Weight parameters
:param nbits: int
Number of bits
:param qm:
Quantization mode
:param lut_function: (``callable function``)
Python callable representing a look-up table
Returns
-------
scale: numpy.array
Per-channel scale
bias: numpy.array
Per-channel bias
lut: numpy.array
Lookup table
quantized_wp: numpy.array
Quantized weight of same shape as wp, with dtype numpy.uint8
"""
scale = bias = lut = None
# Linear Quantization
if qm == _QUANTIZATION_MODE_LINEAR_QUANTIZATION:
qw, scale, bias = _quantize_channelwise_linear(wp, nbits, axis)
# Lookup tables
elif qm == _QUANTIZATION_MODE_LOOKUP_TABLE_KMEANS:
lut, qw = _get_kmeans_lookup_table_and_weight(nbits, wp)
elif qm == _QUANTIZATION_MODE_CUSTOM_LOOKUP_TABLE:
if 'lut_function' not in kwargs.keys():
raise Exception('Custom lookup table quantization mode '
'selected but no lookup table function passed')
lut_function = kwargs['lut_function']
if not callable(lut_function):
raise Exception('Argument for Lookup Table passed in but is '
'not callable')
try:
lut, qw = lut_function(nbits, wp)
except Exception as e:
raise Exception('{}\nCall to Lookup Table function failed'
.format(e.message))
elif qm == _QUANTIZATION_MODE_LOOKUP_TABLE_LINEAR:
lut, qw = _get_linear_lookup_table_and_weight(nbits, wp)
else:
raise NotImplementedError('Quantization method "{}" not supported'.format(qm))
quantized_wp = _np.uint8(qw)
return scale, bias, lut, quantized_wp | python | def _quantize_wp(wp, nbits, qm, axis=0, **kwargs):
"""
Quantize the weight blob
:param wp: numpy.array
Weight parameters
:param nbits: int
Number of bits
:param qm:
Quantization mode
:param lut_function: (``callable function``)
Python callable representing a look-up table
Returns
-------
scale: numpy.array
Per-channel scale
bias: numpy.array
Per-channel bias
lut: numpy.array
Lookup table
quantized_wp: numpy.array
Quantized weight of same shape as wp, with dtype numpy.uint8
"""
scale = bias = lut = None
# Linear Quantization
if qm == _QUANTIZATION_MODE_LINEAR_QUANTIZATION:
qw, scale, bias = _quantize_channelwise_linear(wp, nbits, axis)
# Lookup tables
elif qm == _QUANTIZATION_MODE_LOOKUP_TABLE_KMEANS:
lut, qw = _get_kmeans_lookup_table_and_weight(nbits, wp)
elif qm == _QUANTIZATION_MODE_CUSTOM_LOOKUP_TABLE:
if 'lut_function' not in kwargs.keys():
raise Exception('Custom lookup table quantization mode '
'selected but no lookup table function passed')
lut_function = kwargs['lut_function']
if not callable(lut_function):
raise Exception('Argument for Lookup Table passed in but is '
'not callable')
try:
lut, qw = lut_function(nbits, wp)
except Exception as e:
raise Exception('{}\nCall to Lookup Table function failed'
.format(e.message))
elif qm == _QUANTIZATION_MODE_LOOKUP_TABLE_LINEAR:
lut, qw = _get_linear_lookup_table_and_weight(nbits, wp)
else:
raise NotImplementedError('Quantization method "{}" not supported'.format(qm))
quantized_wp = _np.uint8(qw)
return scale, bias, lut, quantized_wp | [
"def",
"_quantize_wp",
"(",
"wp",
",",
"nbits",
",",
"qm",
",",
"axis",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"scale",
"=",
"bias",
"=",
"lut",
"=",
"None",
"# Linear Quantization",
"if",
"qm",
"==",
"_QUANTIZATION_MODE_LINEAR_QUANTIZATION",
":",
"qw",
",",
"scale",
",",
"bias",
"=",
"_quantize_channelwise_linear",
"(",
"wp",
",",
"nbits",
",",
"axis",
")",
"# Lookup tables",
"elif",
"qm",
"==",
"_QUANTIZATION_MODE_LOOKUP_TABLE_KMEANS",
":",
"lut",
",",
"qw",
"=",
"_get_kmeans_lookup_table_and_weight",
"(",
"nbits",
",",
"wp",
")",
"elif",
"qm",
"==",
"_QUANTIZATION_MODE_CUSTOM_LOOKUP_TABLE",
":",
"if",
"'lut_function'",
"not",
"in",
"kwargs",
".",
"keys",
"(",
")",
":",
"raise",
"Exception",
"(",
"'Custom lookup table quantization mode '",
"'selected but no lookup table function passed'",
")",
"lut_function",
"=",
"kwargs",
"[",
"'lut_function'",
"]",
"if",
"not",
"callable",
"(",
"lut_function",
")",
":",
"raise",
"Exception",
"(",
"'Argument for Lookup Table passed in but is '",
"'not callable'",
")",
"try",
":",
"lut",
",",
"qw",
"=",
"lut_function",
"(",
"nbits",
",",
"wp",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"Exception",
"(",
"'{}\\nCall to Lookup Table function failed'",
".",
"format",
"(",
"e",
".",
"message",
")",
")",
"elif",
"qm",
"==",
"_QUANTIZATION_MODE_LOOKUP_TABLE_LINEAR",
":",
"lut",
",",
"qw",
"=",
"_get_linear_lookup_table_and_weight",
"(",
"nbits",
",",
"wp",
")",
"else",
":",
"raise",
"NotImplementedError",
"(",
"'Quantization method \"{}\" not supported'",
".",
"format",
"(",
"qm",
")",
")",
"quantized_wp",
"=",
"_np",
".",
"uint8",
"(",
"qw",
")",
"return",
"scale",
",",
"bias",
",",
"lut",
",",
"quantized_wp"
] | Quantize the weight blob
:param wp: numpy.array
Weight parameters
:param nbits: int
Number of bits
:param qm:
Quantization mode
:param lut_function: (``callable function``)
Python callable representing a look-up table
Returns
-------
scale: numpy.array
Per-channel scale
bias: numpy.array
Per-channel bias
lut: numpy.array
Lookup table
quantized_wp: numpy.array
Quantized weight of same shape as wp, with dtype numpy.uint8 | [
"Quantize",
"the",
"weight",
"blob"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py#L215-L266 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py | _quantize_wp_field | def _quantize_wp_field(wp, nbits, qm, shape, axis=0, **kwargs):
"""
Quantize WeightParam field in Neural Network Protobuf
:param wp: MLModel.NeuralNetwork.WeightParam
WeightParam field
:param nbits: int
Number of bits to be quantized
:param qm: str
Quantization mode
:param shape: tuple
Tensor shape held by wp
:param axis: int
Axis over which quantization is performed on, can be either 0 or 1
:param lut_function: (``callable function``)
Python callable representing a LUT table function
"""
# De-quantization
if qm == _QUANTIZATION_MODE_DEQUANTIZE:
return _dequantize_wp(wp, shape, axis)
# If the float32 field is empty do nothing and return
if len(wp.floatValue) == 0:
return
# Half precision (16-bit) quantization
if nbits == 16:
return _wp_to_fp16wp(wp)
if nbits > 8:
raise Exception('Only 8-bit and lower quantization is supported')
if qm not in _SUPPORTED_QUANTIZATION_MODES:
raise Exception('Quantization mode {} not supported'.format(qm))
# axis parameter check
if axis == 1 and len(shape) != 4:
raise Exception('Quantization on second axis is only supported '
'for rank-4 weight blob.')
if axis != 0 and axis != 1:
raise Exception('Invalid quantization axis {} passed in. Allowed'
'values are 0 (first axis) and 1 (second axis)'.format(axis))
# WeightParam size check - non-linear quantizations are applied on layer level
num_channels = shape[axis] if qm == _QUANTIZATION_MODE_LINEAR_QUANTIZATION else 1
if len(wp.floatValue) % num_channels:
raise Exception('Number of quantization channels does not divide evenly into weights')
qparams = wp.quantization
qparams.numberOfBits = nbits
weights = _np.array(wp.floatValue).reshape(shape)
scale, bias, lut, uint8_weights = _quantize_wp(weights, nbits, qm, axis, **kwargs)
uint8_weights = uint8_weights.flatten()
if qm == _QUANTIZATION_MODE_LINEAR_QUANTIZATION:
qparams.linearQuantization.scale.extend(scale)
qparams.linearQuantization.bias.extend(bias)
else:
qparams.lookupTableQuantization.floatValue.extend(lut)
wp.rawValue = bytes()
if nbits == 8:
wp.rawValue += uint8_weights.tobytes()
else:
wp.rawValue += _convert_array_to_nbit_quantized_bytes(uint8_weights, nbits).tobytes()
del wp.floatValue[:] | python | def _quantize_wp_field(wp, nbits, qm, shape, axis=0, **kwargs):
"""
Quantize WeightParam field in Neural Network Protobuf
:param wp: MLModel.NeuralNetwork.WeightParam
WeightParam field
:param nbits: int
Number of bits to be quantized
:param qm: str
Quantization mode
:param shape: tuple
Tensor shape held by wp
:param axis: int
Axis over which quantization is performed on, can be either 0 or 1
:param lut_function: (``callable function``)
Python callable representing a LUT table function
"""
# De-quantization
if qm == _QUANTIZATION_MODE_DEQUANTIZE:
return _dequantize_wp(wp, shape, axis)
# If the float32 field is empty do nothing and return
if len(wp.floatValue) == 0:
return
# Half precision (16-bit) quantization
if nbits == 16:
return _wp_to_fp16wp(wp)
if nbits > 8:
raise Exception('Only 8-bit and lower quantization is supported')
if qm not in _SUPPORTED_QUANTIZATION_MODES:
raise Exception('Quantization mode {} not supported'.format(qm))
# axis parameter check
if axis == 1 and len(shape) != 4:
raise Exception('Quantization on second axis is only supported '
'for rank-4 weight blob.')
if axis != 0 and axis != 1:
raise Exception('Invalid quantization axis {} passed in. Allowed'
'values are 0 (first axis) and 1 (second axis)'.format(axis))
# WeightParam size check - non-linear quantizations are applied on layer level
num_channels = shape[axis] if qm == _QUANTIZATION_MODE_LINEAR_QUANTIZATION else 1
if len(wp.floatValue) % num_channels:
raise Exception('Number of quantization channels does not divide evenly into weights')
qparams = wp.quantization
qparams.numberOfBits = nbits
weights = _np.array(wp.floatValue).reshape(shape)
scale, bias, lut, uint8_weights = _quantize_wp(weights, nbits, qm, axis, **kwargs)
uint8_weights = uint8_weights.flatten()
if qm == _QUANTIZATION_MODE_LINEAR_QUANTIZATION:
qparams.linearQuantization.scale.extend(scale)
qparams.linearQuantization.bias.extend(bias)
else:
qparams.lookupTableQuantization.floatValue.extend(lut)
wp.rawValue = bytes()
if nbits == 8:
wp.rawValue += uint8_weights.tobytes()
else:
wp.rawValue += _convert_array_to_nbit_quantized_bytes(uint8_weights, nbits).tobytes()
del wp.floatValue[:] | [
"def",
"_quantize_wp_field",
"(",
"wp",
",",
"nbits",
",",
"qm",
",",
"shape",
",",
"axis",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"# De-quantization",
"if",
"qm",
"==",
"_QUANTIZATION_MODE_DEQUANTIZE",
":",
"return",
"_dequantize_wp",
"(",
"wp",
",",
"shape",
",",
"axis",
")",
"# If the float32 field is empty do nothing and return",
"if",
"len",
"(",
"wp",
".",
"floatValue",
")",
"==",
"0",
":",
"return",
"# Half precision (16-bit) quantization",
"if",
"nbits",
"==",
"16",
":",
"return",
"_wp_to_fp16wp",
"(",
"wp",
")",
"if",
"nbits",
">",
"8",
":",
"raise",
"Exception",
"(",
"'Only 8-bit and lower quantization is supported'",
")",
"if",
"qm",
"not",
"in",
"_SUPPORTED_QUANTIZATION_MODES",
":",
"raise",
"Exception",
"(",
"'Quantization mode {} not supported'",
".",
"format",
"(",
"qm",
")",
")",
"# axis parameter check",
"if",
"axis",
"==",
"1",
"and",
"len",
"(",
"shape",
")",
"!=",
"4",
":",
"raise",
"Exception",
"(",
"'Quantization on second axis is only supported '",
"'for rank-4 weight blob.'",
")",
"if",
"axis",
"!=",
"0",
"and",
"axis",
"!=",
"1",
":",
"raise",
"Exception",
"(",
"'Invalid quantization axis {} passed in. Allowed'",
"'values are 0 (first axis) and 1 (second axis)'",
".",
"format",
"(",
"axis",
")",
")",
"# WeightParam size check - non-linear quantizations are applied on layer level",
"num_channels",
"=",
"shape",
"[",
"axis",
"]",
"if",
"qm",
"==",
"_QUANTIZATION_MODE_LINEAR_QUANTIZATION",
"else",
"1",
"if",
"len",
"(",
"wp",
".",
"floatValue",
")",
"%",
"num_channels",
":",
"raise",
"Exception",
"(",
"'Number of quantization channels does not divide evenly into weights'",
")",
"qparams",
"=",
"wp",
".",
"quantization",
"qparams",
".",
"numberOfBits",
"=",
"nbits",
"weights",
"=",
"_np",
".",
"array",
"(",
"wp",
".",
"floatValue",
")",
".",
"reshape",
"(",
"shape",
")",
"scale",
",",
"bias",
",",
"lut",
",",
"uint8_weights",
"=",
"_quantize_wp",
"(",
"weights",
",",
"nbits",
",",
"qm",
",",
"axis",
",",
"*",
"*",
"kwargs",
")",
"uint8_weights",
"=",
"uint8_weights",
".",
"flatten",
"(",
")",
"if",
"qm",
"==",
"_QUANTIZATION_MODE_LINEAR_QUANTIZATION",
":",
"qparams",
".",
"linearQuantization",
".",
"scale",
".",
"extend",
"(",
"scale",
")",
"qparams",
".",
"linearQuantization",
".",
"bias",
".",
"extend",
"(",
"bias",
")",
"else",
":",
"qparams",
".",
"lookupTableQuantization",
".",
"floatValue",
".",
"extend",
"(",
"lut",
")",
"wp",
".",
"rawValue",
"=",
"bytes",
"(",
")",
"if",
"nbits",
"==",
"8",
":",
"wp",
".",
"rawValue",
"+=",
"uint8_weights",
".",
"tobytes",
"(",
")",
"else",
":",
"wp",
".",
"rawValue",
"+=",
"_convert_array_to_nbit_quantized_bytes",
"(",
"uint8_weights",
",",
"nbits",
")",
".",
"tobytes",
"(",
")",
"del",
"wp",
".",
"floatValue",
"[",
":",
"]"
] | Quantize WeightParam field in Neural Network Protobuf
:param wp: MLModel.NeuralNetwork.WeightParam
WeightParam field
:param nbits: int
Number of bits to be quantized
:param qm: str
Quantization mode
:param shape: tuple
Tensor shape held by wp
:param axis: int
Axis over which quantization is performed on, can be either 0 or 1
:param lut_function: (``callable function``)
Python callable representing a LUT table function | [
"Quantize",
"WeightParam",
"field",
"in",
"Neural",
"Network",
"Protobuf"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py#L269-L336 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py | compare_models | def compare_models(full_precision_model, quantized_model,
sample_data):
"""
Utility function to compare the performance of a full precision vs quantized model
:param full_precision_model: MLModel
The full precision model with float32 weights
:param quantized_model: MLModel
Quantized version of the model with quantized weights
:param sample_data: str | [dict]
Data used to characterize performance of the quantized model in
comparison to the full precision model. Either a list of sample input
dictionaries or an absolute path to a directory containing images.
Path to a directory containing images is only valid for models with
one image input. For all other models a list of sample inputs must be
provided.
:return:
None. Performance metrics are printed out
"""
emessage = ("""
Invalid sample data provided. Only a list of dictionaries
containing sample data or path to a folder containing images is
supported""")
spec = full_precision_model.get_spec()
num_inputs = len(spec.description.input)
if isinstance(sample_data, str):
input_type = spec.description.input[0].type.WhichOneof('Type')
if num_inputs != 1 or input_type != 'imageType':
raise Exception("""Unable to analyze quantized models. Sample data
was a path to a directory which is only supported with models with
one image type input. Please try passing in a list of sample inputs
as sample data.
""")
_characterize_qmodel_perf_with_data_dir(full_precision_model, quantized_model.get_spec(), sample_data)
elif isinstance(sample_data, list):
if not all(type(d) is dict for d in sample_data):
raise Exception(emessage)
_characterize_quantized_model_perf(full_precision_model, quantized_model.get_spec(), sample_data)
else:
raise Exception(emessage) | python | def compare_models(full_precision_model, quantized_model,
sample_data):
"""
Utility function to compare the performance of a full precision vs quantized model
:param full_precision_model: MLModel
The full precision model with float32 weights
:param quantized_model: MLModel
Quantized version of the model with quantized weights
:param sample_data: str | [dict]
Data used to characterize performance of the quantized model in
comparison to the full precision model. Either a list of sample input
dictionaries or an absolute path to a directory containing images.
Path to a directory containing images is only valid for models with
one image input. For all other models a list of sample inputs must be
provided.
:return:
None. Performance metrics are printed out
"""
emessage = ("""
Invalid sample data provided. Only a list of dictionaries
containing sample data or path to a folder containing images is
supported""")
spec = full_precision_model.get_spec()
num_inputs = len(spec.description.input)
if isinstance(sample_data, str):
input_type = spec.description.input[0].type.WhichOneof('Type')
if num_inputs != 1 or input_type != 'imageType':
raise Exception("""Unable to analyze quantized models. Sample data
was a path to a directory which is only supported with models with
one image type input. Please try passing in a list of sample inputs
as sample data.
""")
_characterize_qmodel_perf_with_data_dir(full_precision_model, quantized_model.get_spec(), sample_data)
elif isinstance(sample_data, list):
if not all(type(d) is dict for d in sample_data):
raise Exception(emessage)
_characterize_quantized_model_perf(full_precision_model, quantized_model.get_spec(), sample_data)
else:
raise Exception(emessage) | [
"def",
"compare_models",
"(",
"full_precision_model",
",",
"quantized_model",
",",
"sample_data",
")",
":",
"emessage",
"=",
"(",
"\"\"\"\n Invalid sample data provided. Only a list of dictionaries\n containing sample data or path to a folder containing images is\n supported\"\"\"",
")",
"spec",
"=",
"full_precision_model",
".",
"get_spec",
"(",
")",
"num_inputs",
"=",
"len",
"(",
"spec",
".",
"description",
".",
"input",
")",
"if",
"isinstance",
"(",
"sample_data",
",",
"str",
")",
":",
"input_type",
"=",
"spec",
".",
"description",
".",
"input",
"[",
"0",
"]",
".",
"type",
".",
"WhichOneof",
"(",
"'Type'",
")",
"if",
"num_inputs",
"!=",
"1",
"or",
"input_type",
"!=",
"'imageType'",
":",
"raise",
"Exception",
"(",
"\"\"\"Unable to analyze quantized models. Sample data\n was a path to a directory which is only supported with models with\n one image type input. Please try passing in a list of sample inputs\n as sample data.\n \"\"\"",
")",
"_characterize_qmodel_perf_with_data_dir",
"(",
"full_precision_model",
",",
"quantized_model",
".",
"get_spec",
"(",
")",
",",
"sample_data",
")",
"elif",
"isinstance",
"(",
"sample_data",
",",
"list",
")",
":",
"if",
"not",
"all",
"(",
"type",
"(",
"d",
")",
"is",
"dict",
"for",
"d",
"in",
"sample_data",
")",
":",
"raise",
"Exception",
"(",
"emessage",
")",
"_characterize_quantized_model_perf",
"(",
"full_precision_model",
",",
"quantized_model",
".",
"get_spec",
"(",
")",
",",
"sample_data",
")",
"else",
":",
"raise",
"Exception",
"(",
"emessage",
")"
] | Utility function to compare the performance of a full precision vs quantized model
:param full_precision_model: MLModel
The full precision model with float32 weights
:param quantized_model: MLModel
Quantized version of the model with quantized weights
:param sample_data: str | [dict]
Data used to characterize performance of the quantized model in
comparison to the full precision model. Either a list of sample input
dictionaries or an absolute path to a directory containing images.
Path to a directory containing images is only valid for models with
one image input. For all other models a list of sample inputs must be
provided.
:return:
None. Performance metrics are printed out | [
"Utility",
"function",
"to",
"compare",
"the",
"performance",
"of",
"a",
"full",
"precision",
"vs",
"quantized",
"model"
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py#L829-L874 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py | quantize_weights | def quantize_weights(full_precision_model,
nbits,
quantization_mode="linear",
sample_data=None,
**kwargs):
"""
Utility function to convert a full precision (float) MLModel to a
nbit quantized MLModel (float16).
:param full_precision_model: MLModel
Model which will be converted to half precision. Currently conversion
for only neural network models is supported. If a pipeline model is
passed in then all embedded neural network models embedded within
will be converted.
:param nbits: Int
Number of bits per quantized weight. Only 8-bit and lower
quantization is supported
:param quantization_mode: str
One of:
"linear":
Simple linear quantization with scale and bias
"linear_lut":
Simple linear quantization represented as a lookup table
"kmeans_lut":
LUT based quantization, where LUT is generated by K-Means clustering
"custom_lut":
LUT quantization where LUT and quantized weight params are
calculated using a custom function. If this mode is selected then
a custom function must be passed in kwargs with key lut_function.
The function must have input params (nbits, wp) where nbits is the
number of quantization bits and wp is the list of weights for a
given layer. The function should return two parameters (lut, qw)
where lut is an array of length (2^nbits)containing LUT values and
qw is the list of quantized weight parameters. See
_get_linear_lookup_table_and_weight for a sample implementation.
:param sample_data: str | [dict]
Data used to characterize performance of the quantized model in
comparison to the full precision model. Either a list of sample input
dictionaries or an absolute path to a directory containing images.
Path to a directory containing images is only valid for models with
one image input. For all other models a list of sample inputs must be
provided.
:param **kwargs:
See below
:Keyword Arguments:
* *lut_function* (``callable function``) --
A callable function provided when quantization mode is set to
_QUANTIZATION_MODE_CUSTOM_LOOKUP_TABLE. See quantization_mode for
more details
Returns
-------
model: MLModel
The quantized MLModel instance if running on macOS 10.14 or later,
otherwise the quantized model specification is returned
Examples
--------
.. sourcecode:: python
>>> import coremltools
>>> from coremltools.models.neural_network import quantization_utils
>>> model = coremltools.models.MLModel('my_model.mlmodel')
>>> quantized_model = quantization_utils.quantize_weights(model, 8, "linear")
"""
qmode_mapping = {
"linear": _QUANTIZATION_MODE_LINEAR_QUANTIZATION,
"kmeans": _QUANTIZATION_MODE_LOOKUP_TABLE_KMEANS,
"linear_lut": _QUANTIZATION_MODE_LOOKUP_TABLE_LINEAR,
"custom_lut": _QUANTIZATION_MODE_CUSTOM_LOOKUP_TABLE,
"dequantization": _QUANTIZATION_MODE_DEQUANTIZE
}
try:
qmode = qmode_mapping[quantization_mode]
except KeyError:
raise Exception("Invalid quantization mode. Quantization mode must be "
"one of {}".format(qmode_mapping))
print("Quantizing using {} quantization".format(quantization_mode))
spec = full_precision_model.get_spec()
qspec = quantize_spec_weights(spec, nbits, qmode, **kwargs)
if macos_version() < (10, 14):
print("WARNING! Unable to return a quantized MLModel instance since OS != macOS 10.14 or later")
print("Returning quantized model specification instead")
return qspec
quantized_model = _get_model(qspec)
if not sample_data:
return quantized_model
compare_models(full_precision_model, quantized_model, sample_data)
return quantized_model | python | def quantize_weights(full_precision_model,
nbits,
quantization_mode="linear",
sample_data=None,
**kwargs):
"""
Utility function to convert a full precision (float) MLModel to a
nbit quantized MLModel (float16).
:param full_precision_model: MLModel
Model which will be converted to half precision. Currently conversion
for only neural network models is supported. If a pipeline model is
passed in then all embedded neural network models embedded within
will be converted.
:param nbits: Int
Number of bits per quantized weight. Only 8-bit and lower
quantization is supported
:param quantization_mode: str
One of:
"linear":
Simple linear quantization with scale and bias
"linear_lut":
Simple linear quantization represented as a lookup table
"kmeans_lut":
LUT based quantization, where LUT is generated by K-Means clustering
"custom_lut":
LUT quantization where LUT and quantized weight params are
calculated using a custom function. If this mode is selected then
a custom function must be passed in kwargs with key lut_function.
The function must have input params (nbits, wp) where nbits is the
number of quantization bits and wp is the list of weights for a
given layer. The function should return two parameters (lut, qw)
where lut is an array of length (2^nbits)containing LUT values and
qw is the list of quantized weight parameters. See
_get_linear_lookup_table_and_weight for a sample implementation.
:param sample_data: str | [dict]
Data used to characterize performance of the quantized model in
comparison to the full precision model. Either a list of sample input
dictionaries or an absolute path to a directory containing images.
Path to a directory containing images is only valid for models with
one image input. For all other models a list of sample inputs must be
provided.
:param **kwargs:
See below
:Keyword Arguments:
* *lut_function* (``callable function``) --
A callable function provided when quantization mode is set to
_QUANTIZATION_MODE_CUSTOM_LOOKUP_TABLE. See quantization_mode for
more details
Returns
-------
model: MLModel
The quantized MLModel instance if running on macOS 10.14 or later,
otherwise the quantized model specification is returned
Examples
--------
.. sourcecode:: python
>>> import coremltools
>>> from coremltools.models.neural_network import quantization_utils
>>> model = coremltools.models.MLModel('my_model.mlmodel')
>>> quantized_model = quantization_utils.quantize_weights(model, 8, "linear")
"""
qmode_mapping = {
"linear": _QUANTIZATION_MODE_LINEAR_QUANTIZATION,
"kmeans": _QUANTIZATION_MODE_LOOKUP_TABLE_KMEANS,
"linear_lut": _QUANTIZATION_MODE_LOOKUP_TABLE_LINEAR,
"custom_lut": _QUANTIZATION_MODE_CUSTOM_LOOKUP_TABLE,
"dequantization": _QUANTIZATION_MODE_DEQUANTIZE
}
try:
qmode = qmode_mapping[quantization_mode]
except KeyError:
raise Exception("Invalid quantization mode. Quantization mode must be "
"one of {}".format(qmode_mapping))
print("Quantizing using {} quantization".format(quantization_mode))
spec = full_precision_model.get_spec()
qspec = quantize_spec_weights(spec, nbits, qmode, **kwargs)
if macos_version() < (10, 14):
print("WARNING! Unable to return a quantized MLModel instance since OS != macOS 10.14 or later")
print("Returning quantized model specification instead")
return qspec
quantized_model = _get_model(qspec)
if not sample_data:
return quantized_model
compare_models(full_precision_model, quantized_model, sample_data)
return quantized_model | [
"def",
"quantize_weights",
"(",
"full_precision_model",
",",
"nbits",
",",
"quantization_mode",
"=",
"\"linear\"",
",",
"sample_data",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"qmode_mapping",
"=",
"{",
"\"linear\"",
":",
"_QUANTIZATION_MODE_LINEAR_QUANTIZATION",
",",
"\"kmeans\"",
":",
"_QUANTIZATION_MODE_LOOKUP_TABLE_KMEANS",
",",
"\"linear_lut\"",
":",
"_QUANTIZATION_MODE_LOOKUP_TABLE_LINEAR",
",",
"\"custom_lut\"",
":",
"_QUANTIZATION_MODE_CUSTOM_LOOKUP_TABLE",
",",
"\"dequantization\"",
":",
"_QUANTIZATION_MODE_DEQUANTIZE",
"}",
"try",
":",
"qmode",
"=",
"qmode_mapping",
"[",
"quantization_mode",
"]",
"except",
"KeyError",
":",
"raise",
"Exception",
"(",
"\"Invalid quantization mode. Quantization mode must be \"",
"\"one of {}\"",
".",
"format",
"(",
"qmode_mapping",
")",
")",
"print",
"(",
"\"Quantizing using {} quantization\"",
".",
"format",
"(",
"quantization_mode",
")",
")",
"spec",
"=",
"full_precision_model",
".",
"get_spec",
"(",
")",
"qspec",
"=",
"quantize_spec_weights",
"(",
"spec",
",",
"nbits",
",",
"qmode",
",",
"*",
"*",
"kwargs",
")",
"if",
"macos_version",
"(",
")",
"<",
"(",
"10",
",",
"14",
")",
":",
"print",
"(",
"\"WARNING! Unable to return a quantized MLModel instance since OS != macOS 10.14 or later\"",
")",
"print",
"(",
"\"Returning quantized model specification instead\"",
")",
"return",
"qspec",
"quantized_model",
"=",
"_get_model",
"(",
"qspec",
")",
"if",
"not",
"sample_data",
":",
"return",
"quantized_model",
"compare_models",
"(",
"full_precision_model",
",",
"quantized_model",
",",
"sample_data",
")",
"return",
"quantized_model"
] | Utility function to convert a full precision (float) MLModel to a
nbit quantized MLModel (float16).
:param full_precision_model: MLModel
Model which will be converted to half precision. Currently conversion
for only neural network models is supported. If a pipeline model is
passed in then all embedded neural network models embedded within
will be converted.
:param nbits: Int
Number of bits per quantized weight. Only 8-bit and lower
quantization is supported
:param quantization_mode: str
One of:
"linear":
Simple linear quantization with scale and bias
"linear_lut":
Simple linear quantization represented as a lookup table
"kmeans_lut":
LUT based quantization, where LUT is generated by K-Means clustering
"custom_lut":
LUT quantization where LUT and quantized weight params are
calculated using a custom function. If this mode is selected then
a custom function must be passed in kwargs with key lut_function.
The function must have input params (nbits, wp) where nbits is the
number of quantization bits and wp is the list of weights for a
given layer. The function should return two parameters (lut, qw)
where lut is an array of length (2^nbits)containing LUT values and
qw is the list of quantized weight parameters. See
_get_linear_lookup_table_and_weight for a sample implementation.
:param sample_data: str | [dict]
Data used to characterize performance of the quantized model in
comparison to the full precision model. Either a list of sample input
dictionaries or an absolute path to a directory containing images.
Path to a directory containing images is only valid for models with
one image input. For all other models a list of sample inputs must be
provided.
:param **kwargs:
See below
:Keyword Arguments:
* *lut_function* (``callable function``) --
A callable function provided when quantization mode is set to
_QUANTIZATION_MODE_CUSTOM_LOOKUP_TABLE. See quantization_mode for
more details
Returns
-------
model: MLModel
The quantized MLModel instance if running on macOS 10.14 or later,
otherwise the quantized model specification is returned
Examples
--------
.. sourcecode:: python
>>> import coremltools
>>> from coremltools.models.neural_network import quantization_utils
>>> model = coremltools.models.MLModel('my_model.mlmodel')
>>> quantized_model = quantization_utils.quantize_weights(model, 8, "linear") | [
"Utility",
"function",
"to",
"convert",
"a",
"full",
"precision",
"(",
"float",
")",
"MLModel",
"to",
"a",
"nbit",
"quantized",
"MLModel",
"(",
"float16",
")",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/models/neural_network/quantization_utils.py#L877-L977 | train |
apple/turicreate | src/unity/python/turicreate/toolkits/recommender/item_similarity_recommender.py | create | def create(observation_data,
user_id='user_id', item_id='item_id', target=None,
user_data=None, item_data=None,
nearest_items=None,
similarity_type='jaccard',
threshold=0.001,
only_top_k=64,
verbose=True,
target_memory_usage = 8*1024*1024*1024,
**kwargs):
"""
Create a recommender that uses item-item similarities based on
users in common.
Parameters
----------
observation_data : SFrame
The dataset to use for training the model. It must contain a column of
user ids and a column of item ids. Each row represents an observed
interaction between the user and the item. The (user, item) pairs
are stored with the model so that they can later be excluded from
recommendations if desired. It can optionally contain a target ratings
column. All other columns are interpreted by the underlying model as
side features for the observations.
The user id and item id columns must be of type 'int' or 'str'. The
target column must be of type 'int' or 'float'.
user_id : string, optional
The name of the column in `observation_data` that corresponds to the
user id.
item_id : string, optional
The name of the column in `observation_data` that corresponds to the
item id.
target : string, optional
The `observation_data` can optionally contain a column of scores
representing ratings given by the users. If present, the name of this
column may be specified variables `target`.
user_data : SFrame, optional
Side information for the users. This SFrame must have a column with
the same name as what is specified by the `user_id` input parameter.
`user_data` can provide any amount of additional user-specific
information. (NB: This argument is currently ignored by this model.)
item_data : SFrame, optional
Side information for the items. This SFrame must have a column with
the same name as what is specified by the `item_id` input parameter.
`item_data` can provide any amount of additional item-specific
information. (NB: This argument is currently ignored by this model.)
similarity_type : {'jaccard', 'cosine', 'pearson'}, optional
Similarity metric to use. See ItemSimilarityRecommender for details.
Default: 'jaccard'.
threshold : float, optional
Predictions ignore items below this similarity value.
Default: 0.001.
only_top_k : int, optional
Number of similar items to store for each item. Default value is
64. Decreasing this decreases the amount of memory required for the
model, but may also decrease the accuracy.
nearest_items : SFrame, optional
A set of each item's nearest items. When provided, this overrides
the similarity computed above.
See Notes in the documentation for ItemSimilarityRecommender.
Default: None.
target_memory_usage : int, optional
The target memory usage for the processing buffers and lookup
tables. The actual memory usage may be higher or lower than this,
but decreasing this decreases memory usage at the expense of
training time, and increasing this can dramatically speed up the
training time. Default is 8GB = 8589934592.
seed_item_set_size : int, optional
For users that have not yet rated any items, or have only
rated uniquely occurring items with no similar item info,
the model seeds the user's item set with the average
ratings of the seed_item_set_size most popular items when
making predictions and recommendations. If set to 0, then
recommendations based on either popularity (no target present)
or average item score (target present) are made in this case.
training_method : (advanced), optional.
The internal processing is done with a combination of nearest
neighbor searching, dense tables for tracking item-item
similarities, and sparse item-item tables. If 'auto' is chosen
(default), then the estimated computation time is estimated for
each, and the computation balanced between the methods in order to
minimize training time given the target memory usage. This allows
the user to force the use of one of these methods. All should give
equivalent results; the only difference would be training time.
Possible values are {'auto', 'dense', 'sparse', 'nn', 'nn:dense',
'nn:sparse'}. 'dense' uses a dense matrix to store item-item
interactions as a lookup, and may do multiple passes to control
memory requirements. 'sparse' does the same but with a sparse lookup
table; this is better if the data has many infrequent items. "nn"
uses a brute-force nearest neighbors search. "nn:dense" and
"nn:sparse" use nearest neighbors for the most frequent items
(see nearest_neighbors_interaction_proportion_threshold below),
and either sparse or dense matrices for the remainder. "auto"
chooses the method predicted to be the fastest based on the
properties of the data.
nearest_neighbors_interaction_proportion_threshold : (advanced) float
Any item that has was rated by more than this proportion of
users is treated by doing a nearest neighbors search. For
frequent items, this is almost always faster, but it is slower
for infrequent items. Furthermore, decreasing this causes more
items to be processed using the nearest neighbor path, which may
decrease memory requirements.
degree_approximation_threshold : (advanced) int, optional
Users with more than this many item interactions may be
approximated. The approximation is done by a combination of
sampling and choosing the interactions likely to have the most
impact on the model. Increasing this can increase the training time
and may or may not increase the quality of the model. Default = 4096.
max_data_passes : (advanced) int, optional
The maximum number of passes through the data allowed in
building the similarity lookup tables. If it is not possible to
build the recommender in this many passes (calculated before
that stage of training), then additional approximations are
applied; namely decreasing degree_approximation_threshold. If
this is not possible, an error is raised. To decrease the
number of passes required, increase target_memory_usage or
decrease nearest_neighbors_interaction_proportion_threshold.
Default = 1024.
Examples
--------
Given basic user-item observation data, an
:class:`~turicreate.recommender.item_similarity_recommender.ItemSimilarityRecommender` is created:
>>> sf = turicreate.SFrame({'user_id': ['0', '0', '0', '1', '1', '2', '2', '2'],
... 'item_id': ['a', 'b', 'c', 'a', 'b', 'b', 'c', 'd']})
>>> m = turicreate.item_similarity_recommender.create(sf)
>>> recs = m.recommend()
When a target is available, one can specify the desired similarity. For
example we may choose to use a cosine similarity, and use it to make
predictions or recommendations.
>>> sf2 = turicreate.SFrame({'user_id': ['0', '0', '0', '1', '1', '2', '2', '2'],
... 'item_id': ['a', 'b', 'c', 'a', 'b', 'b', 'c', 'd'],
... 'rating': [1, 3, 2, 5, 4, 1, 4, 3]})
>>> m2 = turicreate.item_similarity_recommender.create(sf2, target="rating",
... similarity_type='cosine')
>>> m2.predict(sf)
>>> m2.recommend()
Notes
-----
Currently, :class:`~turicreate.recommender.item_similarity_recommender.ItemSimilarityRecommender`
does not leverage the use of side features `user_data` and `item_data`.
**Incorporating pre-defined similar items**
For item similarity models, one may choose to provide user-specified
nearest neighbors graph using the keyword argument `nearest_items`. This is
an SFrame containing, for each item, the nearest items and the similarity
score between them. If provided, these item similarity scores are used for
recommendations. The SFrame must contain (at least) three columns:
* 'item_id': a column with the same name as that provided to the `item_id`
argument (which defaults to the string "item_id").
* 'similar': a column containing the nearest items for the given item id.
This should have the same type as the `item_id` column.
* 'score': a numeric score measuring how similar these two items are.
For example, suppose you first create an ItemSimilarityRecommender and use
:class:`~turicreate.recommender.ItemSimilarityRecommender.get_similar_items`:
>>> sf = turicreate.SFrame({'user_id': ["0", "0", "0", "1", "1", "2", "2", "2"],
... 'item_id': ["a", "b", "c", "a", "b", "b", "c", "d"]})
>>> m = turicreate.item_similarity_recommender.create(sf)
>>> nn = m.get_similar_items()
>>> m2 = turicreate.item_similarity_recommender.create(sf, nearest_items=nn)
With the above code, the item similarities computed for model `m` can be
used to create a new recommender object, `m2`. Note that we could have
created `nn` from some other means, but now use `m2` to make
recommendations via `m2.recommend()`.
See Also
--------
ItemSimilarityRecommender
"""
from turicreate._cython.cy_server import QuietProgress
opts = {}
model_proxy = _turicreate.extensions.item_similarity()
model_proxy.init_options(opts)
if user_data is None:
user_data = _turicreate.SFrame()
if item_data is None:
item_data = _turicreate.SFrame()
if nearest_items is None:
nearest_items = _turicreate.SFrame()
if "training_method" in kwargs and kwargs["training_method"] in ["in_memory", "sgraph"]:
print("WARNING: training_method = " + str(kwargs["training_method"]) + " deprecated; see documentation.")
kwargs["training_method"] = "auto"
opts = {'user_id': user_id,
'item_id': item_id,
'target': target,
'similarity_type': similarity_type,
'threshold': threshold,
'target_memory_usage' : float(target_memory_usage),
'max_item_neighborhood_size': only_top_k}
extra_data = {"nearest_items" : nearest_items}
if kwargs:
try:
possible_args = set(_get_default_options()["name"])
except (RuntimeError, KeyError):
possible_args = set()
bad_arguments = set(kwargs.keys()).difference(possible_args)
if bad_arguments:
raise TypeError("Bad Keyword Arguments: " + ', '.join(bad_arguments))
opts.update(kwargs)
extra_data = {"nearest_items" : nearest_items}
opts.update(kwargs)
with QuietProgress(verbose):
model_proxy.train(observation_data, user_data, item_data, opts, extra_data)
return ItemSimilarityRecommender(model_proxy) | python | def create(observation_data,
user_id='user_id', item_id='item_id', target=None,
user_data=None, item_data=None,
nearest_items=None,
similarity_type='jaccard',
threshold=0.001,
only_top_k=64,
verbose=True,
target_memory_usage = 8*1024*1024*1024,
**kwargs):
"""
Create a recommender that uses item-item similarities based on
users in common.
Parameters
----------
observation_data : SFrame
The dataset to use for training the model. It must contain a column of
user ids and a column of item ids. Each row represents an observed
interaction between the user and the item. The (user, item) pairs
are stored with the model so that they can later be excluded from
recommendations if desired. It can optionally contain a target ratings
column. All other columns are interpreted by the underlying model as
side features for the observations.
The user id and item id columns must be of type 'int' or 'str'. The
target column must be of type 'int' or 'float'.
user_id : string, optional
The name of the column in `observation_data` that corresponds to the
user id.
item_id : string, optional
The name of the column in `observation_data` that corresponds to the
item id.
target : string, optional
The `observation_data` can optionally contain a column of scores
representing ratings given by the users. If present, the name of this
column may be specified variables `target`.
user_data : SFrame, optional
Side information for the users. This SFrame must have a column with
the same name as what is specified by the `user_id` input parameter.
`user_data` can provide any amount of additional user-specific
information. (NB: This argument is currently ignored by this model.)
item_data : SFrame, optional
Side information for the items. This SFrame must have a column with
the same name as what is specified by the `item_id` input parameter.
`item_data` can provide any amount of additional item-specific
information. (NB: This argument is currently ignored by this model.)
similarity_type : {'jaccard', 'cosine', 'pearson'}, optional
Similarity metric to use. See ItemSimilarityRecommender for details.
Default: 'jaccard'.
threshold : float, optional
Predictions ignore items below this similarity value.
Default: 0.001.
only_top_k : int, optional
Number of similar items to store for each item. Default value is
64. Decreasing this decreases the amount of memory required for the
model, but may also decrease the accuracy.
nearest_items : SFrame, optional
A set of each item's nearest items. When provided, this overrides
the similarity computed above.
See Notes in the documentation for ItemSimilarityRecommender.
Default: None.
target_memory_usage : int, optional
The target memory usage for the processing buffers and lookup
tables. The actual memory usage may be higher or lower than this,
but decreasing this decreases memory usage at the expense of
training time, and increasing this can dramatically speed up the
training time. Default is 8GB = 8589934592.
seed_item_set_size : int, optional
For users that have not yet rated any items, or have only
rated uniquely occurring items with no similar item info,
the model seeds the user's item set with the average
ratings of the seed_item_set_size most popular items when
making predictions and recommendations. If set to 0, then
recommendations based on either popularity (no target present)
or average item score (target present) are made in this case.
training_method : (advanced), optional.
The internal processing is done with a combination of nearest
neighbor searching, dense tables for tracking item-item
similarities, and sparse item-item tables. If 'auto' is chosen
(default), then the estimated computation time is estimated for
each, and the computation balanced between the methods in order to
minimize training time given the target memory usage. This allows
the user to force the use of one of these methods. All should give
equivalent results; the only difference would be training time.
Possible values are {'auto', 'dense', 'sparse', 'nn', 'nn:dense',
'nn:sparse'}. 'dense' uses a dense matrix to store item-item
interactions as a lookup, and may do multiple passes to control
memory requirements. 'sparse' does the same but with a sparse lookup
table; this is better if the data has many infrequent items. "nn"
uses a brute-force nearest neighbors search. "nn:dense" and
"nn:sparse" use nearest neighbors for the most frequent items
(see nearest_neighbors_interaction_proportion_threshold below),
and either sparse or dense matrices for the remainder. "auto"
chooses the method predicted to be the fastest based on the
properties of the data.
nearest_neighbors_interaction_proportion_threshold : (advanced) float
Any item that has was rated by more than this proportion of
users is treated by doing a nearest neighbors search. For
frequent items, this is almost always faster, but it is slower
for infrequent items. Furthermore, decreasing this causes more
items to be processed using the nearest neighbor path, which may
decrease memory requirements.
degree_approximation_threshold : (advanced) int, optional
Users with more than this many item interactions may be
approximated. The approximation is done by a combination of
sampling and choosing the interactions likely to have the most
impact on the model. Increasing this can increase the training time
and may or may not increase the quality of the model. Default = 4096.
max_data_passes : (advanced) int, optional
The maximum number of passes through the data allowed in
building the similarity lookup tables. If it is not possible to
build the recommender in this many passes (calculated before
that stage of training), then additional approximations are
applied; namely decreasing degree_approximation_threshold. If
this is not possible, an error is raised. To decrease the
number of passes required, increase target_memory_usage or
decrease nearest_neighbors_interaction_proportion_threshold.
Default = 1024.
Examples
--------
Given basic user-item observation data, an
:class:`~turicreate.recommender.item_similarity_recommender.ItemSimilarityRecommender` is created:
>>> sf = turicreate.SFrame({'user_id': ['0', '0', '0', '1', '1', '2', '2', '2'],
... 'item_id': ['a', 'b', 'c', 'a', 'b', 'b', 'c', 'd']})
>>> m = turicreate.item_similarity_recommender.create(sf)
>>> recs = m.recommend()
When a target is available, one can specify the desired similarity. For
example we may choose to use a cosine similarity, and use it to make
predictions or recommendations.
>>> sf2 = turicreate.SFrame({'user_id': ['0', '0', '0', '1', '1', '2', '2', '2'],
... 'item_id': ['a', 'b', 'c', 'a', 'b', 'b', 'c', 'd'],
... 'rating': [1, 3, 2, 5, 4, 1, 4, 3]})
>>> m2 = turicreate.item_similarity_recommender.create(sf2, target="rating",
... similarity_type='cosine')
>>> m2.predict(sf)
>>> m2.recommend()
Notes
-----
Currently, :class:`~turicreate.recommender.item_similarity_recommender.ItemSimilarityRecommender`
does not leverage the use of side features `user_data` and `item_data`.
**Incorporating pre-defined similar items**
For item similarity models, one may choose to provide user-specified
nearest neighbors graph using the keyword argument `nearest_items`. This is
an SFrame containing, for each item, the nearest items and the similarity
score between them. If provided, these item similarity scores are used for
recommendations. The SFrame must contain (at least) three columns:
* 'item_id': a column with the same name as that provided to the `item_id`
argument (which defaults to the string "item_id").
* 'similar': a column containing the nearest items for the given item id.
This should have the same type as the `item_id` column.
* 'score': a numeric score measuring how similar these two items are.
For example, suppose you first create an ItemSimilarityRecommender and use
:class:`~turicreate.recommender.ItemSimilarityRecommender.get_similar_items`:
>>> sf = turicreate.SFrame({'user_id': ["0", "0", "0", "1", "1", "2", "2", "2"],
... 'item_id': ["a", "b", "c", "a", "b", "b", "c", "d"]})
>>> m = turicreate.item_similarity_recommender.create(sf)
>>> nn = m.get_similar_items()
>>> m2 = turicreate.item_similarity_recommender.create(sf, nearest_items=nn)
With the above code, the item similarities computed for model `m` can be
used to create a new recommender object, `m2`. Note that we could have
created `nn` from some other means, but now use `m2` to make
recommendations via `m2.recommend()`.
See Also
--------
ItemSimilarityRecommender
"""
from turicreate._cython.cy_server import QuietProgress
opts = {}
model_proxy = _turicreate.extensions.item_similarity()
model_proxy.init_options(opts)
if user_data is None:
user_data = _turicreate.SFrame()
if item_data is None:
item_data = _turicreate.SFrame()
if nearest_items is None:
nearest_items = _turicreate.SFrame()
if "training_method" in kwargs and kwargs["training_method"] in ["in_memory", "sgraph"]:
print("WARNING: training_method = " + str(kwargs["training_method"]) + " deprecated; see documentation.")
kwargs["training_method"] = "auto"
opts = {'user_id': user_id,
'item_id': item_id,
'target': target,
'similarity_type': similarity_type,
'threshold': threshold,
'target_memory_usage' : float(target_memory_usage),
'max_item_neighborhood_size': only_top_k}
extra_data = {"nearest_items" : nearest_items}
if kwargs:
try:
possible_args = set(_get_default_options()["name"])
except (RuntimeError, KeyError):
possible_args = set()
bad_arguments = set(kwargs.keys()).difference(possible_args)
if bad_arguments:
raise TypeError("Bad Keyword Arguments: " + ', '.join(bad_arguments))
opts.update(kwargs)
extra_data = {"nearest_items" : nearest_items}
opts.update(kwargs)
with QuietProgress(verbose):
model_proxy.train(observation_data, user_data, item_data, opts, extra_data)
return ItemSimilarityRecommender(model_proxy) | [
"def",
"create",
"(",
"observation_data",
",",
"user_id",
"=",
"'user_id'",
",",
"item_id",
"=",
"'item_id'",
",",
"target",
"=",
"None",
",",
"user_data",
"=",
"None",
",",
"item_data",
"=",
"None",
",",
"nearest_items",
"=",
"None",
",",
"similarity_type",
"=",
"'jaccard'",
",",
"threshold",
"=",
"0.001",
",",
"only_top_k",
"=",
"64",
",",
"verbose",
"=",
"True",
",",
"target_memory_usage",
"=",
"8",
"*",
"1024",
"*",
"1024",
"*",
"1024",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"turicreate",
".",
"_cython",
".",
"cy_server",
"import",
"QuietProgress",
"opts",
"=",
"{",
"}",
"model_proxy",
"=",
"_turicreate",
".",
"extensions",
".",
"item_similarity",
"(",
")",
"model_proxy",
".",
"init_options",
"(",
"opts",
")",
"if",
"user_data",
"is",
"None",
":",
"user_data",
"=",
"_turicreate",
".",
"SFrame",
"(",
")",
"if",
"item_data",
"is",
"None",
":",
"item_data",
"=",
"_turicreate",
".",
"SFrame",
"(",
")",
"if",
"nearest_items",
"is",
"None",
":",
"nearest_items",
"=",
"_turicreate",
".",
"SFrame",
"(",
")",
"if",
"\"training_method\"",
"in",
"kwargs",
"and",
"kwargs",
"[",
"\"training_method\"",
"]",
"in",
"[",
"\"in_memory\"",
",",
"\"sgraph\"",
"]",
":",
"print",
"(",
"\"WARNING: training_method = \"",
"+",
"str",
"(",
"kwargs",
"[",
"\"training_method\"",
"]",
")",
"+",
"\" deprecated; see documentation.\"",
")",
"kwargs",
"[",
"\"training_method\"",
"]",
"=",
"\"auto\"",
"opts",
"=",
"{",
"'user_id'",
":",
"user_id",
",",
"'item_id'",
":",
"item_id",
",",
"'target'",
":",
"target",
",",
"'similarity_type'",
":",
"similarity_type",
",",
"'threshold'",
":",
"threshold",
",",
"'target_memory_usage'",
":",
"float",
"(",
"target_memory_usage",
")",
",",
"'max_item_neighborhood_size'",
":",
"only_top_k",
"}",
"extra_data",
"=",
"{",
"\"nearest_items\"",
":",
"nearest_items",
"}",
"if",
"kwargs",
":",
"try",
":",
"possible_args",
"=",
"set",
"(",
"_get_default_options",
"(",
")",
"[",
"\"name\"",
"]",
")",
"except",
"(",
"RuntimeError",
",",
"KeyError",
")",
":",
"possible_args",
"=",
"set",
"(",
")",
"bad_arguments",
"=",
"set",
"(",
"kwargs",
".",
"keys",
"(",
")",
")",
".",
"difference",
"(",
"possible_args",
")",
"if",
"bad_arguments",
":",
"raise",
"TypeError",
"(",
"\"Bad Keyword Arguments: \"",
"+",
"', '",
".",
"join",
"(",
"bad_arguments",
")",
")",
"opts",
".",
"update",
"(",
"kwargs",
")",
"extra_data",
"=",
"{",
"\"nearest_items\"",
":",
"nearest_items",
"}",
"opts",
".",
"update",
"(",
"kwargs",
")",
"with",
"QuietProgress",
"(",
"verbose",
")",
":",
"model_proxy",
".",
"train",
"(",
"observation_data",
",",
"user_data",
",",
"item_data",
",",
"opts",
",",
"extra_data",
")",
"return",
"ItemSimilarityRecommender",
"(",
"model_proxy",
")"
] | Create a recommender that uses item-item similarities based on
users in common.
Parameters
----------
observation_data : SFrame
The dataset to use for training the model. It must contain a column of
user ids and a column of item ids. Each row represents an observed
interaction between the user and the item. The (user, item) pairs
are stored with the model so that they can later be excluded from
recommendations if desired. It can optionally contain a target ratings
column. All other columns are interpreted by the underlying model as
side features for the observations.
The user id and item id columns must be of type 'int' or 'str'. The
target column must be of type 'int' or 'float'.
user_id : string, optional
The name of the column in `observation_data` that corresponds to the
user id.
item_id : string, optional
The name of the column in `observation_data` that corresponds to the
item id.
target : string, optional
The `observation_data` can optionally contain a column of scores
representing ratings given by the users. If present, the name of this
column may be specified variables `target`.
user_data : SFrame, optional
Side information for the users. This SFrame must have a column with
the same name as what is specified by the `user_id` input parameter.
`user_data` can provide any amount of additional user-specific
information. (NB: This argument is currently ignored by this model.)
item_data : SFrame, optional
Side information for the items. This SFrame must have a column with
the same name as what is specified by the `item_id` input parameter.
`item_data` can provide any amount of additional item-specific
information. (NB: This argument is currently ignored by this model.)
similarity_type : {'jaccard', 'cosine', 'pearson'}, optional
Similarity metric to use. See ItemSimilarityRecommender for details.
Default: 'jaccard'.
threshold : float, optional
Predictions ignore items below this similarity value.
Default: 0.001.
only_top_k : int, optional
Number of similar items to store for each item. Default value is
64. Decreasing this decreases the amount of memory required for the
model, but may also decrease the accuracy.
nearest_items : SFrame, optional
A set of each item's nearest items. When provided, this overrides
the similarity computed above.
See Notes in the documentation for ItemSimilarityRecommender.
Default: None.
target_memory_usage : int, optional
The target memory usage for the processing buffers and lookup
tables. The actual memory usage may be higher or lower than this,
but decreasing this decreases memory usage at the expense of
training time, and increasing this can dramatically speed up the
training time. Default is 8GB = 8589934592.
seed_item_set_size : int, optional
For users that have not yet rated any items, or have only
rated uniquely occurring items with no similar item info,
the model seeds the user's item set with the average
ratings of the seed_item_set_size most popular items when
making predictions and recommendations. If set to 0, then
recommendations based on either popularity (no target present)
or average item score (target present) are made in this case.
training_method : (advanced), optional.
The internal processing is done with a combination of nearest
neighbor searching, dense tables for tracking item-item
similarities, and sparse item-item tables. If 'auto' is chosen
(default), then the estimated computation time is estimated for
each, and the computation balanced between the methods in order to
minimize training time given the target memory usage. This allows
the user to force the use of one of these methods. All should give
equivalent results; the only difference would be training time.
Possible values are {'auto', 'dense', 'sparse', 'nn', 'nn:dense',
'nn:sparse'}. 'dense' uses a dense matrix to store item-item
interactions as a lookup, and may do multiple passes to control
memory requirements. 'sparse' does the same but with a sparse lookup
table; this is better if the data has many infrequent items. "nn"
uses a brute-force nearest neighbors search. "nn:dense" and
"nn:sparse" use nearest neighbors for the most frequent items
(see nearest_neighbors_interaction_proportion_threshold below),
and either sparse or dense matrices for the remainder. "auto"
chooses the method predicted to be the fastest based on the
properties of the data.
nearest_neighbors_interaction_proportion_threshold : (advanced) float
Any item that has was rated by more than this proportion of
users is treated by doing a nearest neighbors search. For
frequent items, this is almost always faster, but it is slower
for infrequent items. Furthermore, decreasing this causes more
items to be processed using the nearest neighbor path, which may
decrease memory requirements.
degree_approximation_threshold : (advanced) int, optional
Users with more than this many item interactions may be
approximated. The approximation is done by a combination of
sampling and choosing the interactions likely to have the most
impact on the model. Increasing this can increase the training time
and may or may not increase the quality of the model. Default = 4096.
max_data_passes : (advanced) int, optional
The maximum number of passes through the data allowed in
building the similarity lookup tables. If it is not possible to
build the recommender in this many passes (calculated before
that stage of training), then additional approximations are
applied; namely decreasing degree_approximation_threshold. If
this is not possible, an error is raised. To decrease the
number of passes required, increase target_memory_usage or
decrease nearest_neighbors_interaction_proportion_threshold.
Default = 1024.
Examples
--------
Given basic user-item observation data, an
:class:`~turicreate.recommender.item_similarity_recommender.ItemSimilarityRecommender` is created:
>>> sf = turicreate.SFrame({'user_id': ['0', '0', '0', '1', '1', '2', '2', '2'],
... 'item_id': ['a', 'b', 'c', 'a', 'b', 'b', 'c', 'd']})
>>> m = turicreate.item_similarity_recommender.create(sf)
>>> recs = m.recommend()
When a target is available, one can specify the desired similarity. For
example we may choose to use a cosine similarity, and use it to make
predictions or recommendations.
>>> sf2 = turicreate.SFrame({'user_id': ['0', '0', '0', '1', '1', '2', '2', '2'],
... 'item_id': ['a', 'b', 'c', 'a', 'b', 'b', 'c', 'd'],
... 'rating': [1, 3, 2, 5, 4, 1, 4, 3]})
>>> m2 = turicreate.item_similarity_recommender.create(sf2, target="rating",
... similarity_type='cosine')
>>> m2.predict(sf)
>>> m2.recommend()
Notes
-----
Currently, :class:`~turicreate.recommender.item_similarity_recommender.ItemSimilarityRecommender`
does not leverage the use of side features `user_data` and `item_data`.
**Incorporating pre-defined similar items**
For item similarity models, one may choose to provide user-specified
nearest neighbors graph using the keyword argument `nearest_items`. This is
an SFrame containing, for each item, the nearest items and the similarity
score between them. If provided, these item similarity scores are used for
recommendations. The SFrame must contain (at least) three columns:
* 'item_id': a column with the same name as that provided to the `item_id`
argument (which defaults to the string "item_id").
* 'similar': a column containing the nearest items for the given item id.
This should have the same type as the `item_id` column.
* 'score': a numeric score measuring how similar these two items are.
For example, suppose you first create an ItemSimilarityRecommender and use
:class:`~turicreate.recommender.ItemSimilarityRecommender.get_similar_items`:
>>> sf = turicreate.SFrame({'user_id': ["0", "0", "0", "1", "1", "2", "2", "2"],
... 'item_id': ["a", "b", "c", "a", "b", "b", "c", "d"]})
>>> m = turicreate.item_similarity_recommender.create(sf)
>>> nn = m.get_similar_items()
>>> m2 = turicreate.item_similarity_recommender.create(sf, nearest_items=nn)
With the above code, the item similarities computed for model `m` can be
used to create a new recommender object, `m2`. Note that we could have
created `nn` from some other means, but now use `m2` to make
recommendations via `m2.recommend()`.
See Also
--------
ItemSimilarityRecommender | [
"Create",
"a",
"recommender",
"that",
"uses",
"item",
"-",
"item",
"similarities",
"based",
"on",
"users",
"in",
"common",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/recommender/item_similarity_recommender.py#L17-L259 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers2.py | _get_elementwise_name_from_keras_layer | def _get_elementwise_name_from_keras_layer(keras_layer):
"""
Get the keras layer name from the activation name.
"""
if isinstance(keras_layer, _keras.layers.Add):
return 'ADD'
elif isinstance(keras_layer, _keras.layers.Multiply):
return 'MULTIPLY'
elif isinstance(keras_layer, _keras.layers.Concatenate):
if len(keras_layer.input_shape[0]) == 3 and (keras_layer.axis == 1 or keras_layer.axis == -2):
return 'SEQUENCE_CONCAT'
elif len(keras_layer.input_shape[0]) == 4 and (keras_layer.axis == 3 or keras_layer.axis == -1):
return 'CONCAT'
elif len(keras_layer.input_shape[0]) == 2 and (keras_layer.axis == 1 or keras_layer.axis == -1):
return 'CONCAT'
else:
raise ValueError('Only channel and sequence concatenation are supported.')
elif isinstance(keras_layer, _keras.layers.Dot):
if len(keras_layer.input_shape[0]) == 2:
if type(keras_layer.axes) is list or type(keras_layer.axes) is tuple:
if len(keras_layer.axes) > 1:
raise ValueError('Only vector dot-product is supported.')
else:
axis = keras_layer.axes[0]
else:
axis = keras_layer.axes
if axis != -1 and axis != 1:
raise ValueError('Only vector dot-product is supported.')
if keras_layer.normalize:
return 'COS'
else:
return 'DOT'
else:
raise ValueError('Only vector dot-product is supported.')
elif isinstance(keras_layer, _keras.layers.Maximum):
return 'MAX'
elif isinstance(keras_layer, _keras.layers.Average):
return 'AVE'
else:
_utils.raise_error_unsupported_option(str(type(keras_layer)), 'merge',
keras_layer.name) | python | def _get_elementwise_name_from_keras_layer(keras_layer):
"""
Get the keras layer name from the activation name.
"""
if isinstance(keras_layer, _keras.layers.Add):
return 'ADD'
elif isinstance(keras_layer, _keras.layers.Multiply):
return 'MULTIPLY'
elif isinstance(keras_layer, _keras.layers.Concatenate):
if len(keras_layer.input_shape[0]) == 3 and (keras_layer.axis == 1 or keras_layer.axis == -2):
return 'SEQUENCE_CONCAT'
elif len(keras_layer.input_shape[0]) == 4 and (keras_layer.axis == 3 or keras_layer.axis == -1):
return 'CONCAT'
elif len(keras_layer.input_shape[0]) == 2 and (keras_layer.axis == 1 or keras_layer.axis == -1):
return 'CONCAT'
else:
raise ValueError('Only channel and sequence concatenation are supported.')
elif isinstance(keras_layer, _keras.layers.Dot):
if len(keras_layer.input_shape[0]) == 2:
if type(keras_layer.axes) is list or type(keras_layer.axes) is tuple:
if len(keras_layer.axes) > 1:
raise ValueError('Only vector dot-product is supported.')
else:
axis = keras_layer.axes[0]
else:
axis = keras_layer.axes
if axis != -1 and axis != 1:
raise ValueError('Only vector dot-product is supported.')
if keras_layer.normalize:
return 'COS'
else:
return 'DOT'
else:
raise ValueError('Only vector dot-product is supported.')
elif isinstance(keras_layer, _keras.layers.Maximum):
return 'MAX'
elif isinstance(keras_layer, _keras.layers.Average):
return 'AVE'
else:
_utils.raise_error_unsupported_option(str(type(keras_layer)), 'merge',
keras_layer.name) | [
"def",
"_get_elementwise_name_from_keras_layer",
"(",
"keras_layer",
")",
":",
"if",
"isinstance",
"(",
"keras_layer",
",",
"_keras",
".",
"layers",
".",
"Add",
")",
":",
"return",
"'ADD'",
"elif",
"isinstance",
"(",
"keras_layer",
",",
"_keras",
".",
"layers",
".",
"Multiply",
")",
":",
"return",
"'MULTIPLY'",
"elif",
"isinstance",
"(",
"keras_layer",
",",
"_keras",
".",
"layers",
".",
"Concatenate",
")",
":",
"if",
"len",
"(",
"keras_layer",
".",
"input_shape",
"[",
"0",
"]",
")",
"==",
"3",
"and",
"(",
"keras_layer",
".",
"axis",
"==",
"1",
"or",
"keras_layer",
".",
"axis",
"==",
"-",
"2",
")",
":",
"return",
"'SEQUENCE_CONCAT'",
"elif",
"len",
"(",
"keras_layer",
".",
"input_shape",
"[",
"0",
"]",
")",
"==",
"4",
"and",
"(",
"keras_layer",
".",
"axis",
"==",
"3",
"or",
"keras_layer",
".",
"axis",
"==",
"-",
"1",
")",
":",
"return",
"'CONCAT'",
"elif",
"len",
"(",
"keras_layer",
".",
"input_shape",
"[",
"0",
"]",
")",
"==",
"2",
"and",
"(",
"keras_layer",
".",
"axis",
"==",
"1",
"or",
"keras_layer",
".",
"axis",
"==",
"-",
"1",
")",
":",
"return",
"'CONCAT'",
"else",
":",
"raise",
"ValueError",
"(",
"'Only channel and sequence concatenation are supported.'",
")",
"elif",
"isinstance",
"(",
"keras_layer",
",",
"_keras",
".",
"layers",
".",
"Dot",
")",
":",
"if",
"len",
"(",
"keras_layer",
".",
"input_shape",
"[",
"0",
"]",
")",
"==",
"2",
":",
"if",
"type",
"(",
"keras_layer",
".",
"axes",
")",
"is",
"list",
"or",
"type",
"(",
"keras_layer",
".",
"axes",
")",
"is",
"tuple",
":",
"if",
"len",
"(",
"keras_layer",
".",
"axes",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"'Only vector dot-product is supported.'",
")",
"else",
":",
"axis",
"=",
"keras_layer",
".",
"axes",
"[",
"0",
"]",
"else",
":",
"axis",
"=",
"keras_layer",
".",
"axes",
"if",
"axis",
"!=",
"-",
"1",
"and",
"axis",
"!=",
"1",
":",
"raise",
"ValueError",
"(",
"'Only vector dot-product is supported.'",
")",
"if",
"keras_layer",
".",
"normalize",
":",
"return",
"'COS'",
"else",
":",
"return",
"'DOT'",
"else",
":",
"raise",
"ValueError",
"(",
"'Only vector dot-product is supported.'",
")",
"elif",
"isinstance",
"(",
"keras_layer",
",",
"_keras",
".",
"layers",
".",
"Maximum",
")",
":",
"return",
"'MAX'",
"elif",
"isinstance",
"(",
"keras_layer",
",",
"_keras",
".",
"layers",
".",
"Average",
")",
":",
"return",
"'AVE'",
"else",
":",
"_utils",
".",
"raise_error_unsupported_option",
"(",
"str",
"(",
"type",
"(",
"keras_layer",
")",
")",
",",
"'merge'",
",",
"keras_layer",
".",
"name",
")"
] | Get the keras layer name from the activation name. | [
"Get",
"the",
"keras",
"layer",
"name",
"from",
"the",
"activation",
"name",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers2.py#L76-L117 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers2.py | convert_dense | def convert_dense(builder, layer, input_names, output_names, keras_layer):
"""
Convert a dense layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get input and output names
input_name, output_name = (input_names[0], output_names[0])
has_bias = keras_layer.use_bias
# Get the weights from keras
W = keras_layer.get_weights ()[0].T
Wb = keras_layer.get_weights ()[1].T if has_bias else None
output_channels, input_channels = W.shape
builder.add_inner_product(name = layer,
W = W,
b = Wb,
input_channels = input_channels,
output_channels = output_channels,
has_bias = has_bias,
input_name = input_name,
output_name = output_name) | python | def convert_dense(builder, layer, input_names, output_names, keras_layer):
"""
Convert a dense layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get input and output names
input_name, output_name = (input_names[0], output_names[0])
has_bias = keras_layer.use_bias
# Get the weights from keras
W = keras_layer.get_weights ()[0].T
Wb = keras_layer.get_weights ()[1].T if has_bias else None
output_channels, input_channels = W.shape
builder.add_inner_product(name = layer,
W = W,
b = Wb,
input_channels = input_channels,
output_channels = output_channels,
has_bias = has_bias,
input_name = input_name,
output_name = output_name) | [
"def",
"convert_dense",
"(",
"builder",
",",
"layer",
",",
"input_names",
",",
"output_names",
",",
"keras_layer",
")",
":",
"# Get input and output names",
"input_name",
",",
"output_name",
"=",
"(",
"input_names",
"[",
"0",
"]",
",",
"output_names",
"[",
"0",
"]",
")",
"has_bias",
"=",
"keras_layer",
".",
"use_bias",
"# Get the weights from keras",
"W",
"=",
"keras_layer",
".",
"get_weights",
"(",
")",
"[",
"0",
"]",
".",
"T",
"Wb",
"=",
"keras_layer",
".",
"get_weights",
"(",
")",
"[",
"1",
"]",
".",
"T",
"if",
"has_bias",
"else",
"None",
"output_channels",
",",
"input_channels",
"=",
"W",
".",
"shape",
"builder",
".",
"add_inner_product",
"(",
"name",
"=",
"layer",
",",
"W",
"=",
"W",
",",
"b",
"=",
"Wb",
",",
"input_channels",
"=",
"input_channels",
",",
"output_channels",
"=",
"output_channels",
",",
"has_bias",
"=",
"has_bias",
",",
"input_name",
"=",
"input_name",
",",
"output_name",
"=",
"output_name",
")"
] | Convert a dense layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | [
"Convert",
"a",
"dense",
"layer",
"from",
"keras",
"to",
"coreml",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers2.py#L137-L165 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers2.py | convert_embedding | def convert_embedding(builder, layer, input_names, output_names, keras_layer):
"""Convert a dense layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get input and output names
input_name, output_name = (input_names[0], output_names[0])
# Get the weights from keras
W = keras_layer.get_weights ()[0].T
# assuming keras embedding layers don't have biases
builder.add_embedding(name = layer,
W = W,
b = None,
input_dim = keras_layer.input_dim,
output_channels = keras_layer.output_dim,
has_bias = False,
input_name = input_name,
output_name = output_name) | python | def convert_embedding(builder, layer, input_names, output_names, keras_layer):
"""Convert a dense layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get input and output names
input_name, output_name = (input_names[0], output_names[0])
# Get the weights from keras
W = keras_layer.get_weights ()[0].T
# assuming keras embedding layers don't have biases
builder.add_embedding(name = layer,
W = W,
b = None,
input_dim = keras_layer.input_dim,
output_channels = keras_layer.output_dim,
has_bias = False,
input_name = input_name,
output_name = output_name) | [
"def",
"convert_embedding",
"(",
"builder",
",",
"layer",
",",
"input_names",
",",
"output_names",
",",
"keras_layer",
")",
":",
"# Get input and output names",
"input_name",
",",
"output_name",
"=",
"(",
"input_names",
"[",
"0",
"]",
",",
"output_names",
"[",
"0",
"]",
")",
"# Get the weights from keras",
"W",
"=",
"keras_layer",
".",
"get_weights",
"(",
")",
"[",
"0",
"]",
".",
"T",
"# assuming keras embedding layers don't have biases",
"builder",
".",
"add_embedding",
"(",
"name",
"=",
"layer",
",",
"W",
"=",
"W",
",",
"b",
"=",
"None",
",",
"input_dim",
"=",
"keras_layer",
".",
"input_dim",
",",
"output_channels",
"=",
"keras_layer",
".",
"output_dim",
",",
"has_bias",
"=",
"False",
",",
"input_name",
"=",
"input_name",
",",
"output_name",
"=",
"output_name",
")"
] | Convert a dense layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | [
"Convert",
"a",
"dense",
"layer",
"from",
"keras",
"to",
"coreml",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers2.py#L167-L192 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers2.py | convert_activation | def convert_activation(builder, layer, input_names, output_names, keras_layer):
"""
Convert an activation layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get input and output names
input_name, output_name = (input_names[0], output_names[0])
non_linearity = _get_activation_name_from_keras_layer(keras_layer)
# Add a non-linearity layer
if non_linearity == 'SOFTMAX':
builder.add_softmax(name = layer, input_name = input_name,
output_name = output_name)
return
if non_linearity == 'RELU6':
# No direct support of RELU with max-activation value - use negate and
# clip layers
relu_output_name = output_name + '_relu'
builder.add_activation(layer, 'RELU', input_name, relu_output_name)
# negate it
neg_output_name = relu_output_name + '_neg'
builder.add_activation(layer+'__neg__', 'LINEAR', relu_output_name,
neg_output_name,[-1.0, 0])
# apply threshold
clip_output_name = relu_output_name + '_clip'
builder.add_unary(layer+'__clip__', neg_output_name, clip_output_name,
'threshold', alpha = -6.0)
# negate it back
builder.add_activation(layer+'_neg2', 'LINEAR', clip_output_name,
output_name,[-1.0, 0])
return
if non_linearity == 'SELU':
elu_output_name = output_name + '_elu'
builder.add_activation(layer+'__elu__', 'ELU', input_name, elu_output_name,
params=1.6732)
builder.add_elementwise(layer,
input_names=elu_output_name,
output_name=output_name,
mode='MULTIPLY',
alpha=1.0507)
return
params = None
if non_linearity == 'UNIT_ELU':
params = 1.0
non_linearity = 'ELU'
elif non_linearity == 'LEAKYRELU':
params = [keras_layer.alpha]
elif non_linearity == 'PRELU':
shared_axes = list(keras_layer.shared_axes)
if not (shared_axes == [1,2,3] or shared_axes == [1,2]):
_utils.raise_error_unsupported_scenario(
"Shared axis not being [1,2,3] or [1,2]",
'parametric_relu', layer)
params = _keras.backend.eval(keras_layer.weights[0])
elif non_linearity == 'ELU':
params = keras_layer.alpha
elif non_linearity == 'THRESHOLDEDRELU':
params = keras_layer.theta
else:
pass # do nothing to parameters
builder.add_activation(name = layer,
non_linearity = non_linearity,
input_name = input_name, output_name = output_name,
params = params) | python | def convert_activation(builder, layer, input_names, output_names, keras_layer):
"""
Convert an activation layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get input and output names
input_name, output_name = (input_names[0], output_names[0])
non_linearity = _get_activation_name_from_keras_layer(keras_layer)
# Add a non-linearity layer
if non_linearity == 'SOFTMAX':
builder.add_softmax(name = layer, input_name = input_name,
output_name = output_name)
return
if non_linearity == 'RELU6':
# No direct support of RELU with max-activation value - use negate and
# clip layers
relu_output_name = output_name + '_relu'
builder.add_activation(layer, 'RELU', input_name, relu_output_name)
# negate it
neg_output_name = relu_output_name + '_neg'
builder.add_activation(layer+'__neg__', 'LINEAR', relu_output_name,
neg_output_name,[-1.0, 0])
# apply threshold
clip_output_name = relu_output_name + '_clip'
builder.add_unary(layer+'__clip__', neg_output_name, clip_output_name,
'threshold', alpha = -6.0)
# negate it back
builder.add_activation(layer+'_neg2', 'LINEAR', clip_output_name,
output_name,[-1.0, 0])
return
if non_linearity == 'SELU':
elu_output_name = output_name + '_elu'
builder.add_activation(layer+'__elu__', 'ELU', input_name, elu_output_name,
params=1.6732)
builder.add_elementwise(layer,
input_names=elu_output_name,
output_name=output_name,
mode='MULTIPLY',
alpha=1.0507)
return
params = None
if non_linearity == 'UNIT_ELU':
params = 1.0
non_linearity = 'ELU'
elif non_linearity == 'LEAKYRELU':
params = [keras_layer.alpha]
elif non_linearity == 'PRELU':
shared_axes = list(keras_layer.shared_axes)
if not (shared_axes == [1,2,3] or shared_axes == [1,2]):
_utils.raise_error_unsupported_scenario(
"Shared axis not being [1,2,3] or [1,2]",
'parametric_relu', layer)
params = _keras.backend.eval(keras_layer.weights[0])
elif non_linearity == 'ELU':
params = keras_layer.alpha
elif non_linearity == 'THRESHOLDEDRELU':
params = keras_layer.theta
else:
pass # do nothing to parameters
builder.add_activation(name = layer,
non_linearity = non_linearity,
input_name = input_name, output_name = output_name,
params = params) | [
"def",
"convert_activation",
"(",
"builder",
",",
"layer",
",",
"input_names",
",",
"output_names",
",",
"keras_layer",
")",
":",
"# Get input and output names",
"input_name",
",",
"output_name",
"=",
"(",
"input_names",
"[",
"0",
"]",
",",
"output_names",
"[",
"0",
"]",
")",
"non_linearity",
"=",
"_get_activation_name_from_keras_layer",
"(",
"keras_layer",
")",
"# Add a non-linearity layer",
"if",
"non_linearity",
"==",
"'SOFTMAX'",
":",
"builder",
".",
"add_softmax",
"(",
"name",
"=",
"layer",
",",
"input_name",
"=",
"input_name",
",",
"output_name",
"=",
"output_name",
")",
"return",
"if",
"non_linearity",
"==",
"'RELU6'",
":",
"# No direct support of RELU with max-activation value - use negate and",
"# clip layers",
"relu_output_name",
"=",
"output_name",
"+",
"'_relu'",
"builder",
".",
"add_activation",
"(",
"layer",
",",
"'RELU'",
",",
"input_name",
",",
"relu_output_name",
")",
"# negate it",
"neg_output_name",
"=",
"relu_output_name",
"+",
"'_neg'",
"builder",
".",
"add_activation",
"(",
"layer",
"+",
"'__neg__'",
",",
"'LINEAR'",
",",
"relu_output_name",
",",
"neg_output_name",
",",
"[",
"-",
"1.0",
",",
"0",
"]",
")",
"# apply threshold",
"clip_output_name",
"=",
"relu_output_name",
"+",
"'_clip'",
"builder",
".",
"add_unary",
"(",
"layer",
"+",
"'__clip__'",
",",
"neg_output_name",
",",
"clip_output_name",
",",
"'threshold'",
",",
"alpha",
"=",
"-",
"6.0",
")",
"# negate it back",
"builder",
".",
"add_activation",
"(",
"layer",
"+",
"'_neg2'",
",",
"'LINEAR'",
",",
"clip_output_name",
",",
"output_name",
",",
"[",
"-",
"1.0",
",",
"0",
"]",
")",
"return",
"if",
"non_linearity",
"==",
"'SELU'",
":",
"elu_output_name",
"=",
"output_name",
"+",
"'_elu'",
"builder",
".",
"add_activation",
"(",
"layer",
"+",
"'__elu__'",
",",
"'ELU'",
",",
"input_name",
",",
"elu_output_name",
",",
"params",
"=",
"1.6732",
")",
"builder",
".",
"add_elementwise",
"(",
"layer",
",",
"input_names",
"=",
"elu_output_name",
",",
"output_name",
"=",
"output_name",
",",
"mode",
"=",
"'MULTIPLY'",
",",
"alpha",
"=",
"1.0507",
")",
"return",
"params",
"=",
"None",
"if",
"non_linearity",
"==",
"'UNIT_ELU'",
":",
"params",
"=",
"1.0",
"non_linearity",
"=",
"'ELU'",
"elif",
"non_linearity",
"==",
"'LEAKYRELU'",
":",
"params",
"=",
"[",
"keras_layer",
".",
"alpha",
"]",
"elif",
"non_linearity",
"==",
"'PRELU'",
":",
"shared_axes",
"=",
"list",
"(",
"keras_layer",
".",
"shared_axes",
")",
"if",
"not",
"(",
"shared_axes",
"==",
"[",
"1",
",",
"2",
",",
"3",
"]",
"or",
"shared_axes",
"==",
"[",
"1",
",",
"2",
"]",
")",
":",
"_utils",
".",
"raise_error_unsupported_scenario",
"(",
"\"Shared axis not being [1,2,3] or [1,2]\"",
",",
"'parametric_relu'",
",",
"layer",
")",
"params",
"=",
"_keras",
".",
"backend",
".",
"eval",
"(",
"keras_layer",
".",
"weights",
"[",
"0",
"]",
")",
"elif",
"non_linearity",
"==",
"'ELU'",
":",
"params",
"=",
"keras_layer",
".",
"alpha",
"elif",
"non_linearity",
"==",
"'THRESHOLDEDRELU'",
":",
"params",
"=",
"keras_layer",
".",
"theta",
"else",
":",
"pass",
"# do nothing to parameters",
"builder",
".",
"add_activation",
"(",
"name",
"=",
"layer",
",",
"non_linearity",
"=",
"non_linearity",
",",
"input_name",
"=",
"input_name",
",",
"output_name",
"=",
"output_name",
",",
"params",
"=",
"params",
")"
] | Convert an activation layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | [
"Convert",
"an",
"activation",
"layer",
"from",
"keras",
"to",
"coreml",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers2.py#L194-L267 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers2.py | convert_advanced_relu | def convert_advanced_relu(builder, layer, input_names, output_names, keras_layer):
"""
Convert an ReLU layer with maximum value from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get input and output names
input_name, output_name = (input_names[0], output_names[0])
if keras_layer.max_value is None:
builder.add_activation(layer, 'RELU', input_name, output_name)
return
# No direct support of RELU with max-activation value - use negate and
# clip layers
relu_output_name = output_name + '_relu'
builder.add_activation(layer, 'RELU', input_name, relu_output_name)
# negate it
neg_output_name = relu_output_name + '_neg'
builder.add_activation(layer+'__neg__', 'LINEAR', relu_output_name,
neg_output_name,[-1.0, 0])
# apply threshold
clip_output_name = relu_output_name + '_clip'
builder.add_unary(layer+'__clip__', neg_output_name, clip_output_name,
'threshold', alpha = -keras_layer.max_value)
# negate it back
builder.add_activation(layer+'_neg2', 'LINEAR', clip_output_name,
output_name,[-1.0, 0]) | python | def convert_advanced_relu(builder, layer, input_names, output_names, keras_layer):
"""
Convert an ReLU layer with maximum value from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get input and output names
input_name, output_name = (input_names[0], output_names[0])
if keras_layer.max_value is None:
builder.add_activation(layer, 'RELU', input_name, output_name)
return
# No direct support of RELU with max-activation value - use negate and
# clip layers
relu_output_name = output_name + '_relu'
builder.add_activation(layer, 'RELU', input_name, relu_output_name)
# negate it
neg_output_name = relu_output_name + '_neg'
builder.add_activation(layer+'__neg__', 'LINEAR', relu_output_name,
neg_output_name,[-1.0, 0])
# apply threshold
clip_output_name = relu_output_name + '_clip'
builder.add_unary(layer+'__clip__', neg_output_name, clip_output_name,
'threshold', alpha = -keras_layer.max_value)
# negate it back
builder.add_activation(layer+'_neg2', 'LINEAR', clip_output_name,
output_name,[-1.0, 0]) | [
"def",
"convert_advanced_relu",
"(",
"builder",
",",
"layer",
",",
"input_names",
",",
"output_names",
",",
"keras_layer",
")",
":",
"# Get input and output names",
"input_name",
",",
"output_name",
"=",
"(",
"input_names",
"[",
"0",
"]",
",",
"output_names",
"[",
"0",
"]",
")",
"if",
"keras_layer",
".",
"max_value",
"is",
"None",
":",
"builder",
".",
"add_activation",
"(",
"layer",
",",
"'RELU'",
",",
"input_name",
",",
"output_name",
")",
"return",
"# No direct support of RELU with max-activation value - use negate and",
"# clip layers",
"relu_output_name",
"=",
"output_name",
"+",
"'_relu'",
"builder",
".",
"add_activation",
"(",
"layer",
",",
"'RELU'",
",",
"input_name",
",",
"relu_output_name",
")",
"# negate it",
"neg_output_name",
"=",
"relu_output_name",
"+",
"'_neg'",
"builder",
".",
"add_activation",
"(",
"layer",
"+",
"'__neg__'",
",",
"'LINEAR'",
",",
"relu_output_name",
",",
"neg_output_name",
",",
"[",
"-",
"1.0",
",",
"0",
"]",
")",
"# apply threshold",
"clip_output_name",
"=",
"relu_output_name",
"+",
"'_clip'",
"builder",
".",
"add_unary",
"(",
"layer",
"+",
"'__clip__'",
",",
"neg_output_name",
",",
"clip_output_name",
",",
"'threshold'",
",",
"alpha",
"=",
"-",
"keras_layer",
".",
"max_value",
")",
"# negate it back",
"builder",
".",
"add_activation",
"(",
"layer",
"+",
"'_neg2'",
",",
"'LINEAR'",
",",
"clip_output_name",
",",
"output_name",
",",
"[",
"-",
"1.0",
",",
"0",
"]",
")"
] | Convert an ReLU layer with maximum value from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | [
"Convert",
"an",
"ReLU",
"layer",
"with",
"maximum",
"value",
"from",
"keras",
"to",
"coreml",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers2.py#L269-L302 | train |
apple/turicreate | src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers2.py | convert_convolution | def convert_convolution(builder, layer, input_names, output_names, keras_layer):
"""
Convert convolution layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
_check_data_format(keras_layer)
# Get input and output names
input_name, output_name = (input_names[0], output_names[0])
has_bias = keras_layer.use_bias
is_deconv = isinstance(keras_layer,
_keras.layers.convolutional.Conv2DTranspose)
# Get the weights from _keras.
weightList = keras_layer.get_weights()
# Dimensions and weights
if is_deconv:
height, width, n_filters, channels = weightList[0].shape
W = weightList[0].transpose([0,1,3,2])
try:
output_blob_shape = list(filter(None, keras_layer.output_shape))
output_shape = output_blob_shape[:-1]
except:
output_shape = None
else:
height, width, channels, n_filters = weightList[0].shape
W = weightList[0]
output_shape = None
b = weightList[1] if has_bias else None
output_channels = n_filters
stride_height, stride_width = keras_layer.strides
# Dilations
dilations = [1,1]
if (type(keras_layer.dilation_rate) is list) or (type(keras_layer.dilation_rate) is tuple):
dilations = [keras_layer.dilation_rate[0], keras_layer.dilation_rate[1]]
else:
dilations = [keras_layer.dilation_rate, keras_layer.dilation_rate]
if is_deconv and not dilations == [1,1]:
raise ValueError("Unsupported non-unity dilation for Deconvolution layer")
groups = 1
kernel_channels = channels
# depth-wise convolution
if isinstance(keras_layer, DepthwiseConv2D):
groups = channels
kernel_channels = 1
depth_multiplier = keras_layer.depth_multiplier
W = _np.reshape(W,(height, width,1,channels * depth_multiplier))
output_channels = channels * depth_multiplier
builder.add_convolution(name = layer,
kernel_channels = kernel_channels,
output_channels = output_channels,
height = height,
width = width,
stride_height = stride_height,
stride_width = stride_width,
border_mode = keras_layer.padding,
groups = groups,
W = W,
b = b,
has_bias = has_bias,
is_deconv = is_deconv,
output_shape = output_shape,
input_name = input_name,
output_name = output_name,
dilation_factors = dilations) | python | def convert_convolution(builder, layer, input_names, output_names, keras_layer):
"""
Convert convolution layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
_check_data_format(keras_layer)
# Get input and output names
input_name, output_name = (input_names[0], output_names[0])
has_bias = keras_layer.use_bias
is_deconv = isinstance(keras_layer,
_keras.layers.convolutional.Conv2DTranspose)
# Get the weights from _keras.
weightList = keras_layer.get_weights()
# Dimensions and weights
if is_deconv:
height, width, n_filters, channels = weightList[0].shape
W = weightList[0].transpose([0,1,3,2])
try:
output_blob_shape = list(filter(None, keras_layer.output_shape))
output_shape = output_blob_shape[:-1]
except:
output_shape = None
else:
height, width, channels, n_filters = weightList[0].shape
W = weightList[0]
output_shape = None
b = weightList[1] if has_bias else None
output_channels = n_filters
stride_height, stride_width = keras_layer.strides
# Dilations
dilations = [1,1]
if (type(keras_layer.dilation_rate) is list) or (type(keras_layer.dilation_rate) is tuple):
dilations = [keras_layer.dilation_rate[0], keras_layer.dilation_rate[1]]
else:
dilations = [keras_layer.dilation_rate, keras_layer.dilation_rate]
if is_deconv and not dilations == [1,1]:
raise ValueError("Unsupported non-unity dilation for Deconvolution layer")
groups = 1
kernel_channels = channels
# depth-wise convolution
if isinstance(keras_layer, DepthwiseConv2D):
groups = channels
kernel_channels = 1
depth_multiplier = keras_layer.depth_multiplier
W = _np.reshape(W,(height, width,1,channels * depth_multiplier))
output_channels = channels * depth_multiplier
builder.add_convolution(name = layer,
kernel_channels = kernel_channels,
output_channels = output_channels,
height = height,
width = width,
stride_height = stride_height,
stride_width = stride_width,
border_mode = keras_layer.padding,
groups = groups,
W = W,
b = b,
has_bias = has_bias,
is_deconv = is_deconv,
output_shape = output_shape,
input_name = input_name,
output_name = output_name,
dilation_factors = dilations) | [
"def",
"convert_convolution",
"(",
"builder",
",",
"layer",
",",
"input_names",
",",
"output_names",
",",
"keras_layer",
")",
":",
"_check_data_format",
"(",
"keras_layer",
")",
"# Get input and output names",
"input_name",
",",
"output_name",
"=",
"(",
"input_names",
"[",
"0",
"]",
",",
"output_names",
"[",
"0",
"]",
")",
"has_bias",
"=",
"keras_layer",
".",
"use_bias",
"is_deconv",
"=",
"isinstance",
"(",
"keras_layer",
",",
"_keras",
".",
"layers",
".",
"convolutional",
".",
"Conv2DTranspose",
")",
"# Get the weights from _keras.",
"weightList",
"=",
"keras_layer",
".",
"get_weights",
"(",
")",
"# Dimensions and weights",
"if",
"is_deconv",
":",
"height",
",",
"width",
",",
"n_filters",
",",
"channels",
"=",
"weightList",
"[",
"0",
"]",
".",
"shape",
"W",
"=",
"weightList",
"[",
"0",
"]",
".",
"transpose",
"(",
"[",
"0",
",",
"1",
",",
"3",
",",
"2",
"]",
")",
"try",
":",
"output_blob_shape",
"=",
"list",
"(",
"filter",
"(",
"None",
",",
"keras_layer",
".",
"output_shape",
")",
")",
"output_shape",
"=",
"output_blob_shape",
"[",
":",
"-",
"1",
"]",
"except",
":",
"output_shape",
"=",
"None",
"else",
":",
"height",
",",
"width",
",",
"channels",
",",
"n_filters",
"=",
"weightList",
"[",
"0",
"]",
".",
"shape",
"W",
"=",
"weightList",
"[",
"0",
"]",
"output_shape",
"=",
"None",
"b",
"=",
"weightList",
"[",
"1",
"]",
"if",
"has_bias",
"else",
"None",
"output_channels",
"=",
"n_filters",
"stride_height",
",",
"stride_width",
"=",
"keras_layer",
".",
"strides",
"# Dilations",
"dilations",
"=",
"[",
"1",
",",
"1",
"]",
"if",
"(",
"type",
"(",
"keras_layer",
".",
"dilation_rate",
")",
"is",
"list",
")",
"or",
"(",
"type",
"(",
"keras_layer",
".",
"dilation_rate",
")",
"is",
"tuple",
")",
":",
"dilations",
"=",
"[",
"keras_layer",
".",
"dilation_rate",
"[",
"0",
"]",
",",
"keras_layer",
".",
"dilation_rate",
"[",
"1",
"]",
"]",
"else",
":",
"dilations",
"=",
"[",
"keras_layer",
".",
"dilation_rate",
",",
"keras_layer",
".",
"dilation_rate",
"]",
"if",
"is_deconv",
"and",
"not",
"dilations",
"==",
"[",
"1",
",",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"\"Unsupported non-unity dilation for Deconvolution layer\"",
")",
"groups",
"=",
"1",
"kernel_channels",
"=",
"channels",
"# depth-wise convolution",
"if",
"isinstance",
"(",
"keras_layer",
",",
"DepthwiseConv2D",
")",
":",
"groups",
"=",
"channels",
"kernel_channels",
"=",
"1",
"depth_multiplier",
"=",
"keras_layer",
".",
"depth_multiplier",
"W",
"=",
"_np",
".",
"reshape",
"(",
"W",
",",
"(",
"height",
",",
"width",
",",
"1",
",",
"channels",
"*",
"depth_multiplier",
")",
")",
"output_channels",
"=",
"channels",
"*",
"depth_multiplier",
"builder",
".",
"add_convolution",
"(",
"name",
"=",
"layer",
",",
"kernel_channels",
"=",
"kernel_channels",
",",
"output_channels",
"=",
"output_channels",
",",
"height",
"=",
"height",
",",
"width",
"=",
"width",
",",
"stride_height",
"=",
"stride_height",
",",
"stride_width",
"=",
"stride_width",
",",
"border_mode",
"=",
"keras_layer",
".",
"padding",
",",
"groups",
"=",
"groups",
",",
"W",
"=",
"W",
",",
"b",
"=",
"b",
",",
"has_bias",
"=",
"has_bias",
",",
"is_deconv",
"=",
"is_deconv",
",",
"output_shape",
"=",
"output_shape",
",",
"input_name",
"=",
"input_name",
",",
"output_name",
"=",
"output_name",
",",
"dilation_factors",
"=",
"dilations",
")"
] | Convert convolution layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object. | [
"Convert",
"convolution",
"layer",
"from",
"keras",
"to",
"coreml",
"."
] | 74514c3f99e25b46f22c6e02977fe3da69221c2e | https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/keras/_layers2.py#L304-L383 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.