INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Convert a _imputer model to the protobuf spec.
Parameters
----------
model: Imputer
A trained Imputer model.
input_features: str
Name of the input column.
output_features: str
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
... | def convert(model, input_features, output_features):
"""Convert a _imputer model to the protobuf spec.
Parameters
----------
model: Imputer
A trained Imputer model.
input_features: str
Name of the input column.
output_features: str
Name of the output column.
Retur... |
Common utilities to set the regression interface params. | def set_classifier_interface_params(spec, features, class_labels,
model_accessor_for_class_labels, output_features = None):
"""
Common utilities to set the regression interface params.
"""
# Normalize the features list.
features = _fm.process_or_validate_features(features)
if class_labe... |
Common utilities to set the regressor interface params. | def set_regressor_interface_params(spec, features, output_features):
""" Common utilities to set the regressor interface params.
"""
if output_features is None:
output_features = [("predicted_class", datatypes.Double())]
else:
output_features = _fm.process_or_validate_features(output_fea... |
Common utilities to set transform interface params. | def set_transform_interface_params(spec, input_features, output_features, are_optional = False):
""" Common utilities to set transform interface params.
"""
input_features = _fm.process_or_validate_features(input_features)
output_features = _fm.process_or_validate_features(output_features)
# Add in... |
Convert SFrame to batch form, where each row contains a sequence of length
predictions_in_chunk * prediction_window, and there is a single label per
prediction window. | def prep_data(data, features, session_id, prediction_window, predictions_in_chunk, target=None, verbose=True):
"""
Convert SFrame to batch form, where each row contains a sequence of length
predictions_in_chunk * prediction_window, and there is a single label per
prediction window.
"""
if target... |
Loads into numpy array from SFrame, assuming SFrame stores data flattened | def _load_into_numpy(sf, np_array, start, end, strides=None, shape=None):
"""Loads into numpy array from SFrame, assuming SFrame stores data flattened"""
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_a... |
Set the inputs of the network spec.
Parameters
----------
input_names: [str]
List of input names of the network.
input_dims: [tuple]
List of input dimensions of the network. The ordering of input_dims
is the same as input_names.
Examples
... | def set_input(self, input_names, input_dims):
"""
Set the inputs of the network spec.
Parameters
----------
input_names: [str]
List of input names of the network.
input_dims: [tuple]
List of input dimensions of the network. The ordering of input_... |
Set the outputs of the network spec.
Parameters
----------
output_names: [str]
List of output names of the network.
output_dims: [tuple]
List of output dimensions of the network. The ordering of output_dims is the same
as output_names.
Examp... | def set_output(self, output_names, output_dims):
"""
Set the outputs of the network spec.
Parameters
----------
output_names: [str]
List of output names of the network.
output_dims: [tuple]
List of output dimensions of the network. The ordering o... |
Set class labels to the model spec to make it a neural network classifier.
Parameters
----------
class_labels: list[int or str]
A list of integers or strings that map the index of the output of a
neural network to labels in a classifier.
predicted_feature_name: ... | def set_class_labels(self, class_labels, predicted_feature_name = 'classLabel', prediction_blob = ''):
"""
Set class labels to the model spec to make it a neural network classifier.
Parameters
----------
class_labels: list[int or str]
A list of integers or strings th... |
Add optional inputs and outputs to the model spec.
Parameters
----------
optionals_in: [str]
List of inputs that are optionals.
optionals_out: [str]
List of outputs that are optionals.
See Also
--------
set_input, set_output | def add_optionals(self, optionals_in, optionals_out):
"""
Add optional inputs and outputs to the model spec.
Parameters
----------
optionals_in: [str]
List of inputs that are optionals.
optionals_out: [str]
List of outputs that are optionals.
... |
Add an embedding layer to the model.
Parameters
----------
name: str
The name of this layer
W: numpy.array
Weight matrix of shape (output_channels, input_dim).
b: numpy.array
Bias vector of shape (output_channels, ).
input_dim: int
... | def add_embedding(self, name, W, b, input_dim, output_channels, has_bias,
input_name, output_name):
"""
Add an embedding layer to the model.
Parameters
----------
name: str
The name of this layer
W: numpy.array
Weight matrix ... |
Add a softmax layer to the model.
Parameters
----------
name: str
The name of this layer.
input_name: str
The input blob name of this layer.
output_name: str
The output blob name of this layer.
See Also
--------
add_ac... | def add_softmax(self, name, input_name, output_name):
"""
Add a softmax layer to the model.
Parameters
----------
name: str
The name of this layer.
input_name: str
The input blob name of this layer.
output_name: str
The output ... |
Add an activation layer to the model.
Parameters
----------
name: str
The name of this layer
non_linearity: str
The non_linearity (activation) function of this layer.
It can be one of the following:
- 'RELU': Rectified Linear Unit (Re... | def add_activation(self, name, non_linearity, input_name, output_name,
params=None):
"""
Add an activation layer to the model.
Parameters
----------
name: str
The name of this layer
non_linearity: str
The non_linearity (activation) functio... |
Add an element-wise operation layer to the model.
Parameters
----------
The name of this layer
name: str
input_names: [str]
A list of input blob names of this layer. The input blobs should have the same shape.
output_name: str
The output blob ... | def add_elementwise(self, name, input_names, output_name, mode, alpha = None):
"""
Add an element-wise operation layer to the model.
Parameters
----------
The name of this layer
name: str
input_names: [str]
A list of input blob names of this layer... |
Add upsample layer to the model.
Parameters
----------
name: str
The name of this layer.
scaling_factor_h: int
Scaling factor on the vertical direction.
scaling_factor_w: int
Scaling factor on the horizontal direction.
input_name: str
... | def add_upsample(self, name, scaling_factor_h, scaling_factor_w, input_name, output_name, mode = 'NN'):
"""
Add upsample layer to the model.
Parameters
----------
name: str
The name of this layer.
scaling_factor_h: int
Scaling factor on the vertic... |
Add scale layer to the model.
Parameters
----------
name: str
The name of this layer.
W: int | numpy.array
Scale of the input.
b: int | numpy.array
Bias to add to the input.
has_bias: boolean
Whether the bias vector of this... | def add_scale(self, name, W, b, has_bias, input_name, output_name, shape_scale = [1], shape_bias = [1]):
"""
Add scale layer to the model.
Parameters
----------
name: str
The name of this layer.
W: int | numpy.array
Scale of the input.
b: ... |
Add bias layer to the model.
Parameters
----------
name: str
The name of this layer.
b: int | numpy.array
Bias to add to the input.
input_name: str
The input blob name of this layer.
output_name: str
The output blob name of... | def add_bias(self, name, b, input_name, output_name, shape_bias = [1]):
"""
Add bias layer to the model.
Parameters
----------
name: str
The name of this layer.
b: int | numpy.array
Bias to add to the input.
input_name: str
The... |
Add sequence repeat layer to the model.
Parameters
----------
name: str
The name of this layer.
nrep: int
Number of repetitions of the input blob along the sequence axis.
input_name: str
The input blob name of this layer.
output_name: ... | def add_sequence_repeat(self, name, nrep, input_name, output_name):
"""
Add sequence repeat layer to the model.
Parameters
----------
name: str
The name of this layer.
nrep: int
Number of repetitions of the input blob along the sequence axis.
... |
Add a convolution layer to the network.
Please see the ConvolutionLayerParams in Core ML neural network
protobuf message for more information about input and output blob dimensions.
Parameters
----------
name: str
The name of this layer.
kernel_channels: int... | 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',
dilation_factors = [1,1],
paddi... |
Add a padding layer to the model. Kindly refer to NeuralNetwork.proto for details.
Parameters
----------
name: str
The name of this layer.
left: int
Number of elements to be padded on the left side of the input blob.
right: int
Number of eleme... | def add_padding(self, name,
left = 0, right = 0, top = 0, bottom = 0,
value = 0,
input_name = 'data', output_name = 'out',
padding_type = 'constant'):
"""
Add a padding layer to the model. Kindly refer to NeuralNetwork.proto for details.
Parameter... |
Add a cropping layer to the model.
The cropping layer have two functional modes:
- When it has 1 input blob, it crops the input blob based
on the 4 parameters [left, right, top, bottom].
- When it has 2 input blobs, it crops the first input blob based
on the ... | def add_crop(self, name, left, right, top, bottom, offset, input_names,
output_name):
"""
Add a cropping layer to the model.
The cropping layer have two functional modes:
- When it has 1 input blob, it crops the input blob based
on the 4 parameters [left, r... |
Add a simple recurrent layer to the model.
Parameters
----------
name: str
The name of this layer.
W_h: numpy.array
Weights of the recurrent layer's hidden state. Must be of shape (hidden_size, hidden_size).
W_x: numpy.array
Weights of the rec... | 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):
"""
Add a simple recurrent layer to the model.
Parameters
----------
name: str
The name of this layer.
W_h: ... |
Add a Gated-Recurrent Unit (GRU) layer to the model.
Parameters
----------
name: str
The name of this layer.
W_h: [numpy.array]
List of recursion weight matrices. The ordering is [R_z, R_r, R_o],
where R_z, R_r and R_o are weight matrices at update ga... | 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):
"""
Add a Gated-Recurrent Unit (GRU) layer to the model.
Parameters
------... |
Add a Uni-directional LSTM layer to the model.
Parameters
----------
name: str
The name of this layer.
W_h: [numpy.array]
List of recursion weight matrices. The ordering is [R_i, R_f, R_o, R_z],
where R_i, R_f, R_o, R_z are weight matrices at input ga... | 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 = None,
output_all = Fals... |
Add a Bi-directional LSTM layer to the model.
Parameters
----------
name: str
The name of this layer.
W_h: [numpy.array]
List of recursion weight matrices for the forward layer. The ordering is [R_i, R_f, R_o, R_z],
where R_i, R_f, R_o, R_z are weight... | 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',
peep = None, peep_back = None,
... |
Add a flatten layer. Only flattens the channel, height and width axis. Leaves the sequence axis as is.
Parameters
----------
name: str
The name of this layer.
mode: int
- If mode == 0, the flatten layer is in CHANNEL_FIRST mode.
- If mode == 1, the f... | def add_flatten(self, name, mode, input_name, output_name):
"""
Add a flatten layer. Only flattens the channel, height and width axis. Leaves the sequence axis as is.
Parameters
----------
name: str
The name of this layer.
mode: int
- If mode == ... |
Add a slice layer. Equivalent to to numpy slice [start_index:end_index:stride],
start_index is included, while end_index is exclusive.
Parameters
----------
name: str
The name of this layer.
input_name: str
The input blob name of this layer.
outp... | def add_slice(self, name, input_name, output_name, axis, start_index = 0, end_index = -1, stride = 1):
"""
Add a slice layer. Equivalent to to numpy slice [start_index:end_index:stride],
start_index is included, while end_index is exclusive.
Parameters
----------
name: s... |
Add a data reorganization layer of type "SPACE_TO_DEPTH" or "DEPTH_TO_SPACE".
Parameters
----------
name: str
The name of this layer.
input_name: str
The input blob name of this layer.
output_name: str
The output blob name of this layer.
... | def add_reorganize_data(self, name, input_name, output_name, mode = 'SPACE_TO_DEPTH', block_size = 2):
"""
Add a data reorganization layer of type "SPACE_TO_DEPTH" or "DEPTH_TO_SPACE".
Parameters
----------
name: str
The name of this layer.
input_name: str
... |
Add a Batch Normalization layer. Batch Normalization operation is
defined as:
`y = gamma * (x - mean) / sqrt(variance + epsilon) + beta`
Parameters
----------
name: str
The name of this layer.
channels: int
Number of channels of the input blob.
... | 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, epsilon = 1e-5):
"""
Add a Batch ... |
Add a permute layer. Assumes that the input has dimensions in the order [Seq, C, H, W]
Parameters
----------
name: str
The name of this layer.
dim: tuple
The order in which to permute the input dimensions = [seq,C,H,W].
Must have length 4 and a permut... | def add_permute(self, name, dim, input_name, output_name):
"""
Add a permute layer. Assumes that the input has dimensions in the order [Seq, C, H, W]
Parameters
----------
name: str
The name of this layer.
dim: tuple
The order in which to permute ... |
Add a reshape layer. Kindly refer to NeuralNetwork.proto for details.
Parameters
----------
name: str
The name of this layer.
target_shape: tuple
Shape of the output blob. The product of target_shape must be equal
to the shape of the input blob.
... | def add_reshape(self, name, input_name, output_name, target_shape, mode):
"""
Add a reshape layer. Kindly refer to NeuralNetwork.proto for details.
Parameters
----------
name: str
The name of this layer.
target_shape: tuple
Shape of the output blo... |
Add a reduce layer. Applies the function specified by the parameter mode,
along dimension(s) specified by the parameter axis.
Parameters
----------
name: str
The name of this layer.
input_name: str
The input blob name of this layer.
output_name: ... | def add_reduce(self, name, input_name, output_name, axis, mode, epsilon = 1e-6):
"""
Add a reduce layer. Applies the function specified by the parameter mode,
along dimension(s) specified by the parameter axis.
Parameters
----------
name: str
The name of this... |
Add a LRN (local response normalization) layer. Please see the LRNLayerParams message in Core ML neural network
protobuf for more information about the operation of this layer. Supports "across" channels normalization.
Parameters
----------
name: str
The name of this layer.
... | def add_lrn(self, name, input_name, output_name, alpha, beta, local_size, k = 1.0):
"""
Add a LRN (local response normalization) layer. Please see the LRNLayerParams message in Core ML neural network
protobuf for more information about the operation of this layer. Supports "across" channels norm... |
Add an MVN (mean variance normalization) layer. Computes mean, variance and normalizes the input.
Parameters
----------
name: str
The name of this layer.
input_name: str
The input blob name of this layer.
output_name: str
The output blob name... | def add_mvn(self, name, input_name, output_name, across_channels = True, normalize_variance = True, epsilon = 1e-5):
"""
Add an MVN (mean variance normalization) layer. Computes mean, variance and normalizes the input.
Parameters
----------
name: str
The name of this... |
Add L2 normalize layer. Normalizes the input by the L2 norm, i.e. divides by the
the square root of the sum of squares of all elements of the input along C, H and W dimensions.
Parameters
----------
name: str
The name of this layer.
input_name: str
The i... | def add_l2_normalize(self, name, input_name, output_name, epsilon = 1e-5):
"""
Add L2 normalize layer. Normalizes the input by the L2 norm, i.e. divides by the
the square root of the sum of squares of all elements of the input along C, H and W dimensions.
Parameters
----------
... |
Add a Unary layer. Applies the specified function (mode) to all the elements of the input.
Please see the UnaryFunctionLayerParams message in Core ML neural network
protobuf for more information about the operation of this layer.
Prior to the application of the function the input can be scaled a... | def add_unary(self, name, input_name, output_name, mode, alpha = 1.0,
shift = 0, scale = 1.0, epsilon = 1e-6):
"""
Add a Unary layer. Applies the specified function (mode) to all the elements of the input.
Please see the UnaryFunctionLayerParams message in Core ML neural netw... |
Add a Split layer that uniformly splits the input along the channel dimension
to produce multiple outputs.
Parameters
----------
name: str
The name of this layer.
input_name: str
The input blob name of this layer.
output_names: [str]
... | def add_split(self, name, input_name, output_names):
"""
Add a Split layer that uniformly splits the input along the channel dimension
to produce multiple outputs.
Parameters
----------
name: str
The name of this layer.
input_name: str
Th... |
Add a load constant layer.
Parameters
----------
name: str
The name of this layer.
output_name: str
The output blob name of this layer.
constant_value: numpy.array
value of the constant as a numpy array.
shape: [int]
Lis... | def add_load_constant(self, name, output_name, constant_value, shape):
"""
Add a load constant layer.
Parameters
----------
name: str
The name of this layer.
output_name: str
The output blob name of this layer.
constant_value: numpy.arra... |
Add a custom layer.
Parameters
----------
name: str
The name of this layer.
input_names: [str]
The input blob names to this layer.
output_names: [str]
The output blob names from this layer.
custom_proto_spec: CustomLayerParams
... | def add_custom(self, name, input_names, output_names, custom_proto_spec = None):
"""
Add a custom layer.
Parameters
----------
name: str
The name of this layer.
input_names: [str]
The input blob names to this layer.
output_names: [str]
... |
Add pre-processing parameters to the neural network object
Parameters
----------
image_input_names: [str]
Name of input blobs that are images
is_bgr: boolean | dict()
Channel order for input blobs that are images. BGR if True else RGB.
To specify a d... | 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):
"""Add pre-processing parameters to the neural network object
Parameters
----------
image_input_names: [str... |
Registers a new generator class, specifying a set of
properties relevant to this scanner. Ctor for that class
should have one parameter: list of properties. | def register(scanner_class, relevant_properties):
""" Registers a new generator class, specifying a set of
properties relevant to this scanner. Ctor for that class
should have one parameter: list of properties.
"""
assert issubclass(scanner_class, Scanner)
assert isinstance(relevant_pro... |
Returns an instance of previously registered scanner
with the specified properties. | def get(scanner_class, properties):
""" Returns an instance of previously registered scanner
with the specified properties.
"""
assert issubclass(scanner_class, Scanner)
assert is_iterable_typed(properties, basestring)
scanner_name = str(scanner_class)
if not registered(scanner_name):
... |
Installs the specified scanner on actual target 'target'.
vtarget: virtual target from which 'target' was actualized. | def install (self, scanner, target, vtarget):
""" Installs the specified scanner on actual target 'target'.
vtarget: virtual target from which 'target' was actualized.
"""
assert isinstance(scanner, Scanner)
assert isinstance(target, basestring)
assert isinstance(vtar... |
Fills in the rest of function data into the skeleton function object
that were created via _make_skel_func(). | def _fill_function(func, globals, defaults, dict, module, closure_values):
""" Fills in the rest of function data into the skeleton function object
that were created via _make_skel_func().
"""
func.__globals__.update(globals)
func.__defaults__ = defaults
func.__dict__ = dict
func.__modul... |
Creates a skeleton function object that contains just the provided
code and the correct number of cells in func_closure. All other
func attributes (e.g. func_globals) are empty. | def _make_skel_func(code, cell_count, base_globals=None):
""" Creates a skeleton function object that contains just the provided
code and the correct number of cells in func_closure. All other
func attributes (e.g. func_globals) are empty.
"""
if base_globals is None:
base_globals =... |
Put attributes from `class_dict` back on `skeleton_class`.
See CloudPickler.save_dynamic_class for more info. | def _rehydrate_skeleton_class(skeleton_class, class_dict):
"""Put attributes from `class_dict` back on `skeleton_class`.
See CloudPickler.save_dynamic_class for more info.
"""
for attrname, attr in class_dict.items():
setattr(skeleton_class, attrname, attr)
return skeleton_class |
Iterate over each part instead of calling imp.find_module directly.
This function is able to find submodules (e.g. sickit.tree) | def _find_module(mod_name):
"""
Iterate over each part instead of calling imp.find_module directly.
This function is able to find submodules (e.g. sickit.tree)
"""
path = None
for part in mod_name.split('.'):
if path is not None:
path = [path]
file, path, description ... |
Save a module as an import | def save_module(self, obj):
"""
Save a module as an import
"""
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:
... |
Ensure de-pickler imports any package child-modules that
are needed by the function | def _save_subimports(self, code, top_level_dependencies):
"""
Ensure de-pickler imports any package child-modules that
are needed by the function
"""
# check if any known dependency is an imported package
for x in top_level_dependencies:
if isinstance(x, types... |
Save a class that can't be stored as module global.
This method is used to serialize classes that are defined inside
functions, or that otherwise can't be serialized as attribute lookups
from global modules. | def save_dynamic_class(self, obj):
"""
Save a class that can't be stored as module global.
This method is used to serialize classes that are defined inside
functions, or that otherwise can't be serialized as attribute lookups
from global modules.
"""
clsdict = di... |
Pickles an actual func object.
A func comprises: code, globals, defaults, closure, and dict. We
extract and save these, injecting reducing functions at certain points
to recreate the func object. Keep in mind that some of these pieces
can contain a ref to the func itself. Thus, a nai... | def save_function_tuple(self, func):
""" Pickles an actual func object.
A func comprises: code, globals, defaults, closure, and dict. We
extract and save these, injecting reducing functions at certain points
to recreate the func object. Keep in mind that some of these pieces
... |
Find all globals names read or written to by codeblock co | def extract_code_globals(cls, co):
"""
Find all globals names read or written to by codeblock co
"""
out_names = cls._extract_code_globals_cache.get(co)
if out_names is None:
try:
names = co.co_names
except AttributeError:
#... |
Save a "global".
The name of this method is somewhat misleading: all types get
dispatched here. | def save_global(self, obj, name=None, pack=struct.pack):
"""
Save a "global".
The name of this method is somewhat misleading: all types get
dispatched here.
"""
if obj.__module__ == "__builtin__" or obj.__module__ == "builtins":
if obj in _BUILTIN_TYPE_NAMES:... |
Modified to support __transient__ on new objects
Change only affects protocol level 2 (which is always used by PiCloud | def save_reduce(self, func, args, state=None,
listitems=None, dictitems=None, obj=None):
"""Modified to support __transient__ on new objects
Change only affects protocol level 2 (which is always used by PiCloud"""
# Assert that args is a tuple or None
if not isinstanc... |
Partial objects do not serialize correctly in python2.x -- this fixes the bugs | def save_partial(self, obj):
"""Partial objects do not serialize correctly in python2.x -- this fixes the bugs"""
self.save_reduce(_genpartial, (obj.func, obj.args, obj.keywords)) |
Save a file | def save_file(self, obj):
"""Save a file"""
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'):
raise pickle.Pi... |
Hack function for saving numpy ufunc objects | def save_ufunc(self, obj):
"""Hack function for saving numpy ufunc objects"""
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__:... |
Pulls out all the symbols from a descriptor proto.
Args:
desc_proto: The proto to extract symbols from.
package: The package containing the descriptor type.
Yields:
The fully qualified name found in the descriptor. | def _ExtractSymbols(desc_proto, package):
"""Pulls out all the symbols from a descriptor proto.
Args:
desc_proto: The proto to extract symbols from.
package: The package containing the descriptor type.
Yields:
The fully qualified name found in the descriptor.
"""
message_name = '.'.join((packag... |
Adds the FileDescriptorProto and its types to this database.
Args:
file_desc_proto: The FileDescriptorProto to add.
Raises:
DescriptorDatabaseConflictingDefinitionError: if an attempt is made to
add a proto with the same name but different definition than an
exisiting proto in the d... | def Add(self, file_desc_proto):
"""Adds the FileDescriptorProto and its types to this database.
Args:
file_desc_proto: The FileDescriptorProto to add.
Raises:
DescriptorDatabaseConflictingDefinitionError: if an attempt is made to
add a proto with the same name but different definition t... |
Convert a normalizer model to the protobuf spec.
Parameters
----------
model: Normalizer
A Normalizer.
input_features: str
Name of the input column.
output_features: str
Name of the output column.
Returns
-------
model_spec: An object of type Model_pb.
... | def convert(model, input_features, output_features):
"""Convert a normalizer model to the protobuf spec.
Parameters
----------
model: Normalizer
A Normalizer.
input_features: str
Name of the input column.
output_features: str
Name of the output column.
Returns
... |
customized submit script, that submit nslave jobs, each must contain args as parameter
note this can be a lambda function containing additional parameters in input
Parameters
nslave number of slave process to start up
args arguments to launch each job
this usually includes th... | def mpi_submit(nslave, worker_args, worker_envs):
"""
customized submit script, that submit nslave jobs, each must contain args as parameter
note this can be a lambda function containing additional parameters in input
Parameters
nslave number of slave process to start up
args arg... |
Consume byte-code | 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(self, method_name, generic_consume)
... |
Create a (binary or multi-class) classifier model of type
:class:`~turicreate.random_forest_classifier.RandomForestClassifier` using
an ensemble of decision trees trained on subsets of the data.
Parameters
----------
dataset : SFrame
A training dataset containing feature columns and a targe... | def create(dataset, target,
features=None,
max_iterations=10,
validation_set='auto',
verbose=True, class_weights=None,
random_seed=None,
metric='auto',
**kwargs):
"""
Create a (binary or multi-class) classifier model of type
:class... |
Return a classification, for each example in the ``dataset``, using the
trained random forest model. The output SFrame contains predictions
as class labels (0 or 1) and probabilities associated with the the example.
Parameters
----------
dataset : SFrame
Dataset of n... | def classify(self, dataset, missing_value_action='auto'):
"""
Return a classification, for each example in the ``dataset``, using the
trained random forest model. The output SFrame contains predictions
as class labels (0 or 1) and probabilities associated with the the example.
P... |
Get the right converter function for Keras | def _get_layer_converter_fn(layer):
"""Get the right converter function for Keras
"""
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)) |
Convert a Keras model to Core ML protobuf specification (.mlmodel).
Parameters
----------
model: Keras model object | str | (str, str)
A trained Keras neural network model which can be one of the following:
- a Keras model object
- a string with the path to a Keras model file (h5)
... | def convertToSpec(model,
input_names = None,
output_names = None,
image_input_names = None,
input_name_shape_dict = {},
is_bgr = False,
red_bias = 0.0,
green_bias = 0.0,
blue_b... |
Convert a Keras model to Core ML protobuf specification (.mlmodel).
Parameters
----------
model: Keras model object | str | (str, str)
A trained Keras neural network model which can be one of the following:
- a Keras model object
- a string with the path to a Keras model file (h5)... | def convert(model,
input_names = None,
output_names = None,
image_input_names = None,
input_name_shape_dict = {},
is_bgr = False,
red_bias = 0.0,
green_bias = 0.0,
blue_bias = ... |
Convert a boosted tree model to protobuf format.
Parameters
----------
decision_tree : RandomForestRegressor
A trained scikit-learn tree model.
feature_names: [str]
Name of the input columns.
target: str
Name of the output column.
Returns
-------
model_spec: A... | def convert(model, feature_names, target):
"""Convert a boosted tree model to protobuf format.
Parameters
----------
decision_tree : RandomForestRegressor
A trained scikit-learn tree model.
feature_names: [str]
Name of the input columns.
target: str
Name of the output ... |
Create a DBSCAN clustering model. The DBSCAN method partitions the input
dataset into three types of points, based on the estimated probability
density at each point.
- **Core** points have a large number of points within a given neighborhood.
Specifically, `min_core_neighbors` must be within distanc... | def create(dataset, features=None, distance=None, radius=1.,
min_core_neighbors=10, verbose=True):
"""
Create a DBSCAN clustering model. The DBSCAN method partitions the input
dataset into three types of points, based on the estimated probability
density at each point.
- **Core** points ... |
Load find the path to xgboost dynamic library files.
Returns
-------
lib_path: list(string)
List of all found library path to xgboost | def find_lib_path():
"""Load find the path to xgboost dynamic library files.
Returns
-------
lib_path: list(string)
List of all found library path to xgboost
"""
curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__)))
# make pythonpack hack: copy this directory one... |
Check if a model is of the right type. Raise error if not.
Parameters
----------
model: model
Any scikit-learn model
expected_type: Type
Expected type of the scikit-learn. | def check_expected_type(model, expected_type):
"""Check if a model is of the right type. Raise error if not.
Parameters
----------
model: model
Any scikit-learn model
expected_type: Type
Expected type of the scikit-learn.
"""
if (model.__class__.__name__ != expected_type.__... |
Convert a LIBSVM model to Core ML format.
Parameters
----------
model: a libsvm model (C-SVC, nu-SVC, epsilon-SVR, or nu-SVR)
or string path to a saved model.
input_names: str | [str]
Name of the input column(s).
If a single string is used (the default) the input will be an ar... | def convert(model, input_names='input', target_name='target',
probability='classProbability', input_length='auto'):
"""
Convert a LIBSVM model to Core ML format.
Parameters
----------
model: a libsvm model (C-SVC, nu-SVC, epsilon-SVR, or nu-SVR)
or string path to a saved model.... |
Appends an item to the list. Similar to list.append(). | def append(self, value):
"""Appends an item to the list. Similar to list.append()."""
self._values.append(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(). | def insert(self, key, value):
"""Inserts the item at the specified position. Similar to list.insert()."""
self._values.insert(key, self._type_checker.CheckValue(value))
if not self._message_listener.dirty:
self._message_listener.Modified() |
Extends by appending the given iterable. Similar to list.extend(). | def extend(self, elem_seq):
"""Extends by appending the given iterable. Similar to list.extend()."""
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 b... |
Appends the contents of another repeated field of the same type to this
one. We do not check the types of the individual fields. | def MergeFrom(self, other):
"""Appends the contents of another repeated field of the same type to this
one. We do not check the types of the individual fields.
"""
self._values.extend(other._values)
self._message_listener.Modified() |
Removes an item from the list. Similar to list.remove(). | def remove(self, elem):
"""Removes an item from the list. Similar to list.remove()."""
self._values.remove(elem)
self._message_listener.Modified() |
Removes and returns an item at a given index. Similar to list.pop(). | def pop(self, key=-1):
"""Removes and returns an item at a given index. Similar to list.pop()."""
value = self._values[key]
self.__delitem__(key)
return value |
Adds a new element at the end of the list and returns it. Keyword
arguments may be used to initialize the element. | def add(self, **kwargs):
"""Adds a new element at the end of the list and returns it. Keyword
arguments may be used to initialize the element.
"""
new_element = self._message_descriptor._concrete_class(**kwargs)
new_element._SetListener(self._message_listener)
self._values.append(new_element)
... |
Extends by appending the given sequence of elements of the same type
as this one, copying each individual message. | def extend(self, elem_seq):
"""Extends by appending the given sequence of elements of the same type
as this one, copying each individual message.
"""
message_class = self._message_descriptor._concrete_class
listener = self._message_listener
values = self._values
for message in elem_seq:
... |
Returns the elements of B that are not in A. | def difference (b, a):
""" Returns the elements of B that are not in A.
"""
a = set(a)
result = []
for item in b:
if item not in a:
result.append(item)
return result |
Removes from set1 any items which don't appear in set2 and returns the result. | def intersection (set1, set2):
""" Removes from set1 any items which don't appear in set2 and returns the result.
"""
assert is_iterable(set1)
assert is_iterable(set2)
result = []
for v in set1:
if v in set2:
result.append (v)
return result |
Returns true iff all elements of 'small' exist in 'large'. | def contains (small, large):
""" Returns true iff all elements of 'small' exist in 'large'.
"""
small = to_seq (small)
large = to_seq (large)
for s in small:
if not s in large:
return False
return True |
Annotate your images loaded in either an SFrame or SArray Format
The annotate util is a GUI assisted application used to create labels in
SArray Image data. Specifying a column, with dtype Image, in an SFrame
works as well since SFrames are composed of multiple SArrays.
When the GUI is... | def annotate(data, image_column=None, annotation_column='annotations'):
"""
Annotate your images loaded in either an SFrame or SArray Format
The annotate util is a GUI assisted application used to create labels in
SArray Image data. Specifying a column, with dtype Image, in an SFrame
... |
Recover the last annotated SFrame.
If you annotate an SFrame and forget to assign it to a variable, this
function allows you to recover the last annotated SFrame.
Returns
-------
out : SFrame
A new SFrame that contains the recovered annotation data.... | def recover_annotation():
"""
Recover the last annotated SFrame.
If you annotate an SFrame and forget to assign it to a variable, this
function allows you to recover the last annotated SFrame.
Returns
-------
out : SFrame
A new SFrame th... |
Returns True iff 'a' contains the same elements as 'b', irrespective of their order.
# TODO: Python 2.4 has a proper set class. | def equal (a, b):
""" Returns True iff 'a' contains the same elements as 'b', irrespective of their order.
# TODO: Python 2.4 has a proper set class.
"""
assert is_iterable(a)
assert is_iterable(b)
return contains (a, b) and contains (b, a) |
Convert a DictVectorizer model to the protobuf spec.
Parameters
----------
model: DictVectorizer
A fitted DictVectorizer model.
input_features: str
Name of the input column.
output_features: str
Name of the output column.
Returns
-------
model_spec: An object ... | def convert(model, input_features, output_features):
"""Convert a DictVectorizer model to the protobuf spec.
Parameters
----------
model: DictVectorizer
A fitted DictVectorizer model.
input_features: str
Name of the input column.
output_features: str
Name of the output... |
Internal function.
This function is called via a call back returning from IPC to Cython
to Python. It tries to perform incremental printing to IPython Notebook or
Jupyter Notebook and when all else fails, just prints locally. | def print_callback(val):
"""
Internal function.
This function is called via a call back returning from IPC to Cython
to Python. It tries to perform incremental printing to IPython Notebook or
Jupyter Notebook and when all else fails, just prints locally.
"""
success = False
try:
... |
Internal function to execute toolkit on the turicreate server.
Parameters
----------
toolkit_name : string
The name of the toolkit.
options : dict
A map containing the required input for the toolkit function,
for example: {'graph': g, 'reset_prob': 0.15}.
verbose : bool
... | def run(toolkit_name, options, verbose=True, show_progress=False):
"""
Internal function to execute toolkit on the turicreate server.
Parameters
----------
toolkit_name : string
The name of the toolkit.
options : dict
A map containing the required input for the toolkit function... |
Truncates the remainder part after division. | def _RoundTowardZero(value, divider):
"""Truncates the remainder part after division."""
# 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 ... |
Checks whether the path is valid for Message Descriptor. | def _IsValidPath(message_descriptor, path):
"""Checks whether the path is valid for Message Descriptor."""
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
f... |
Raises ValueError if message is not a FieldMask. | def _CheckFieldMaskMessage(message):
"""Raises ValueError if message is not a FieldMask."""
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... |
Converts a path name from snake_case to camelCase. | def _SnakeCaseToCamelCase(path_name):
"""Converts a path name from snake_case to camelCase."""
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(pa... |
Converts a field name from camelCase to snake_case. | def _CamelCaseToSnakeCase(path_name):
"""Converts a field name from camelCase to snake_case."""
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 += '... |
Merge all fields specified by a sub-tree from source to destination. | def _MergeMessage(
node, source, destination, replace_message, replace_repeated):
"""Merge all fields specified by a sub-tree from source to destination."""
source_descriptor = source.DESCRIPTOR
for name in node:
child = node[name]
field = source_descriptor.fields_by_name[name]
if field is None:
... |
Adds the field paths descended from node to field_mask. | def _AddFieldPaths(node, prefix, field_mask):
"""Adds the field paths descended from node to 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], c... |
Packs the specified message into current Any message. | def Pack(self, msg, type_url_prefix='type.googleapis.com/'):
"""Packs the specified message into current Any message."""
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_prefi... |
Unpacks the current Any message into specified message. | def Unpack(self, msg):
"""Unpacks the current Any message into specified message."""
descriptor = msg.DESCRIPTOR
if not self.Is(descriptor):
return False
msg.ParseFromString(self.value)
return True |
Converts Timestamp to RFC 3339 date string format.
Returns:
A string converted from timestamp. The string is always Z-normalized
and uses 3, 6 or 9 fractional digits as required to represent the
exact time. Example of the return format: '1972-01-01T10:00:20.021Z' | def ToJsonString(self):
"""Converts Timestamp to RFC 3339 date string format.
Returns:
A string converted from timestamp. The string is always Z-normalized
and uses 3, 6 or 9 fractional digits as required to represent the
exact time. Example of the return format: '1972-01-01T10:00:20.021Z'
... |
Parse a RFC 3339 date string format to Timestamp.
Args:
value: A date string. Any fractional digits (or none) and any offset are
accepted as long as they fit into nano-seconds precision.
Example of accepted format: '1972-01-01T10:00:20.021-05:00'
Raises:
ParseError: On parsing ... | def FromJsonString(self, value):
"""Parse a RFC 3339 date string format to Timestamp.
Args:
value: A date string. Any fractional digits (or none) and any offset are
accepted as long as they fit into nano-seconds precision.
Example of accepted format: '1972-01-01T10:00:20.021-05:00'
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.