Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def prep_data(data, features, session_id, prediction_window, predictions_in_chunk, target=None, verbose=True):
if target is None:
target = ""
if verbose:
result_dict = _extensions._activity_classifier_prepare_data_verbose(
data, featu... | [
"\n Convert SFrame to batch form, where each row contains a sequence of length\n predictions_in_chunk * prediction_window, and there is a single label per\n prediction window.\n "
] |
Please provide a description of the function:def _load_into_numpy(sf, np_array, start, end, strides=None, shape=None):
np_array[:] = 0.0
np_array_2d = np_array.reshape((np_array.shape[0], np_array.shape[1] * np_array.shape[2]))
_extensions.sframe_load_to_numpy(sf, np_array.ctypes.data,
... | [
"Loads into numpy array from SFrame, assuming SFrame stores data flattened"
] |
Please provide a description of the function:def set_input(self, input_names, input_dims):
spec = self.spec
nn_spec = self.nn_spec
for idx, dim in enumerate(input_dims):
if len(dim) == 3:
input_shape = (dim[0], dim[1], dim[2])
elif len(dim) == 2:
... | [
"\n Set the inputs of the network spec.\n\n Parameters\n ----------\n input_names: [str]\n List of input names of the network.\n\n input_dims: [tuple]\n List of input dimensions of the network. The ordering of input_dims\n is the same as input_name... |
Please provide a description of the function:def set_output(self, output_names, output_dims):
spec = self.spec
nn_spec = self.nn_spec
for idx, dim in enumerate(output_dims):
spec.description.output[idx].type.multiArrayType.ClearField("shape")
spec.description.out... | [
"\n Set the outputs of the network spec.\n\n Parameters\n ----------\n output_names: [str]\n List of output names of the network.\n\n output_dims: [tuple]\n List of output dimensions of the network. The ordering of output_dims is the same\n as outp... |
Please provide a description of the function:def set_class_labels(self, class_labels, predicted_feature_name = 'classLabel', prediction_blob = ''):
spec = self.spec
nn_spec = self.nn_spec
if len(spec.description.output) == 0:
raise ValueError(
"Model should ... | [
"\n Set class labels to the model spec to make it a neural network classifier.\n\n Parameters\n ----------\n class_labels: list[int or str]\n A list of integers or strings that map the index of the output of a\n neural network to labels in a classifier.\n\n p... |
Please provide a description of the function:def add_optionals(self, optionals_in, optionals_out):
spec = self.spec
if (not optionals_in) and (not optionals_out):
return
# assuming single sizes here
input_types = [datatypes.Array(dim) for (name, dim) in optionals_in... | [
"\n Add optional inputs and outputs to the model spec.\n\n Parameters\n ----------\n optionals_in: [str]\n List of inputs that are optionals.\n\n optionals_out: [str]\n List of outputs that are optionals.\n\n See Also\n --------\n set_inp... |
Please provide a description of the function:def add_embedding(self, name, W, b, input_dim, output_channels, has_bias,
input_name, output_name):
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer... | [
"\n Add an embedding layer to the model.\n\n Parameters\n ----------\n name: str\n The name of this layer\n W: numpy.array\n Weight matrix of shape (output_channels, input_dim).\n b: numpy.array\n Bias vector of shape (output_channels, ).\n ... |
Please provide a description of the function:def add_softmax(self, name, input_name, output_name):
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spe... | [
"\n Add a softmax layer to the model.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n input_name: str\n The input blob name of this layer.\n output_name: str\n The output blob name of this layer.\n\n See Also\n ... |
Please provide a description of the function:def add_activation(self, name, non_linearity, input_name, output_name,
params=None):
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_lay... | [
"\n Add an activation layer to the model.\n\n Parameters\n ----------\n name: str\n The name of this layer\n non_linearity: str\n The non_linearity (activation) function of this layer.\n It can be one of the following:\n\n - 'RELU': ... |
Please provide a description of the function:def add_elementwise(self, name, input_names, output_name, mode, alpha = None):
spec = self.spec
nn_spec = self.nn_spec
spec_layer = nn_spec.layers.add()
spec_layer.name = name
if isinstance(input_names, list):
fo... | [
"\n Add an element-wise operation layer to the model.\n\n Parameters\n ----------\n The name of this layer\n name: str\n input_names: [str]\n A list of input blob names of this layer. The input blobs should have the same shape.\n output_name: str\n ... |
Please provide a description of the function:def add_upsample(self, name, scaling_factor_h, scaling_factor_w, input_name, output_name, mode = 'NN'):
spec = self.spec
nn_spec = self.nn_spec
# Add a new inner-product layer
spec_layer = nn_spec.layers.add()
spec_layer.name... | [
"\n Add upsample layer to the model.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n scaling_factor_h: int\n Scaling factor on the vertical direction.\n scaling_factor_w: int\n Scaling factor on the horizontal direction.\... |
Please provide a description of the function:def add_scale(self, name, W, b, has_bias, input_name, output_name, shape_scale = [1], shape_bias = [1]):
spec = self.spec
nn_spec = self.nn_spec
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append... | [
"\n Add scale layer to the model.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n W: int | numpy.array\n Scale of the input.\n b: int | numpy.array\n Bias to add to the input.\n has_bias: boolean\n Wheth... |
Please provide a description of the function:def add_bias(self, name, b, input_name, output_name, shape_bias = [1]):
spec = self.spec
nn_spec = self.nn_spec
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.o... | [
"\n Add bias layer to the model.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n b: int | numpy.array\n Bias to add to the input.\n input_name: str\n The input blob name of this layer.\n output_name: str\n ... |
Please provide a description of the function:def add_sequence_repeat(self, name, nrep, input_name, output_name):
spec = self.spec
nn_spec = self.nn_spec
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output... | [
"\n Add sequence repeat layer to the model.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n nrep: int\n Number of repetitions of the input blob along the sequence axis.\n input_name: str\n The input blob name of this laye... |
Please provide a description of the function:def add_convolution(self, name, kernel_channels, output_channels, height,
width, stride_height, stride_width, border_mode, groups, W, b, has_bias,
is_deconv = False, output_shape = None,
input_name = 'data', output_name = 'out',
... | [
"\n Add a convolution layer to the network.\n\n Please see the ConvolutionLayerParams in Core ML neural network\n protobuf message for more information about input and output blob dimensions.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n ... |
Please provide a description of the function:def add_padding(self, name,
left = 0, right = 0, top = 0, bottom = 0,
value = 0,
input_name = 'data', output_name = 'out',
padding_type = 'constant'):
# Currently only constant padding is supported.
spe... | [
"\n Add a padding layer to the model. Kindly refer to NeuralNetwork.proto for details.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n left: int\n Number of elements to be padded on the left side of the input blob.\n right: int\n ... |
Please provide a description of the function:def add_crop(self, name, left, right, top, bottom, offset, input_names,
output_name):
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
for ... | [
"\n Add a cropping layer to the model.\n The cropping layer have two functional modes:\n\n - When it has 1 input blob, it crops the input blob based\n on the 4 parameters [left, right, top, bottom].\n - When it has 2 input blobs, it crops the first input blob based\n... |
Please provide a description of the function:def add_simple_rnn(self,name, W_h, W_x, b, hidden_size, input_size, activation, input_names, output_names, output_all = False, reverse_input = False):
spec = self.spec
nn_spec = self.nn_spec
# Add a new Layer
spec_layer = nn_spec.la... | [
"\n Add a simple recurrent layer to the model.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n W_h: numpy.array\n Weights of the recurrent layer's hidden state. Must be of shape (hidden_size, hidden_size).\n W_x: numpy.array\n ... |
Please provide a description of the function:def add_gru(self, name, W_h, W_x, b, hidden_size, input_size,
input_names, output_names, activation = 'TANH', inner_activation = 'SIGMOID_HARD',
output_all = False, reverse_input = False):
spec = self.spec
nn_spec = self.nn_sp... | [
"\n Add a Gated-Recurrent Unit (GRU) layer to the model.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n W_h: [numpy.array]\n List of recursion weight matrices. The ordering is [R_z, R_r, R_o],\n where R_z, R_r and R_o are weigh... |
Please provide a description of the function:def add_unilstm(self, name, W_h, W_x, b, hidden_size, input_size, input_names, output_names,
inner_activation = 'SIGMOID',
cell_state_update_activation = 'TANH',
output_activation = 'TANH',
peep ... | [
"\n Add a Uni-directional LSTM layer to the model.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n W_h: [numpy.array]\n List of recursion weight matrices. The ordering is [R_i, R_f, R_o, R_z],\n where R_i, R_f, R_o, R_z are weig... |
Please provide a description of the function:def add_bidirlstm(self, name, W_h, W_x, b, W_h_back, W_x_back, b_back, hidden_size, input_size,
input_names, output_names,
inner_activation = 'SIGMOID',
cell_state_update_activation = 'TANH',
output_activation = 'TANH',
... | [
"\n Add a Bi-directional LSTM layer to the model.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n W_h: [numpy.array]\n List of recursion weight matrices for the forward layer. The ordering is [R_i, R_f, R_o, R_z],\n where R_i, R... |
Please provide a description of the function:def add_flatten(self, name, mode, input_name, output_name):
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
... | [
"\n Add a flatten layer. Only flattens the channel, height and width axis. Leaves the sequence axis as is.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n mode: int\n\n - If mode == 0, the flatten layer is in CHANNEL_FIRST mode.\n ... |
Please provide a description of the function:def add_slice(self, name, input_name, output_name, axis, start_index = 0, end_index = -1, stride = 1):
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
... | [
"\n Add a slice layer. Equivalent to to numpy slice [start_index:end_index:stride],\n start_index is included, while end_index is exclusive.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n\n input_name: str\n The input blob name of ... |
Please provide a description of the function:def add_reorganize_data(self, name, input_name, output_name, mode = 'SPACE_TO_DEPTH', block_size = 2):
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
... | [
"\n Add a data reorganization layer of type \"SPACE_TO_DEPTH\" or \"DEPTH_TO_SPACE\".\n\n Parameters\n ----------\n name: str\n The name of this layer.\n\n input_name: str\n The input blob name of this layer.\n output_name: str\n The output ... |
Please provide a description of the function:def add_batchnorm(self, name, channels, gamma, beta,
mean = None, variance = None,
input_name = 'data', output_name = 'out',
compute_mean_var = False,
instance_normalization = False, epsi... | [
"\n Add a Batch Normalization layer. Batch Normalization operation is\n defined as:\n\n `y = gamma * (x - mean) / sqrt(variance + epsilon) + beta`\n Parameters\n\n ----------\n name: str\n The name of this layer.\n channels: int\n Number of chan... |
Please provide a description of the function:def add_permute(self, name, dim, input_name, output_name):
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
... | [
"\n Add a permute layer. Assumes that the input has dimensions in the order [Seq, C, H, W]\n\n Parameters\n ----------\n name: str\n The name of this layer.\n dim: tuple\n The order in which to permute the input dimensions = [seq,C,H,W].\n Must hav... |
Please provide a description of the function:def add_reshape(self, name, input_name, output_name, target_shape, mode):
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(inp... | [
"\n Add a reshape layer. Kindly refer to NeuralNetwork.proto for details.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n target_shape: tuple\n Shape of the output blob. The product of target_shape must be equal\n to the shape o... |
Please provide a description of the function:def add_reduce(self, name, input_name, output_name, axis, mode, epsilon = 1e-6):
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.app... | [
"\n Add a reduce layer. Applies the function specified by the parameter mode,\n along dimension(s) specified by the parameter axis.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n\n input_name: str\n The input blob name of this laye... |
Please provide a description of the function:def add_lrn(self, name, input_name, output_name, alpha, beta, local_size, k = 1.0):
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.... | [
"\n Add a LRN (local response normalization) layer. Please see the LRNLayerParams message in Core ML neural network\n protobuf for more information about the operation of this layer. Supports \"across\" channels normalization.\n\n Parameters\n ----------\n name: str\n T... |
Please provide a description of the function:def add_mvn(self, name, input_name, output_name, across_channels = True, normalize_variance = True, epsilon = 1e-5):
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name... | [
"\n Add an MVN (mean variance normalization) layer. Computes mean, variance and normalizes the input.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n\n input_name: str\n The input blob name of this layer.\n output_name: str\n ... |
Please provide a description of the function:def add_l2_normalize(self, name, input_name, output_name, epsilon = 1e-5):
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(in... | [
"\n Add L2 normalize layer. Normalizes the input by the L2 norm, i.e. divides by the\n the square root of the sum of squares of all elements of the input along C, H and W dimensions.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n\n input_name... |
Please provide a description of the function:def add_unary(self, name, input_name, output_name, mode, alpha = 1.0,
shift = 0, scale = 1.0, epsilon = 1e-6):
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
s... | [
"\n Add a Unary layer. Applies the specified function (mode) to all the elements of the input.\n Please see the UnaryFunctionLayerParams message in Core ML neural network\n protobuf for more information about the operation of this layer.\n Prior to the application of the function the inp... |
Please provide a description of the function:def add_split(self, name, input_name, output_names):
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec... | [
"\n Add a Split layer that uniformly splits the input along the channel dimension\n to produce multiple outputs.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n\n input_name: str\n The input blob name of this layer.\n output_... |
Please provide a description of the function:def add_load_constant(self, name, output_name, constant_value, shape):
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.output.append(output... | [
"\n Add a load constant layer.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n\n output_name: str\n The output blob name of this layer.\n\n constant_value: numpy.array\n value of the constant as a numpy array.\n\n ... |
Please provide a description of the function:def add_custom(self, name, input_names, output_names, custom_proto_spec = None):
spec = self.spec
nn_spec = self.nn_spec
# custom layers require a newer specification version
from coremltools import _MINIMUM_CUSTOM_LAYER_SPEC_VERSIO... | [
"\n Add a custom layer.\n\n Parameters\n ----------\n name: str\n The name of this layer.\n\n input_names: [str]\n The input blob names to this layer.\n\n output_names: [str]\n The output blob names from this layer.\n\n custom_proto_s... |
Please provide a description of the function:def set_pre_processing_parameters(self, image_input_names = [], is_bgr = False,
red_bias = 0.0, green_bias = 0.0, blue_bias = 0.0, gray_bias = 0.0, image_scale = 1.0):
spec = self.spec
if not image_input_names:
return # nothin... | [
"Add pre-processing parameters to the neural network object\n\n Parameters\n ----------\n image_input_names: [str]\n Name of input blobs that are images\n\n is_bgr: boolean | dict()\n Channel order for input blobs that are images. BGR if True else RGB.\n ... |
Please provide a description of the function:def register(scanner_class, relevant_properties):
assert issubclass(scanner_class, Scanner)
assert isinstance(relevant_properties, basestring)
__scanners[str(scanner_class)] = relevant_properties | [
" Registers a new generator class, specifying a set of\n properties relevant to this scanner. Ctor for that class\n should have one parameter: list of properties.\n "
] |
Please provide a description of the function:def get(scanner_class, properties):
assert issubclass(scanner_class, Scanner)
assert is_iterable_typed(properties, basestring)
scanner_name = str(scanner_class)
if not registered(scanner_name):
raise BaseException ("attempt to get unregisted sca... | [
" Returns an instance of previously registered scanner\n with the specified properties.\n "
] |
Please provide a description of the function:def install (self, scanner, target, vtarget):
assert isinstance(scanner, Scanner)
assert isinstance(target, basestring)
assert isinstance(vtarget, basestring)
engine = self.manager_.engine()
engine.set_target_variable(target, ... | [
" Installs the specified scanner on actual target 'target'.\n vtarget: virtual target from which 'target' was actualized.\n "
] |
Please provide a description of the function:def _fill_function(func, globals, defaults, dict, module, closure_values):
func.__globals__.update(globals)
func.__defaults__ = defaults
func.__dict__ = dict
func.__module__ = module
cells = func.__closure__
if cells is not None:
for cel... | [
" Fills in the rest of function data into the skeleton function object\n that were created via _make_skel_func().\n "
] |
Please provide a description of the function:def _make_skel_func(code, cell_count, base_globals=None):
if base_globals is None:
base_globals = {}
base_globals['__builtins__'] = __builtins__
closure = (
tuple(_make_empty_cell() for _ in range(cell_count))
if cell_count >= 0 else... | [
" Creates a skeleton function object that contains just the provided\n code and the correct number of cells in func_closure. All other\n func attributes (e.g. func_globals) are empty.\n "
] |
Please provide a description of the function:def _rehydrate_skeleton_class(skeleton_class, class_dict):
for attrname, attr in class_dict.items():
setattr(skeleton_class, attrname, attr)
return skeleton_class | [
"Put attributes from `class_dict` back on `skeleton_class`.\n\n See CloudPickler.save_dynamic_class for more info.\n "
] |
Please provide a description of the function:def _find_module(mod_name):
path = None
for part in mod_name.split('.'):
if path is not None:
path = [path]
file, path, description = imp.find_module(part, path)
if file is not None:
file.close()
return path, d... | [
"\n Iterate over each part instead of calling imp.find_module directly.\n This function is able to find submodules (e.g. sickit.tree)\n "
] |
Please provide a description of the function:def save_module(self, obj):
mod_name = obj.__name__
# If module is successfully found then it is not a dynamically created module
if hasattr(obj, '__file__'):
is_dynamic = False
else:
try:
_find... | [
"\n Save a module as an import\n "
] |
Please provide a description of the function:def _save_subimports(self, code, top_level_dependencies):
# check if any known dependency is an imported package
for x in top_level_dependencies:
if isinstance(x, types.ModuleType) and hasattr(x, '__package__') and x.__package__:
... | [
"\n Ensure de-pickler imports any package child-modules that\n are needed by the function\n "
] |
Please provide a description of the function:def save_dynamic_class(self, obj):
clsdict = dict(obj.__dict__) # copy dict proxy to a dict
if not isinstance(clsdict.get('__dict__', None), property):
# don't extract dict that are properties
clsdict.pop('__dict__', None)
... | [
"\n Save a class that can't be stored as module global.\n\n This method is used to serialize classes that are defined inside\n functions, or that otherwise can't be serialized as attribute lookups\n from global modules.\n "
] |
Please provide a description of the function:def save_function_tuple(self, func):
if is_tornado_coroutine(func):
self.save_reduce(_rebuild_tornado_coroutine, (func.__wrapped__,),
obj=func)
return
save = self.save
write = self.write
... | [
" Pickles an actual func object.\n\n A func comprises: code, globals, defaults, closure, and dict. We\n extract and save these, injecting reducing functions at certain points\n to recreate the func object. Keep in mind that some of these pieces\n can contain a ref to the func itself. ... |
Please provide a description of the function:def extract_code_globals(cls, co):
out_names = cls._extract_code_globals_cache.get(co)
if out_names is None:
try:
names = co.co_names
except AttributeError:
# PyPy "builtin-code" object
... | [
"\n Find all globals names read or written to by codeblock co\n "
] |
Please provide a description of the function:def save_global(self, obj, name=None, pack=struct.pack):
if obj.__module__ == "__builtin__" or obj.__module__ == "builtins":
if obj in _BUILTIN_TYPE_NAMES:
return self.save_reduce(_builtin_type, (_BUILTIN_TYPE_NAMES[obj],), obj=ob... | [
"\n Save a \"global\".\n\n The name of this method is somewhat misleading: all types get\n dispatched here.\n "
] |
Please provide a description of the function:def save_reduce(self, func, args, state=None,
listitems=None, dictitems=None, obj=None):
# Assert that args is a tuple or None
if not isinstance(args, tuple):
raise pickle.PicklingError("args from reduce() should be a ... | [
"Modified to support __transient__ on new objects\n Change only affects protocol level 2 (which is always used by PiCloud"
] |
Please provide a description of the function:def save_partial(self, obj):
self.save_reduce(_genpartial, (obj.func, obj.args, obj.keywords)) | [
"Partial objects do not serialize correctly in python2.x -- this fixes the bugs"
] |
Please provide a description of the function:def save_file(self, obj):
try:
import StringIO as pystringIO #we can't use cStringIO as it lacks the name attribute
except ImportError:
import io as pystringIO
if not hasattr(obj, 'name') or not hasattr(obj, 'mode'):... | [
"Save a file"
] |
Please provide a description of the function:def save_ufunc(self, obj):
name = obj.__name__
numpy_tst_mods = ['numpy', 'scipy.special']
for tst_mod_name in numpy_tst_mods:
tst_mod = sys.modules.get(tst_mod_name, None)
if tst_mod and name in tst_mod.__dict__:
... | [
"Hack function for saving numpy ufunc objects"
] |
Please provide a description of the function:def _ExtractSymbols(desc_proto, package):
message_name = '.'.join((package, desc_proto.name))
yield message_name
for nested_type in desc_proto.nested_type:
for symbol in _ExtractSymbols(nested_type, message_name):
yield symbol
for enum_type in desc_prot... | [
"Pulls out all the symbols from a descriptor proto.\n\n Args:\n desc_proto: The proto to extract symbols from.\n package: The package containing the descriptor type.\n\n Yields:\n The fully qualified name found in the descriptor.\n "
] |
Please provide a description of the function:def Add(self, file_desc_proto):
proto_name = file_desc_proto.name
if proto_name not in self._file_desc_protos_by_file:
self._file_desc_protos_by_file[proto_name] = file_desc_proto
elif self._file_desc_protos_by_file[proto_name] != file_desc_proto:
... | [
"Adds the FileDescriptorProto and its types to this database.\n\n Args:\n file_desc_proto: The FileDescriptorProto to add.\n Raises:\n DescriptorDatabaseConflictingDefinitionError: if an attempt is made to\n add a proto with the same name but different definition than an\n exisiting pr... |
Please provide a description of the function:def convert(model, input_features, output_features):
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
# Test the scikit-learn model
_sklearn_util.check_expected_type(model, Normalizer)
... | [
"Convert a normalizer model to the protobuf spec.\n\n Parameters\n ----------\n model: Normalizer\n A Normalizer.\n\n input_features: str\n Name of the input column.\n\n output_features: str\n Name of the output column.\n\n Returns\n -------\n model_spec: An object of ty... |
Please provide a description of the function:def mpi_submit(nslave, worker_args, worker_envs):
worker_args += ['%s=%s' % (k, str(v)) for k, v in worker_envs.items()]
sargs = ' '.join(args.command + worker_args)
if args.hostfile is None:
cmd = ' '.join(['mpirun -n %d' % (nslave)] + args.command ... | [
"\n customized submit script, that submit nslave jobs, each must contain args as parameter\n note this can be a lambda function containing additional parameters in input\n Parameters\n nslave number of slave process to start up\n args arguments to launch each job\n this u... |
Please provide a description of the function:def consume(self):
'''
Consume byte-code
'''
generic_consume = getattr(self, 'generic_consume', None)
for instr in disassembler(self.code):
method_name = 'consume_%s' % (instr.opname)
method = getattr(s... | [] |
Please provide a description of the function:def create(dataset, target,
features=None,
max_iterations=10,
validation_set='auto',
verbose=True, class_weights=None,
random_seed=None,
metric='auto',
**kwargs):
if random_seed is not Non... | [
"\n Create a (binary or multi-class) classifier model of type\n :class:`~turicreate.random_forest_classifier.RandomForestClassifier` using\n an ensemble of decision trees trained on subsets of the data.\n\n Parameters\n ----------\n dataset : SFrame\n A training dataset containing feature c... |
Please provide a description of the function:def classify(self, dataset, missing_value_action='auto'):
return super(RandomForestClassifier, self).classify(dataset,
missing_value_action=missing_value_action) | [
"\n Return a classification, for each example in the ``dataset``, using the\n trained random forest model. The output SFrame contains predictions\n as class labels (0 or 1) and probabilities associated with the the example.\n\n Parameters\n ----------\n dataset : SFrame\n ... |
Please provide a description of the function:def _get_layer_converter_fn(layer):
layer_type = type(layer)
if layer_type in _KERAS_LAYER_REGISTRY:
return _KERAS_LAYER_REGISTRY[layer_type]
else:
raise TypeError("Keras layer of type %s is not supported." % type(layer)) | [
"Get the right converter function for Keras\n "
] |
Please provide a description of the function:def convertToSpec(model,
input_names = None,
output_names = None,
image_input_names = None,
input_name_shape_dict = {},
is_bgr = False,
red_bias = 0.0,
... | [
"\n Convert a Keras model to Core ML protobuf specification (.mlmodel).\n\n Parameters\n ----------\n model: Keras model object | str | (str, str)\n A trained Keras neural network model which can be one of the following:\n\n - a Keras model object\n - a string with the path to a Ker... |
Please provide a description of the function:def convert(model,
input_names = None,
output_names = None,
image_input_names = None,
input_name_shape_dict = {},
is_bgr = False,
red_bias = 0.0,
gre... | [
"\n Convert a Keras model to Core ML protobuf specification (.mlmodel).\n\n Parameters\n ----------\n model: Keras model object | str | (str, str)\n\n A trained Keras neural network model which can be one of the following:\n\n - a Keras model object\n - a string with the path to a K... |
Please provide a description of the function:def convert(model, feature_names, target):
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
_sklearn_util.check_expected_type(model, _ensemble.RandomForestRegressor)
def is_rf_model(m):
... | [
"Convert a boosted tree model to protobuf format.\n\n Parameters\n ----------\n decision_tree : RandomForestRegressor\n A trained scikit-learn tree model.\n\n feature_names: [str]\n Name of the input columns.\n\n target: str\n Name of the output column.\n\n Returns\n ------... |
Please provide a description of the function:def create(dataset, features=None, distance=None, radius=1.,
min_core_neighbors=10, verbose=True):
## Start the training time clock and instantiate an empty model
logger = _logging.getLogger(__name__)
start_time = _time.time()
## Validate t... | [
"\n Create a DBSCAN clustering model. The DBSCAN method partitions the input\n dataset into three types of points, based on the estimated probability\n density at each point.\n\n - **Core** points have a large number of points within a given neighborhood.\n Specifically, `min_core_neighbors` must b... |
Please provide a description of the function:def find_lib_path():
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
# make pythonpack hack: copy this directory one level upper for setup.py
dll_path = [curr_path, os.path.join(curr_path, '../../wrapper/'),
os.path... | [
"Load find the path to xgboost dynamic library files.\n\n Returns\n -------\n lib_path: list(string)\n List of all found library path to xgboost\n "
] |
Please provide a description of the function:def check_expected_type(model, expected_type):
if (model.__class__.__name__ != expected_type.__name__):
raise TypeError("Expected model of type '%s' (got %s)" % \
(expected_type.__name__, model.__class__.__name__)) | [
"Check if a model is of the right type. Raise error if not.\n\n Parameters\n ----------\n model: model\n Any scikit-learn model\n\n expected_type: Type\n Expected type of the scikit-learn.\n "
] |
Please provide a description of the function:def convert(model, input_names='input', target_name='target',
probability='classProbability', input_length='auto'):
if not(_HAS_LIBSVM):
raise RuntimeError('libsvm not found. libsvm conversion API is disabled.')
if isinstance(model, _string_... | [
"\n Convert a LIBSVM model to Core ML format.\n\n Parameters\n ----------\n\n model: a libsvm model (C-SVC, nu-SVC, epsilon-SVR, or nu-SVR)\n or string path to a saved model.\n\n input_names: str | [str]\n Name of the input column(s).\n If a single string is used (the default) th... |
Please provide a description of the function:def append(self, value):
self._values.append(self._type_checker.CheckValue(value))
if not self._message_listener.dirty:
self._message_listener.Modified() | [
"Appends an item to the list. Similar to list.append()."
] |
Please provide a description of the function:def insert(self, key, value):
self._values.insert(key, self._type_checker.CheckValue(value))
if not self._message_listener.dirty:
self._message_listener.Modified() | [
"Inserts the item at the specified position. Similar to list.insert()."
] |
Please provide a description of the function:def extend(self, elem_seq):
if elem_seq is None:
return
try:
elem_seq_iter = iter(elem_seq)
except TypeError:
if not elem_seq:
# silently ignore falsy inputs :-/.
# TODO(ptucker): Deprecate this behavior. b/18413862
... | [
"Extends by appending the given iterable. Similar to list.extend()."
] |
Please provide a description of the function:def MergeFrom(self, other):
self._values.extend(other._values)
self._message_listener.Modified() | [
"Appends the contents of another repeated field of the same type to this\n one. We do not check the types of the individual fields.\n "
] |
Please provide a description of the function:def remove(self, elem):
self._values.remove(elem)
self._message_listener.Modified() | [
"Removes an item from the list. Similar to list.remove()."
] |
Please provide a description of the function:def pop(self, key=-1):
value = self._values[key]
self.__delitem__(key)
return value | [
"Removes and returns an item at a given index. Similar to list.pop()."
] |
Please provide a description of the function:def add(self, **kwargs):
new_element = self._message_descriptor._concrete_class(**kwargs)
new_element._SetListener(self._message_listener)
self._values.append(new_element)
if not self._message_listener.dirty:
self._message_listener.Modified()
r... | [
"Adds a new element at the end of the list and returns it. Keyword\n arguments may be used to initialize the element.\n "
] |
Please provide a description of the function:def extend(self, elem_seq):
message_class = self._message_descriptor._concrete_class
listener = self._message_listener
values = self._values
for message in elem_seq:
new_element = message_class()
new_element._SetListener(listener)
new_e... | [
"Extends by appending the given sequence of elements of the same type\n as this one, copying each individual message.\n "
] |
Please provide a description of the function:def difference (b, a):
a = set(a)
result = []
for item in b:
if item not in a:
result.append(item)
return result | [
" Returns the elements of B that are not in A.\n "
] |
Please provide a description of the function:def intersection (set1, set2):
assert is_iterable(set1)
assert is_iterable(set2)
result = []
for v in set1:
if v in set2:
result.append (v)
return result | [
" Removes from set1 any items which don't appear in set2 and returns the result.\n "
] |
Please provide a description of the function:def contains (small, large):
small = to_seq (small)
large = to_seq (large)
for s in small:
if not s in large:
return False
return True | [
" Returns true iff all elements of 'small' exist in 'large'.\n "
] |
Please provide a description of the function:def equal (a, b):
assert is_iterable(a)
assert is_iterable(b)
return contains (a, b) and contains (b, a) | [
" Returns True iff 'a' contains the same elements as 'b', irrespective of their order.\n # TODO: Python 2.4 has a proper set class.\n "
] |
Please provide a description of the function:def annotate(data, image_column=None, annotation_column='annotations'):
# Check Value of Column Variables
if image_column == None:
image_column = _tkutl._find_only_image_column(data)
if image_column == None:
raise ValueError("'image_... | [
"\n Annotate your images loaded in either an SFrame or SArray Format\n\n The annotate util is a GUI assisted application used to create labels in\n SArray Image data. Specifying a column, with dtype Image, in an SFrame\n works as well since SFrames are composed of multiple SArrays.\n\n ... |
Please provide a description of the function:def recover_annotation():
empty_instance = __tc.extensions.ImageClassification()
annotation_wrapper = empty_instance.get_annotation_registry()
return annotation_wrapper.annotation_sframe | [
"\n Recover the last annotated SFrame.\n \n If you annotate an SFrame and forget to assign it to a variable, this\n function allows you to recover the last annotated SFrame.\n \n Returns\n -------\n\n out : SFrame\n A new SFrame that contains the re... |
Please provide a description of the function:def convert(model, input_features, output_features):
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
# Set the interface params.
spec = _Model_pb2.Model()
spec.specificationVersion = S... | [
"Convert a DictVectorizer model to the protobuf spec.\n\n Parameters\n ----------\n model: DictVectorizer\n A fitted DictVectorizer model.\n\n input_features: str\n Name of the input column.\n\n output_features: str\n Name of the output column.\n\n Returns\n -------\n mo... |
Please provide a description of the function:def print_callback(val):
success = False
try:
# for reasons I cannot fathom, regular printing, even directly
# to io.stdout does not work.
# I have to intrude rather deep into IPython to make it behave
if have_ipython:
... | [
"\n Internal function.\n This function is called via a call back returning from IPC to Cython\n to Python. It tries to perform incremental printing to IPython Notebook or\n Jupyter Notebook and when all else fails, just prints locally.\n "
] |
Please provide a description of the function:def run(toolkit_name, options, verbose=True, show_progress=False):
unity = glconnect.get_unity()
if (not verbose):
glconnect.get_server().set_log_progress(False)
(success, message, params) = unity.run_toolkit(toolkit_name, options)
if (len(mess... | [
"\n Internal function to execute toolkit on the turicreate server.\n\n Parameters\n ----------\n toolkit_name : string\n The name of the toolkit.\n\n options : dict\n A map containing the required input for the toolkit function,\n for example: {'graph': g, 'reset_prob': 0.15}.\n\... |
Please provide a description of the function:def _RoundTowardZero(value, divider):
# For some languanges, the sign of the remainder is implementation
# dependent if any of the operands is negative. Here we enforce
# "rounded toward zero" semantics. For example, for (-5) / 2 an
# implementation may give -3 as... | [
"Truncates the remainder part after division."
] |
Please provide a description of the function:def _IsValidPath(message_descriptor, path):
parts = path.split('.')
last = parts.pop()
for name in parts:
field = message_descriptor.fields_by_name[name]
if (field is None or
field.label == FieldDescriptor.LABEL_REPEATED or
field.type != Fiel... | [
"Checks whether the path is valid for Message Descriptor."
] |
Please provide a description of the function:def _CheckFieldMaskMessage(message):
message_descriptor = message.DESCRIPTOR
if (message_descriptor.name != 'FieldMask' or
message_descriptor.file.name != 'google/protobuf/field_mask.proto'):
raise ValueError('Message {0} is not a FieldMask.'.format(
... | [
"Raises ValueError if message is not a FieldMask."
] |
Please provide a description of the function:def _SnakeCaseToCamelCase(path_name):
result = []
after_underscore = False
for c in path_name:
if c.isupper():
raise Error('Fail to print FieldMask to Json string: Path name '
'{0} must not contain uppercase letters.'.format(path_name))
... | [
"Converts a path name from snake_case to camelCase."
] |
Please provide a description of the function:def _CamelCaseToSnakeCase(path_name):
result = []
for c in path_name:
if c == '_':
raise ParseError('Fail to parse FieldMask: Path name '
'{0} must not contain "_"s.'.format(path_name))
if c.isupper():
result += '_'
res... | [
"Converts a field name from camelCase to snake_case."
] |
Please provide a description of the function:def _MergeMessage(
node, source, destination, replace_message, replace_repeated):
source_descriptor = source.DESCRIPTOR
for name in node:
child = node[name]
field = source_descriptor.fields_by_name[name]
if field is None:
raise ValueError('Error:... | [
"Merge all fields specified by a sub-tree from source to destination."
] |
Please provide a description of the function:def _AddFieldPaths(node, prefix, field_mask):
if not node:
field_mask.paths.append(prefix)
return
for name in sorted(node):
if prefix:
child_path = prefix + '.' + name
else:
child_path = name
_AddFieldPaths(node[name], child_path, field... | [
"Adds the field paths descended from node to field_mask."
] |
Please provide a description of the function:def Pack(self, msg, type_url_prefix='type.googleapis.com/'):
if len(type_url_prefix) < 1 or type_url_prefix[-1] != '/':
self.type_url = '%s/%s' % (type_url_prefix, msg.DESCRIPTOR.full_name)
else:
self.type_url = '%s%s' % (type_url_prefix, msg.DESCRIP... | [
"Packs the specified message into current Any message."
] |
Please provide a description of the function:def Unpack(self, msg):
descriptor = msg.DESCRIPTOR
if not self.Is(descriptor):
return False
msg.ParseFromString(self.value)
return True | [
"Unpacks the current Any message into specified message."
] |
Please provide a description of the function:def ToJsonString(self):
nanos = self.nanos % _NANOS_PER_SECOND
total_sec = self.seconds + (self.nanos - nanos) // _NANOS_PER_SECOND
seconds = total_sec % _SECONDS_PER_DAY
days = (total_sec - seconds) // _SECONDS_PER_DAY
dt = datetime(1970, 1, 1) + ti... | [
"Converts Timestamp to RFC 3339 date string format.\n\n Returns:\n A string converted from timestamp. The string is always Z-normalized\n and uses 3, 6 or 9 fractional digits as required to represent the\n exact time. Example of the return format: '1972-01-01T10:00:20.021Z'\n "
] |
Please provide a description of the function:def FromJsonString(self, value):
timezone_offset = value.find('Z')
if timezone_offset == -1:
timezone_offset = value.find('+')
if timezone_offset == -1:
timezone_offset = value.rfind('-')
if timezone_offset == -1:
raise ParseError(
... | [
"Parse a RFC 3339 date string format to Timestamp.\n\n Args:\n value: A date string. Any fractional digits (or none) and any offset are\n accepted as long as they fit into nano-seconds precision.\n Example of accepted format: '1972-01-01T10:00:20.021-05:00'\n\n Raises:\n ParseError... |
Please provide a description of the function:def FromNanoseconds(self, nanos):
self.seconds = nanos // _NANOS_PER_SECOND
self.nanos = nanos % _NANOS_PER_SECOND | [
"Converts nanoseconds since epoch to Timestamp."
] |
Please provide a description of the function:def FromMicroseconds(self, micros):
self.seconds = micros // _MICROS_PER_SECOND
self.nanos = (micros % _MICROS_PER_SECOND) * _NANOS_PER_MICROSECOND | [
"Converts microseconds since epoch to Timestamp."
] |
Please provide a description of the function:def FromMilliseconds(self, millis):
self.seconds = millis // _MILLIS_PER_SECOND
self.nanos = (millis % _MILLIS_PER_SECOND) * _NANOS_PER_MILLISECOND | [
"Converts milliseconds since epoch to Timestamp."
] |
Please provide a description of the function:def ToDatetime(self):
return datetime.utcfromtimestamp(
self.seconds + self.nanos / float(_NANOS_PER_SECOND)) | [
"Converts Timestamp to datetime."
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.