INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Transforms short text into a dictionary of TFIDF - weighted 3 - gram character counts.
def short_text__str(self, column_name, output_column_prefix): """ Transforms short text into a dictionary of TFIDF-weighted 3-gram character counts. """ from ._ngram_counter import NGramCounter from ._tfidf import TFIDF return [NGramCounter(features=[column_name...
Interprets an integer column as a categorical variable.
def categorical__int(self, column_name, output_column_prefix): """ Interprets an integer column as a categorical variable. """ return [_ColumnFunctionTransformation( features = [column_name], output_column_prefix = output_column_prefix, transform_func...
Sets up the content transforms.
def _setup_from_data(self, data): """ Sets up the content transforms. """ fitted_state = {} _raise_error_if_not_of_type(data, [_SFrame]) feature_columns = _internal_utils.get_column_names(data, self._exclude, self._features) if not feature_columns: ...
Fits a transformer using the SFrame data.
def fit(self, data): """ Fits a transformer using the SFrame `data`. Parameters ---------- data : SFrame The data used to fit the transformer. Returns ------- self (A fitted object) See Also -------- transform, fit_tr...
Fits and transforms the SFrame data using a fitted model.
def fit_transform(self, data): """ Fits and transforms the SFrame `data` using a fitted model. Parameters ---------- data : SFrame The data to be transformed. Returns ------- A transformed SFrame. Returns ------- out...
Transform the SFrame data using a fitted model.
def transform(self, data): """ Transform the SFrame `data` using a fitted model. Parameters ---------- data : SFrame The data to be transformed. Returns ------- A transformed SFrame. Returns ------- out: SFrame ...
Returns a structured description of the model including ( where relevant ) the schema of the training data description of the training data training statistics and model hyperparameters.
def _get_summary_struct(self): """ Returns a structured description of the model, including (where relevant) the schema of the training data, description of the training data, training statistics, and model hyperparameters. Returns ------- sections : list (of lis...
Save the model as a directory which can be loaded with the: py: func: ~turicreate. load_model method.
def _save_impl(self, pickler): """ Save the model as a directory, which can be loaded with the :py:func:`~turicreate.load_model` method. Parameters ---------- pickler : GLPickler An opened GLPickle archive (Do not close the archive). See Also ...
Create a new mock object.
def CreateMock(self, class_to_mock): """Create a new mock object. Args: # class_to_mock: the class to be mocked class_to_mock: class Returns: MockObject that can be used as the class_to_mock would be. """ new_mock = MockObject(class_to_mock) self._mock_objects.append(new_moc...
Replace a method attribute etc. with a Mock.
def StubOutWithMock(self, obj, attr_name, use_mock_anything=False): """Replace a method, attribute, etc. with a Mock. This will replace a class or module with a MockObject, and everything else (method, function, etc) with a MockAnything. This can be overridden to always use a MockAnything by setting u...
Verify that all of the expected calls have been made.
def _Verify(self): """Verify that all of the expected calls have been made. Raises: ExpectedMethodCallsError: if there are still more method calls in the expected queue. """ # If the list of expected calls is not empty, raise an exception if self._expected_calls_queue: # The la...
Verify the called method is expected.
def _VerifyMethodCall(self): """Verify the called method is expected. This can be an ordered method, or part of an unordered set. Returns: The expected mock method. Raises: UnexpectedMethodCall if the method called was not expected. """ expected = self._PopNextMethod() # Loo...
Returns a possible group from the end of the call queue or None if no other methods are on the stack.
def GetPossibleGroup(self): """Returns a possible group from the end of the call queue or None if no other methods are on the stack. """ # Remove this method from the tail of the queue so we can add it to a group. this_method = self._call_queue.pop() assert this_method == self # Determine ...
Checks if the last method ( a possible group ) is an instance of our group_class. Adds the current method to this group or creates a new one.
def _CheckAndCreateNewGroup(self, group_name, group_class): """Checks if the last method (a possible group) is an instance of our group_class. Adds the current method to this group or creates a new one. Args: group_name: the name of the group. group_class: the class used to create instance of ...
Check to see if the RHS is an instance of class_name.
def equals(self, rhs): """Check to see if the RHS is an instance of class_name. Args: # rhs: the right hand side of the test rhs: object Returns: bool """ try: return isinstance(rhs, self._class_name) except TypeError: # Check raw types if there was a type error....
Check to see if RHS is almost equal to float_value
def equals(self, rhs): """Check to see if RHS is almost equal to float_value Args: rhs: the value to compare to float_value Returns: bool """ try: return round(rhs-self._float_value, self._places) == 0 except TypeError: # This is probably because either float_value or ...
Check whether the given key/ value pair is in the rhs dict.
def equals(self, rhs): """Check whether the given key/value pair is in the rhs dict. Returns: bool """ try: return rhs[self._key] == self._value except Exception: return False
Check to see whether actual_seq has same elements as expected_seq.
def equals(self, actual_seq): """Check to see whether actual_seq has same elements as expected_seq. Args: actual_seq: sequence Returns: bool """ try: expected = dict([(element, None) for element in self._expected_seq]) actual = dict([(element, None) for element in actual_s...
Checks whether any Comparator is equal to rhs.
def equals(self, rhs): """Checks whether any Comparator is equal to rhs. Args: # rhs: can be anything Returns: bool """ for comparator in self._comparators: if comparator.equals(rhs): return True return False
Remove a method call from the group.
def MethodCalled(self, mock_method): """Remove a method call from the group. If the method is not in the set, an UnexpectedMethodCallError will be raised. Args: mock_method: a mock method that should be equal to a method in the group. Returns: The mock method from the group Raise...
Remove a method call from the group.
def MethodCalled(self, mock_method): """Remove a method call from the group. If the method is not in the set, an UnexpectedMethodCallError will be raised. Args: mock_method: a mock method that should be equal to a method in the group. Returns: The mock method from the group Raise...
Return True if all methods in this group are called at least once.
def IsSatisfied(self): """Return True if all methods in this group are called at least once.""" # NOTE(psycho): We can't use the simple set difference here because we want # to match different parameters which are considered the same e.g. IsA(str) # and some string. This solution is O(n^2) but n should ...
Convert a _imputer model to the protobuf spec.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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:
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.
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.
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.
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.
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.
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.
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.
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:
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 ]
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.
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.
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.
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.
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.
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 and shifted by using th...
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.
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.
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.
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
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.
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.
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.
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.
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.
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.
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.
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 the parameters of master_uri and parameters pass...
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.
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.
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 ).
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 ).
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.
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.
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.
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.
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.
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