INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Load a Python module that should be useable from Jamfiles. | 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 w... |
Set the named attribute from the specification given by the user. The value actually set may be different. | 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:
... |
Prints the project attributes. | 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... |
Given a free - standing function callable return a new callable that will call callable and report all exceptins using call_and_report_errors. | 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_repo... |
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. | 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, basestrin... |
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. | 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... |
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: | 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 :
... |
Creates a feature extractor from an input array feature return | 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 li... |
Add a single build XML output file to our data. | 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)
i... |
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. | 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',... |
Given a build action log process into the corresponding test log and specific test log sub - part. | 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)
... |
The time - stamp goes to the corresponding attribute in the result. | 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 |
Print the detailed info of failed or always print tests. | 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 o... |
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 | 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... |
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_fie... | 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 : li... |
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 ... | 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, descript... |
Print the network information summary. Args: mlmodel_spec: the mlmodel spec interface_only: Shows only the input and output of the network | 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('... |
Takes an SVM classifier produces a starting spec using the parts. that are shared between all SVMs. | 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, la... |
Convert a Support Vector Classtion ( SVC ) model to the protobuf spec. Parameters ---------- model: SVC A trained SVC encoder model. | 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 (defau... |
Extract the ordering of the 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)
f... |
Extract the ordering of 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,... |
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. | 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... |
remove the layer and its input/ output edges | 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)
fo... |
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 | 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 n... |
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 | 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.inde... |
Defuse the fused activation layers in the network. | 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... |
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. | 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.
"""
... |
Insert permutation layers before a 1D start point or after 1D end point | 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 t... |
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 | 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)
... |
Report something about component configuration that the user should better know. | 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) |
Create a Transformer object to transform data for feature engineering. | 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 Transformer... |
Preprocess each example breaking it up into frames. | 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()
progres... |
Parameters ---------- preprocessed_data: SArray | 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 = F... |
Performs both audio preprocessing and VGGish deep feature extraction. | 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)
outp... |
Return the Core ML 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 MLMod... |
Remove redundant statements. The statement a = 1 will be removed:: a = 1 a = 2 | 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
... |
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. | 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 ... |
Makes a token to refer to a Python value inside Jam language code. | 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 ... |
Abbreviates each part of string that is delimited by a -. | 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) |
Apply a set of standard transformations to string to produce an abbreviation no more than 4 characters long. | 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 ... |
Get the decision from this node to a child node. | 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 t... |
Return the node as a dictionary. | 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... |
Recursive function to dump this tree as a json blob. | 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 JS... |
Return the prediction score ( if leaf node ) or None if its an intermediate node. | 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 v... |
Return the prediction path from this node to the parent node. | 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... |
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. | 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 cl... |
Check if a Turi create model is pickle safe. | 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 a... |
Check if class is a Turi create model. | 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
---... |
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. | 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 typ... |
Internal util to get a GLC object from a persistent ID in the pickle file. | 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 ... |
Provide a persistent ID for saving GLC objects by reference. Return None for all non GLC objects. | 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 ob... |
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. | 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 = ... |
Reconstruct a GLC object using the persistent ID. | 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.
... |
Clean up files that were created. | 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... |
Convert scikit - learn pipeline classifier or regressor to Core ML format. | 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.
... |
Generate a new Message instance from this Descriptor and a byte string. | 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... |
Construct a class object for a protobuf described by descriptor. | 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__ = Ge... |
Loads images from a directory. JPEG and PNG images are supported. | 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' | ... |
Internal helper function for decoding a single Image or an SArray of Images | 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... |
Resizes the image or SArray of Images to a specific width height and number of channels. | 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 resiz... |
Convert bit 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(... |
Unpack bytes to bits | 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)):
... |
Generate a linear lookup table. | 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 ... |
Generate K - Means lookup table given a weight parameter field | 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.a... |
Linearly quantize weight blob. | 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,... |
Quantize the weight blob | 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... |
Quantize WeightParam field in Neural Network Protobuf | 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
:pa... |
Utility function to compare the performance of a full precision vs quantized model | 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... |
Utility function to convert a full precision ( float ) MLModel to a nbit quantized MLModel ( float16 ). | 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 f... |
Create a recommender that uses item - item similarities based on users in common. | 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*102... |
Get the keras layer name from the activation name. | 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, _ke... |
Convert a dense layer from keras to coreml. | 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 o... |
Convert a dense layer from keras to coreml. | 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 ou... |
Convert an activation layer from keras to coreml. | 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 ... |
Convert an ReLU layer with maximum value from keras to coreml. | 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.
... |
Convert convolution layer from keras to coreml. | 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... |
Convert convolution layer from keras to coreml. | def convert_convolution1d(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.
"""
# Get... |
Convert separable convolution layer from keras to coreml. | def convert_separable_convolution(builder, layer, input_names, output_names, keras_layer):
"""
Convert separable convolution layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.... |
Convert a Batch Normalization layer. | def convert_batchnorm(builder, layer, input_names, output_names, keras_layer):
"""
Convert a Batch Normalization layer.
Parameters
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get input and output names
i... |
Convert a flatten layer from keras to coreml. ---------- Parameters keras_layer: layer A keras layer object. | def convert_flatten(builder, layer, input_names, output_names, keras_layer):
"""
Convert a flatten layer from keras to coreml.
----------
Parameters
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, ou... |
Convert concat layer from keras to coreml. | def convert_merge(builder, layer, input_names, output_names, keras_layer):
"""
Convert concat layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get input and ou... |
Convert pooling layer from keras to coreml. | def convert_pooling(builder, layer, input_names, output_names, keras_layer):
"""
Convert pooling layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
_check_data_for... |
Convert padding layer from keras to coreml. Keras only supports zero padding at this time. Parameters ---------- keras_layer: layer A keras layer object. | def convert_padding(builder, layer, input_names, output_names, keras_layer):
"""
Convert padding layer from keras to coreml.
Keras only supports zero padding at this time.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural n... |
Convert padding layer from keras to coreml. Keras only supports zero padding at this time. Parameters ---------- keras_layer: layer A keras layer object. | def convert_cropping(builder, layer, input_names, output_names, keras_layer):
"""
Convert padding layer from keras to coreml.
Keras only supports zero padding at this time.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural ... |
Convert convolution layer from keras to coreml. | def convert_upsample(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_dat... |
Convert a softmax layer from keras to coreml. | def convert_permute(builder, layer, input_names, output_names, keras_layer):
"""
Convert a softmax layer from keras to coreml.
Parameters
keras_layer: layer
----------
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
input_name, o... |
Convert an SimpleRNN layer from keras to coreml. | def convert_simple_rnn(builder, layer, input_names, output_names, keras_layer):
"""
Convert an SimpleRNN layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get i... |
Convert an LSTM layer from keras to coreml. | def convert_lstm(builder, layer, input_names, output_names, keras_layer):
"""
Convert an LSTM layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
hidden_size = ker... |
Convert a GRU layer from keras to coreml. | def convert_gru(builder, layer, input_names, output_names, keras_layer):
"""
Convert a GRU layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
hidden_size = keras_... |
Convert a bidirectional layer from keras to coreml. Currently assumes the units are LSTMs. | def convert_bidirectional(builder, layer, input_names, output_names, keras_layer):
"""
Convert a bidirectional layer from keras to coreml.
Currently assumes the units are LSTMs.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A n... |
obj [: ] | def SLICE_0(self, instr):
'obj[:]'
value = self.ast_stack.pop()
kw = dict(lineno=instr.lineno, col_offset=0)
slice = _ast.Slice(lower=None, step=None, upper=None, **kw)
subscr = _ast.Subscript(value=value, slice=slice, ctx=_ast.Load(), **kw)
self.ast_stack.append(subscr... |
obj [ lower: ] = expr | def STORE_SLICE_1(self, instr):
'obj[lower:] = expr'
lower = self.ast_stack.pop()
value = self.ast_stack.pop()
expr = self.ast_stack.pop()
kw = dict(lineno=instr.lineno, col_offset=0)
slice = _ast.Slice(lower=lower, step=None, upper=None, **kw)
subscr = _ast.Subs... |
obj [ lower: upper ] = expr | def STORE_SLICE_3(self, instr):
'obj[lower:upper] = expr'
upper = self.ast_stack.pop()
lower = self.ast_stack.pop()
value = self.ast_stack.pop()
expr = self.ast_stack.pop()
kw = dict(lineno=instr.lineno, col_offset=0)
slice = _ast.Slice(lower=lower, step... |
obj [: ] = expr | def DELETE_SLICE_0(self, instr):
'obj[:] = expr'
value = self.ast_stack.pop()
kw = dict(lineno=instr.lineno, col_offset=0)
slice = _ast.Slice(lower=None, step=None, upper=None, **kw)
subscr = _ast.Subscript(value=value, slice=slice, ctx=_ast.Del(), **kw)
delete = _ast.D... |
Create a content - based recommender model in which the similarity between the items recommended is determined by the content of those items rather than learned from user interaction data. | def create(item_data, item_id,
observation_data = None,
user_id = None, target = None,
weights = 'auto',
similarity_metrics = 'auto',
item_data_transform = 'auto',
max_item_neighborhood_size = 64, verbose=True):
"""Create a content-based recommender... |
Return a set of symbols in node that are assigned.: param node: ast node: returns: set of strings. | def lhs(node):
'''
Return a set of symbols in `node` that are assigned.
:param node: ast node
:returns: set of strings.
'''
gen = ConditionalSymbolVisitor()
if isinstance(node, (list, tuple)):
gen.visit_list(node)
else:
gen.visit(node)
return gen.lhs |
Group outputs into conditional and stable: param node: ast node: returns: tuple of ( conditional stable ) | def conditional_lhs(node):
'''
Group outputs into conditional and stable
:param node: ast node
:returns: tuple of (conditional, stable)
'''
gen = ConditionalSymbolVisitor()
gen.visit(node)
return gen.cond_lhs, gen.stable_lhs |
Group lhs and rhs into conditional stable and undefined: param node: ast node: returns: tuple of ( conditional_lhs stable_lhs ) ( conditional_rhs stable_rhs ) undefined | def conditional_symbols(node):
'''
Group lhs and rhs into conditional, stable and undefined
:param node: ast node
:returns: tuple of (conditional_lhs, stable_lhs),(conditional_rhs, stable_rhs), undefined
'''
gen = ConditionalSymbolVisitor()
gen.visit(node)
lhs = gen.cond_lhs,... |
Load rabit library. | def _loadlib(lib='standard'):
"""Load rabit library."""
global _LIB
if _LIB is not None:
warnings.warn('rabit.int call was ignored because it has'\
' already been initialized', level=2)
return
if lib == 'standard':
_LIB = ctypes.cdll.LoadLibrary(WRAPPER_... |
Intialize the rabit module call this once before using anything. | def init(args=None, lib='standard'):
"""Intialize the rabit module, call this once before using anything.
Parameters
----------
args: list of str, optional
The list of arguments used to initialized the rabit
usually you need to pass in sys.argv.
Defaults to sys.argv when it is N... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.