Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function: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_ed... | [
"\n Get edges that represents transition from not 1D to 1D, and 1D to not 1D\n A 'in_edge e(u,v)' means u operates on non-1D blobs, but v operates on 1D blobs.\n An 'out_edge e(u,v)' means u operates on 1D blobs, but v operates on non-1D blobs.\n "
] |
Please provide a description of the function: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 p... | [
"\n Insert permutation layers before a 1D start point or after 1D end point\n "
] |
Please provide a description of the function: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` ... | [] |
Please provide a description of the function: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."
] |
Please provide a description of the function: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):
transform... | [
"\n Create a Transformer object to transform data for feature engineering.\n\n Parameters\n ----------\n dataset : SFrame\n The dataset to use for training the model.\n\n transformers: Transformer | list[Transformer]\n An Transformer or a list of Transformers.\n\n See Also\n ----... |
Please provide a description of the function: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_p... | [] |
Please provide a description of the function: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() < (... | [
"\n Parameters\n ----------\n preprocessed_data : SArray\n\n Returns\n -------\n numpy array containing the deep features\n "
] |
Please provide a description of the function: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_featu... | [] |
Please provide a description of the function: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... | [
"\n Return the Core ML spec\n "
] |
Please provide a description of the function: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
... | [] |
Please provide a description of the function: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:
... | [
"To prevent circular imports, this extends isinstance()\n by checking also if `value` has a particular class name (or inherits from a\n particular class name). This check is safe in that an AttributeError is not\n raised in case `value` doesn't have a __class__ attribute.\n "
] |
Please provide a description of the function: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_pyth... | [
"Makes a token to refer to a Python value inside Jam language code.\n\n The token is merely a string that can be passed around in Jam code and\n eventually passed back. For example, we might want to pass PropertySet\n instance to a tag function and it might eventually call back\n to virtual_target.add_s... |
Please provide a description of the function: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 '-'."
] |
Please provide a description of the function: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
... | [
"Apply a set of standard transformations to string to produce an\n abbreviation no more than 4 characters long.\n "
] |
Please provide a description of the function: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... | [
"\n Get the decision from this node to a child node.\n\n Parameters\n ----------\n child: Node\n A child node of this node.\n\n Returns\n -------\n dict: A dictionary that describes how to get from this node to the\n child node.\n "
] |
Please provide a description of the function: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 | [
"\n Return the node as a dictionary.\n\n Returns\n -------\n dict: All the attributes of this node as a dictionary (minus the left\n and right).\n "
] |
Please provide a description of the function: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()
... | [
"\n Recursive function to dump this tree as a json blob.\n\n Parameters\n ----------\n root_id: Root id of the sub-tree\n output: Carry over output from the previous sub-trees.\n\n Returns\n -------\n dict: A tree in JSON format. Starts at the root node and re... |
Please provide a description of the function: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... | [
"\n Return the prediction score (if leaf node) or None if its an\n intermediate node.\n\n Parameters\n ----------\n node_id: id of the node to get the prediction value.\n\n Returns\n -------\n float or None: returns float value of prediction if leaf node and N... |
Please provide a description of the function: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 = {} ... | [
"\n Return the prediction path from this node to the parent node.\n\n Parameters\n ----------\n node_id : id of the node to get the prediction path.\n missing_id : Additional info that contains nodes with missing features.\n\n Returns\n -------\n list: The ... |
Please provide a description of the function: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):
... | [
"\n Given a weighted graph with observed class labels of a subset of vertices,\n infer the label probability for the unobserved vertices using the\n \"label propagation\" algorithm.\n\n The algorithm iteratively updates the label probability of current vertex\n as a weighted sum of label probability ... |
Please provide a description of the function: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 | [
"\n Check if a Turi create model is pickle safe.\n\n The function does it by checking that _CustomModel is the base class.\n\n Parameters\n ----------\n obj_class : Class to be checked.\n\n Returns\n ----------\n True if the GLC class is a model and is pickle safe.\n\n "
] |
Please provide a description of the function: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) | [
"\n Check if class is a Turi create model.\n\n The function does it by checking the method resolution order (MRO) of the\n class and verifies that _Model is the base class.\n\n Parameters\n ----------\n obj_class : Class to be checked.\n\n Returns\n ----------\n True if the class is a ... |
Please provide a description of the function: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 ... | [
"\n Internal util to get the type of the GLC class. The pickle file stores\n this name so that it knows how to construct the object on unpickling.\n\n Parameters\n ----------\n obj_class : Class which has to be categorized.\n\n Returns\n ----------\n A class type for the pickle file to sa... |
Please provide a description of the function: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 = _SArr... | [
"\n Internal util to get a GLC object from a persistent ID in the pickle file.\n\n Parameters\n ----------\n type_tag : The name of the glc class as saved in the GLC pickler.\n\n gl_archive_abs_path: An absolute path to the GLC archive where the\n object was saved.\n\n Ret... |
Please provide a description of the function: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.
... | [
"\n Provide a persistent ID for \"saving\" GLC objects by reference. Return\n None for all non GLC objects.\n\n Parameters\n ----------\n\n obj: Name of the object whose persistent ID is extracted.\n\n Returns\n --------\n None if the object is not a GLC objec... |
Please provide a description of the function: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):
... | [
"\n Close the pickle file, and the zip archive file. The single zip archive\n file can now be shipped around to be loaded by the unpickler.\n "
] |
Please provide a description of the function: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_obje... | [
"\n Reconstruct a GLC object using the persistent ID.\n\n This method should not be used externally. It is required by the unpickler super class.\n\n Parameters\n ----------\n pid : The persistent ID used in pickle file to save the GLC object.\n\n Returns\n ----... |
Please provide a description of the function: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.is... | [
"\n Clean up files that were created.\n "
] |
Please provide a description of the function: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
... | [
"\n Convert scikit-learn pipeline, classifier, or regressor to Core ML format.\n\n Parameters\n ----------\n sk_obj: model | [model] of scikit-learn format.\n Scikit learn model(s) to convert to a Core ML format.\n\n The input model may be a single scikit learn model, a scikit learn\n ... |
Please provide a description of the function: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.\n\n Args:\n descriptor: Protobuf Descriptor object\n byte_str: Serialized protocol buffer byte string\n\n Returns:\n Newly created protobuf Message object.\n "
] |
Please provide a description of the function: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[GeneratedProtoc... | [
"Construct a class object for a protobuf described by descriptor.\n\n Composite descriptors are handled by defining the new class as a member of the\n parent class, recursing as deep as necessary.\n This is the dynamic equivalent to:\n\n class Parent(message.Message):\n __metaclass__ = GeneratedProtocolMessa... |
Please provide a description of the function: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,
... | [
"\n Loads images from a directory. JPEG and PNG images are supported.\n\n Parameters\n ----------\n url : str\n The string of the path where all the images are stored.\n\n format : {'PNG' | 'JPG' | 'auto'}, optional\n The format of the images in the directory. The default 'auto' paramet... |
Please provide a description of the function: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:
... | [
"\n Internal helper function for decoding a single Image or an SArray of Images\n "
] |
Please provide a description of the function: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 == 'bi... | [
"\n Resizes the image or SArray of Images to a specific width, height, and\n number of channels.\n\n Parameters\n ----------\n\n image : turicreate.Image | SArray\n The image or SArray of images to be resized.\n width : int\n The width the image is resized to.\n height : int\n ... |
Please provide a description of the function: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 ra... | [
"\n Convert bit array to byte array.\n\n :param arr: list\n Bits as a list where each element is an integer of 0 or 1\n\n Returns\n -------\n numpy.array\n 1D numpy array of type uint8\n "
] |
Please provide a description of the function: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 | [
"\n Unpack bytes to bits\n\n :param arr: list\n Byte Stream, as a list of uint8 values\n\n Returns\n -------\n bit_arr: list\n Decomposed bit stream as a list of 0/1s of length (len(arr) * 8)\n "
] |
Please provide a description of the function: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, ... | [
"\n Generate a linear lookup table.\n\n :param nbits: int\n Number of bits to represent a quantized weight value\n\n :param wp: numpy.array\n Weight blob to be quantized\n\n Returns\n -------\n lookup_table: numpy.array\n Lookup table of shape (2^nbits, )\n qw: numpy.array\... |
Please provide a description of the function: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.p... | [
"\n Generate K-Means lookup table given a weight parameter field\n\n :param nbits:\n Number of bits for quantization\n\n :param w:\n Weight as numpy array\n\n Returns\n -------\n lut: numpy.array\n Lookup table, numpy array of shape (1 << nbits, );\n wq: numpy.array\n ... |
Please provide a description of the function: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) + t... | [
"\n Linearly quantize weight blob.\n\n :param weight: numpy.array\n Weight to be quantized.\n\n :param nbits: int\n Number of bits per weight element\n\n :param axis: int\n Axis of the weight blob to compute channel-wise quantization, can be 0 or 1\n\n Returns\n -------\n q... |
Please provide a description of the function: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 == _Q... | [
"\n Quantize the weight blob\n\n :param wp: numpy.array\n Weight parameters\n :param nbits: int\n Number of bits\n :param qm:\n Quantization mode\n :param lut_function: (``callable function``)\n Python callable representing a look-up table\n\n Returns\n -------\n ... |
Please provide a description of the function: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:
... | [
"\n Quantize WeightParam field in Neural Network Protobuf\n\n :param wp: MLModel.NeuralNetwork.WeightParam\n WeightParam field\n :param nbits: int\n Number of bits to be quantized\n :param qm: str\n Quantization mode\n :param shape: tuple\n Tensor shape held by wp\n :pa... |
Please provide a description of the function:def compare_models(full_precision_model, quantized_model,
sample_data):
emessage = ()
spec = full_precision_model.get_spec()
num_inputs = len(spec.description.input)
if isinstance(sample_data, str):
input_type = spe... | [
"\n Utility function to compare the performance of a full precision vs quantized model\n\n :param full_precision_model: MLModel\n The full precision model with float32 weights\n\n :param quantized_model: MLModel\n Quantized version of the model with quantized weights\n\n :param sample_data... |
Please provide a description of the function:def quantize_weights(full_precision_model,
nbits,
quantization_mode="linear",
sample_data=None,
**kwargs):
qmode_mapping = {
"linear": _QUANTIZATION_MODE_LINEAR_QUANTIZATION,... | [
"\n Utility function to convert a full precision (float) MLModel to a\n nbit quantized MLModel (float16).\n\n :param full_precision_model: MLModel\n Model which will be converted to half precision. Currently conversion\n for only neural network models is supported. If a pipeline model is\n ... |
Please provide a description of the function: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... | [
"\n Create a recommender that uses item-item similarities based on\n users in common.\n\n Parameters\n ----------\n observation_data : SFrame\n The dataset to use for training the model. It must contain a column of\n user ids and a column of item ids. Each row represents an observed\n ... |
Please provide a description of the function: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.Concatenat... | [
"\n Get the keras layer name from the activation name.\n "
] |
Please provide a description of the function: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_weig... | [
"\n Convert a dense layer from keras to coreml.\n\n Parameters\n keras_layer: layer\n ----------\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function: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 kera... | [
"Convert a dense layer from keras to coreml.\n\n Parameters\n keras_layer: layer\n ----------\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function: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-linea... | [
"\n Convert an activation layer from keras to coreml.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function: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... | [
"\n Convert an ReLU layer with maximum value from keras to coreml.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function: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 = i... | [
"\n Convert convolution layer from keras to coreml.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function:def convert_convolution1d(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.
# Keras store... | [
"\n Convert convolution layer from keras to coreml.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function:def convert_separable_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
# G... | [
"\n Convert separable convolution layer from keras to coreml.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function:def convert_batchnorm(builder, layer, input_names, output_names, keras_layer):
# Get input and output names
input_name, output_name = (input_names[0], output_names[0])
axis = keras_layer.axis
nb_channels = keras_layer.input_shape[axis]
# Set param... | [
"\n Convert a Batch Normalization layer.\n\n Parameters\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function:def convert_flatten(builder, layer, input_names, output_names, keras_layer):
input_name, output_name = (input_names[0], output_names[0])
# blob_order == 0 if the input blob needs not be rearranged
# blob_order == 1 if the input blob needs to be rearranged
... | [
"\n Convert a flatten layer from keras to coreml.\n ----------\n Parameters\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function:def convert_merge(builder, layer, input_names, output_names, keras_layer):
# Get input and output names
output_name = output_names[0]
mode = _get_elementwise_name_from_keras_layer(keras_layer)
builder.add_elementwise(name = layer, input_names = input_na... | [
"\n Convert concat layer from keras to coreml.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function:def convert_pooling(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])
# Pooling layer type
if isinstance(keras_layer, _ke... | [
"\n Convert pooling layer from keras to coreml.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function:def convert_padding(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])
is_1d = isinstance(keras_layer, _keras.layers.ZeroPaddi... | [
"\n Convert padding layer from keras to coreml.\n Keras only supports zero padding at this time.\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function:def convert_cropping(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])
is_1d = isinstance(keras_layer, _keras.layers.Cropping... | [
"\n Convert padding layer from keras to coreml.\n Keras only supports zero padding at this time.\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function:def convert_upsample(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])
is_1d = isinstance(keras_layer, _keras.layers.UpSampli... | [
"\n Convert convolution layer from keras to coreml.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function:def convert_permute(builder, layer, input_names, output_names, keras_layer):
input_name, output_name = (input_names[0], output_names[0])
keras_dims = keras_layer.dims
# Keras permute layer index begins at 1
if len(keras_dims) == 3:
# Keras input... | [
"\n Convert a softmax layer from keras to coreml.\n\n Parameters\n keras_layer: layer\n ----------\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function:def convert_simple_rnn(builder, layer, input_names, output_names, keras_layer):
# Get input and output names
hidden_size = keras_layer.units
input_size = keras_layer.input_shape[-1]
output_all = keras_layer.return_sequences
reverse_input = keras_lay... | [
"\n Convert an SimpleRNN layer from keras to coreml.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function:def convert_lstm(builder, layer, input_names, output_names, keras_layer):
hidden_size = keras_layer.units
input_size = keras_layer.input_shape[-1]
output_all = keras_layer.return_sequences
reverse_input = keras_layer.go_backwards
# Keras: [W_x, W_h... | [
"\n Convert an LSTM layer from keras to coreml.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function:def convert_gru(builder, layer, input_names, output_names, keras_layer):
hidden_size = keras_layer.units
input_size = keras_layer.input_shape[-1]
output_all = keras_layer.return_sequences
reverse_input = keras_layer.go_backwards
# Keras: Z R O
... | [
"\n Convert a GRU layer from keras to coreml.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function:def convert_bidirectional(builder, layer, input_names, output_names, keras_layer):
input_size = keras_layer.input_shape[-1]
lstm_layer = keras_layer.forward_layer
if (type(lstm_layer) != _keras.layers.recurrent.LSTM):
raise TypeError('Bidirectional... | [
"\n Convert a bidirectional layer from keras to coreml.\n Currently assumes the units are LSTMs.\n\n Parameters\n ----------\n keras_layer: layer\n A keras layer object.\n\n builder: NeuralNetworkBuilder\n A neural network builder object.\n "
] |
Please provide a description of the function: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()... | [] |
Please provide a description of the function: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,... | [] |
Please provide a description of the function: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)... | [] |
Please provide a description of the function: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, c... | [] |
Please provide a description of the function: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 model in which the similarity\n between the items recommended is determined by the content of\n those items rather than learned from user interaction data.\n\n The similarity score between two items is calculated by first\n computing the similarity between the item da... |
Please provide a description of the function: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:
... | [] |
Please provide a description of the function: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 | [] |
Please provide a description of the function: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(... | [] |
Please provide a description of the function:def _loadlib(lib='standard'):
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.... | [
"Load rabit library."
] |
Please provide a description of the function:def init(args=None, lib='standard'):
if args is None:
args = sys.argv
_loadlib(lib)
arr = (ctypes.c_char_p * len(args))()
arr[:] = args
_LIB.RabitInit(len(args), arr) | [
"Intialize the rabit module, call this once before using anything.\n\n Parameters\n ----------\n args: list of str, optional\n The list of arguments used to initialized the rabit\n usually you need to pass in sys.argv.\n Defaults to sys.argv when it is None.\n lib: {'standard', 'moc... |
Please provide a description of the function:def tracker_print(msg):
if not isinstance(msg, str):
msg = str(msg)
_LIB.RabitTrackerPrint(ctypes.c_char_p(msg).encode('utf-8')) | [
"Print message to the tracker.\n\n This function can be used to communicate the information of\n the progress to the tracker\n\n Parameters\n ----------\n msg : str\n The message to be printed to tracker.\n "
] |
Please provide a description of the function:def allreduce(data, op, prepare_fun=None):
if not isinstance(data, np.ndarray):
raise Exception('allreduce only takes in numpy.ndarray')
buf = data.ravel()
if buf.base is data.base:
buf = buf.copy()
if buf.dtype not in DTYPE_ENUM__:
... | [
"Perform allreduce, return the result.\n\n Parameters\n ----------\n data: numpy array\n Input data.\n op: int\n Reduction operators, can be MIN, MAX, SUM, BITOR\n prepare_fun: function\n Lazy preprocessing function, if it is not None, prepare_fun(data)\n will be called by... |
Please provide a description of the function:def load_checkpoint(with_local=False):
gptr = ctypes.POINTER(ctypes.c_char)()
global_len = ctypes.c_ulong()
if with_local:
lptr = ctypes.POINTER(ctypes.c_char)()
local_len = ctypes.c_ulong()
version = _LIB.RabitLoadCheckPoint(
... | [
"Load latest check point.\n\n Parameters\n ----------\n with_local: bool, optional\n whether the checkpoint contains local model\n\n Returns\n -------\n tuple : tuple\n if with_local: return (version, gobal_model, local_model)\n else return (version, gobal_model)\n if r... |
Please provide a description of the function:def checkpoint(global_model, local_model=None):
sglobal = pickle.dumps(global_model)
if local_model is None:
_LIB.RabitCheckPoint(sglobal, len(sglobal), None, 0)
del sglobal
else:
slocal = pickle.dumps(local_model)
_LIB.RabitC... | [
"Checkpoint the model.\n\n This means we finished a stage of execution.\n Every time we call check point, there is a version number which will increase by one.\n\n Parameters\n ----------\n global_model: anytype that can be pickled\n globally shared model/state when calling this function,\n ... |
Please provide a description of the function:def stack_annotations(annotations_sarray):
_raise_error_if_not_sarray(annotations_sarray, variable_name='annotations_sarray')
sf = _tc.SFrame({'annotations': annotations_sarray}).add_row_number('row_id')
sf = sf.stack('annotations', new_column_name='annotati... | [
"\n Converts object detection annotations (ground truth or predictions) to\n stacked format (an `SFrame` where each row is one object instance).\n\n Parameters\n ----------\n annotations_sarray: SArray\n An `SArray` with unstacked predictions, exactly formatted as the\n annotations colu... |
Please provide a description of the function:def unstack_annotations(annotations_sframe, num_rows=None):
_raise_error_if_not_sframe(annotations_sframe, variable_name="annotations_sframe")
cols = ['label', 'type', 'coordinates']
has_confidence = 'confidence' in annotations_sframe.column_names()
if ... | [
"\n Converts object detection annotations (ground truth or predictions) to\n unstacked format (an `SArray` where each element is a list of object\n instances).\n\n Parameters\n ----------\n annotations_sframe: SFrame\n An `SFrame` with stacked predictions, produced by the\n `stack_an... |
Please provide a description of the function:def create(observation_data,
user_id='user_id', item_id='item_id', target=None,
user_data=None, item_data=None,
num_factors=32,
regularization=1e-9,
linear_regularization=1e-9,
side_data_factorization=True,
... | [
"Create a RankingFactorizationRecommender that learns latent factors for each\n user and item and uses them to make rating predictions.\n\n Parameters\n ----------\n observation_data : SFrame\n The dataset to use for training the model. It must contain a column of\n user ids and a column o... |
Please provide a description of the function:def preprocess():
"splits _sources/reference.rst into separate files"
text = open("./_sources/reference.rst", "r").read()
os.remove("./_sources/reference.rst")
if not os.path.exists("./_sources/reference"):
os.makedirs("./_sources/reference")
d... | [] |
Please provide a description of the function:def PackTag(field_number, wire_type):
if not 0 <= wire_type <= _WIRETYPE_MAX:
raise message.EncodeError('Unknown wire type: %d' % wire_type)
return (field_number << TAG_TYPE_BITS) | wire_type | [
"Returns an unsigned 32-bit integer that encodes the field number and\n wire type information in standard protocol message wire format.\n\n Args:\n field_number: Expected to be an integer in the range [1, 1 << 29)\n wire_type: One of the WIRETYPE_* constants.\n "
] |
Please provide a description of the function:def _VarUInt64ByteSizeNoTag(uint64):
if uint64 <= 0x7f: return 1
if uint64 <= 0x3fff: return 2
if uint64 <= 0x1fffff: return 3
if uint64 <= 0xfffffff: return 4
if uint64 <= 0x7ffffffff: return 5
if uint64 <= 0x3ffffffffff: return 6
if uint64 <= 0x1ffffffffff... | [
"Returns the number of bytes required to serialize a single varint\n using boundary value comparisons. (unrolled loop optimization -WPierce)\n uint64 must be unsigned.\n "
] |
Please provide a description of the function:def _seconds_as_string(seconds):
TIME_UNITS = [('s', 60), ('m', 60), ('h', 24), ('d', None)]
unit_strings = []
cur = max(int(seconds), 1)
for suffix, size in TIME_UNITS:
if size is not None:
cur, rest = divmod(cur, size)
else:... | [
"\n Returns seconds as a human-friendly string, e.g. '1d 4h 47m 41s'\n "
] |
Please provide a description of the function:def _get_converter_module(sk_obj):
try:
cv_idx = _converter_lookup[sk_obj.__class__]
except KeyError:
raise ValueError(
"Transformer '%s' not supported; supported transformers are %s."
% (repr(sk_obj),
... | [
"\n Returns the module holding the conversion functions for a\n particular model).\n "
] |
Please provide a description of the function:def _convert_sklearn_model(input_sk_obj, input_features = None,
output_feature_names = None, class_labels = None):
if not(HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
from... | [
"\n Converts a generic sklearn pipeline, transformer, classifier, or regressor\n into an coreML specification.\n "
] |
Please provide a description of the function:def set_default_prediction_value(self, values):
if type(values) is not list:
values = [float(values)]
self.tree_parameters.numPredictionDimensions = len(values)
for value in values:
self.tree_parameters.basePredictionV... | [
"\n Set the default prediction value(s).\n\n The values given here form the base prediction value that the values\n at activated leaves are added to. If values is a scalar, then\n the output of the tree must also be 1 dimensional; otherwise, values\n must be a list with length ma... |
Please provide a description of the function:def set_post_evaluation_transform(self, value):
r
self.tree_spec.postEvaluationTransform = \
_TreeEnsemble_pb2.TreeEnsemblePostEvaluationTransform.Value(value) | [
"\n Set the post processing transform applied after the prediction value\n from the tree ensemble.\n\n Parameters\n ----------\n\n value: str\n\n A value denoting the transform applied. Possible values are:\n\n - \"NoTransform\" (default). Do not apply a tr... |
Please provide a description of the function:def add_branch_node(self, tree_id, node_id, feature_index, feature_value,
branch_mode, true_child_id, false_child_id, relative_hit_rate = None,
missing_value_tracks_true_child = False):
spec_node = self.tree_parameters.nodes.add()
... | [
"\n Add a branch node to the tree ensemble.\n\n Parameters\n ----------\n tree_id: int\n ID of the tree to add the node to.\n\n node_id: int\n ID of the node within the tree.\n\n feature_index: int\n Index of the feature in the input being s... |
Please provide a description of the function:def add_leaf_node(self, tree_id, node_id, values, relative_hit_rate = None):
spec_node = self.tree_parameters.nodes.add()
spec_node.treeId = tree_id
spec_node.nodeId = node_id
spec_node.nodeBehavior = \
_TreeEnsemble_pb2.Tr... | [
"\n Add a leaf node to the tree ensemble.\n\n Parameters\n ----------\n tree_id: int\n ID of the tree to add the node to.\n\n node_id: int\n ID of the node within the tree.\n\n values: [float | int | list | dict]\n Value(s) at the leaf node ... |
Please provide a description of the function:def create (raw_properties = []):
assert (is_iterable_typed(raw_properties, property.Property)
or is_iterable_typed(raw_properties, basestring))
# FIXME: propagate to callers.
if len(raw_properties) > 0 and isinstance(raw_properties[0], property.... | [
" Creates a new 'PropertySet' instance for the given raw properties,\n or returns an already existing one.\n "
] |
Please provide a description of the function:def create_with_validation (raw_properties):
assert is_iterable_typed(raw_properties, basestring)
properties = [property.create_from_string(s) for s in raw_properties]
property.validate(properties)
return create(properties) | [
" Creates new 'PropertySet' instances after checking\n that all properties are valid and converting implicit\n properties into gristed form.\n "
] |
Please provide a description of the function:def create_from_user_input(raw_properties, jamfile_module, location):
assert is_iterable_typed(raw_properties, basestring)
assert isinstance(jamfile_module, basestring)
assert isinstance(location, basestring)
properties = property.create_from_strings(raw... | [
"Creates a property-set from the input given by the user, in the\n context of 'jamfile-module' at 'location'"
] |
Please provide a description of the function:def refine_from_user_input(parent_requirements, specification, jamfile_module,
location):
assert isinstance(parent_requirements, PropertySet)
assert is_iterable_typed(specification, basestring)
assert isinstance(jamfile_module, bas... | [
"Refines requirements with requirements provided by the user.\n Specially handles \"-<property>value\" syntax in specification\n to remove given requirements.\n - parent-requirements -- property-set object with requirements\n to refine\n - specification -- string list of requirements provided b... |
Please provide a description of the function:def base (self):
result = [p for p in self.lazy_properties
if not(p.feature.incidental or p.feature.free)]
result.extend(self.base_)
return result | [
" Returns properties that are neither incidental nor free.\n "
] |
Please provide a description of the function:def free (self):
result = [p for p in self.lazy_properties
if not p.feature.incidental and p.feature.free]
result.extend(self.free_)
return result | [
" Returns free properties which are not dependency properties.\n "
] |
Please provide a description of the function:def dependency (self):
result = [p for p in self.lazy_properties if p.feature.dependency]
result.extend(self.dependency_)
return self.dependency_ | [
" Returns dependency properties.\n "
] |
Please provide a description of the function:def non_dependency (self):
result = [p for p in self.lazy_properties if not p.feature.dependency]
result.extend(self.non_dependency_)
return result | [
" Returns properties that are not dependencies.\n "
] |
Please provide a description of the function:def incidental (self):
result = [p for p in self.lazy_properties if p.feature.incidental]
result.extend(self.incidental_)
return result | [
" Returns incidental properties.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.