text
stringlengths
81
112k
Annotate an input or output multiArray feature in a Neural Network spec to to accommodate a list of enumerated array shapes :param spec: MLModel The MLModel spec containing the feature :param feature_name: str The name of the image feature for which to add shape information. If the...
Annotate an input or output image feature in a Neural Network spec to to accommodate a list of enumerated image sizes :param spec: MLModel The MLModel spec containing the feature :param feature_name: str The name of the image feature for which to add size information. If the featur...
Annotate an input or output Image feature in a Neural Network spec to to accommodate a range of image sizes :param spec: MLModel The MLModel spec containing the feature :param feature_name: str The name of the Image feature for which to add shape information. If the feature is not ...
Annotate an input or output MLMultiArray feature in a Neural Network spec to accommodate a range of shapes :param spec: MLModel The MLModel spec containing the feature :param feature_name: str The name of the feature for which to add shape range information. If the feature is not f...
For a given model specification, returns a dictionary with a shape range object for each input feature name. def get_allowed_shape_ranges(spec): """ For a given model specification, returns a dictionary with a shape range object for each input feature name. """ shaper = NeuralNetworkShaper(spec, False...
Examines a model specification and determines if it can compute results for more than one output shape. :param spec: MLModel The protobuf specification of the model. :return: Bool Returns True if the model can allow multiple input shapes, False otherwise. def can_allow_multiple_input_shapes(s...
Returns true if any one of the channel, height, or width ranges of this shape allow more than one input value. def isFlexible(self): """ Returns true if any one of the channel, height, or width ranges of this shape allow more than one input value. """ for key, value in self.arrayShapeRa...
Generate a macro definition or undefinition def define_macro(out_f, (name, args, body), undefine=False, check=True): """Generate a macro definition or undefinition""" if undefine: out_f.write( '#undef {0}\n' .format(macro_name(name)) ) else: if args: ...
Generate the filename def filename(out_dir, name, undefine=False): """Generate the filename""" if undefine: prefix = 'undef_' else: prefix = '' return os.path.join(out_dir, '{0}{1}.hpp'.format(prefix, name.lower()))
Generates the length limits def length_limits(max_length_limit, length_limit_step): """Generates the length limits""" string_len = len(str(max_length_limit)) return [ str(i).zfill(string_len) for i in xrange( length_limit_step, max_length_limit + length_limit_step - ...
Generate the take function def generate_take(out_f, steps, line_prefix): """Generate the take function""" out_f.write( '{0}constexpr inline int take(int n_)\n' '{0}{{\n' '{0} return {1} 0 {2};\n' '{0}}}\n' '\n'.format( line_prefix, ''.join('n_ >=...
Generate the make_string template def generate_make_string(out_f, max_step): """Generate the make_string template""" steps = [2 ** n for n in xrange(int(math.log(max_step, 2)), -1, -1)] with Namespace( out_f, ['boost', 'metaparse', 'v{0}'.format(VERSION), 'impl'] ) as nsp: gene...
Generate string.hpp def generate_string(out_dir, limits): """Generate string.hpp""" max_limit = max((int(v) for v in limits)) with open(filename(out_dir, 'string'), 'wb') as out_f: with IncludeGuard(out_f): out_f.write( '\n' '#include <boost/metaparse/v{...
Throws when the path does not exist def existing_path(value): """Throws when the path does not exist""" if os.path.exists(value): return value else: raise argparse.ArgumentTypeError("Path {0} not found".format(value))
The main function of the script def main(): """The main function of the script""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( '--boost_dir', required=False, type=existing_path, help='The path to the include/boost directory of Metaparse' ) ...
Generate the beginning part def begin(self): """Generate the beginning part""" self.out_f.write('\n') for depth, name in enumerate(self.names): self.out_f.write( '{0}namespace {1}\n{0}{{\n'.format(self.prefix(depth), name) )
Generate the closing part def end(self): """Generate the closing part""" for depth in xrange(len(self.names) - 1, -1, -1): self.out_f.write('{0}}}\n'.format(self.prefix(depth)))
Generate the beginning part def begin(self): """Generate the beginning part""" name = 'BOOST_METAPARSE_V1_CPP11_IMPL_STRING_HPP' self.out_f.write('#ifndef {0}\n#define {0}\n'.format(name)) write_autogen_info(self.out_f)
Calculates the deep features used by the Sound Classifier. Internally the Sound Classifier calculates deep features for both model creation and predictions. If the same data will be used multiple times, calculating the deep features just once will result in a significant speed up. Parameters -...
Creates a :class:`SoundClassifier` model. Parameters ---------- dataset : SFrame Input data. The column named by the 'feature' parameter will be extracted for modeling. target : string or int Name of the column containing the target variable. The values in this column m...
A function to load a previously saved SoundClassifier instance. def _load_version(cls, state, version): """ A function to load a previously saved SoundClassifier instance. """ from ._audio_feature_extractor import _get_feature_extractor from .._mxnet import _mxnet_utils ...
Return the classification for each examples in the ``dataset``. The output SFrame contains predicted class labels and its probability. Parameters ---------- dataset : SFrame | SArray | dict The audio data to be classified. If dataset is an SFrame, it must have a ...
Evaluate the model by making predictions of target values and comparing these to actual values. Parameters ---------- dataset : SFrame Dataset to use for evaluation, must include a column with the same name as the features used for model training. Additional colu...
Save the model in Core ML format. See Also -------- save Examples -------- >>> model.export_coreml('./myModel.mlmodel') def export_coreml(self, filename): """ Save the model in Core ML format. See Also -------- save Exa...
Return predictions for ``dataset``. Predictions can be generated as class labels or probabilities. Parameters ---------- dataset : SFrame | SArray | dict The audio data to be classified. If dataset is an SFrame, it must have a column with the same name as ...
Return top-k predictions for the ``dataset``. Predictions are returned as an SFrame with three columns: `id`, `class`, and `probability` or `rank` depending on the ``output_type`` parameter. Parameters ---------- dataset : SFrame | SArray | dict The audio dat...
Convert data into canonical form. def _init_data(data, allow_empty, default_name): """Convert data into canonical form.""" assert (data is not None) or allow_empty if data is None: data = [] if isinstance(data, (np.ndarray, NDArray)): data = [data] if isinstance(data, list): ...
The name and shape of data provided by this iterator def provide_data(self): """The name and shape of data provided by this iterator""" return [(k, tuple([self.batch_size] + list(v.shape[1:]))) for k, v in self.data]
The name and shape of label provided by this iterator def provide_label(self): """The name and shape of label provided by this iterator""" return [(k, tuple([self.batch_size] + list(v.shape[1:]))) for k, v in self.label]
Clear the module state. This is mainly for testing purposes. def reset (): """ Clear the module state. This is mainly for testing purposes. """ global __generators, __type_to_generators, __generators_for_toolset, __construct_stack global __overrides, __active_generators global __viable_generators_c...
Registers new generator instance 'g'. def register (g): """ Registers new generator instance 'g'. """ assert isinstance(g, Generator) id = g.id() __generators [id] = g # A generator can produce several targets of the # same type. We want unique occurence of that generator # in .genera...
Creates new instance of the 'generator' class and registers it. Returns the creates instance. Rationale: the instance is returned so that it's possible to first register a generator and then call 'run' method on that generator, bypassing all generator selection. def register_standard (i...
Make generator 'overrider-id' be preferred to 'overridee-id'. If, when searching for generators that could produce a target of certain type, both those generators are amoung viable generators, the overridden generator is immediately discarded. The overridden generators are discarded immediately ...
Returns a list of source type which can possibly be converted to 'target_type' by some chain of generator invocation. More formally, takes all generators for 'target_type' and returns union of source types for those generators and result of calling itself recusrively on source types. d...
Helper rule, caches the result of '__viable_source_types_real'. def viable_source_types (target_type): """ Helper rule, caches the result of '__viable_source_types_real'. """ assert isinstance(target_type, basestring) if target_type not in __viable_source_types_cache: __vst_cached_types.append(...
Returns the list of source types, which, when passed to 'run' method of 'generator', has some change of being eventually used (probably after conversion by other generators) def viable_source_types_for_generator_real (generator): """ Returns the list of source types, which, when passed to 'run' ...
Caches the result of 'viable_source_types_for_generator'. def viable_source_types_for_generator (generator): """ Caches the result of 'viable_source_types_for_generator'. """ assert isinstance(generator, Generator) if generator not in __viable_source_types_cache: __vstg_cached_generators.append...
Returns usage requirements + list of created targets. def try_one_generator_really (project, name, generator, target_type, properties, sources): """ Returns usage requirements + list of created targets. """ if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectT...
Checks if generator invocation can be pruned, because it's guaranteed to fail. If so, quickly returns empty list. Otherwise, calls try_one_generator_really. def try_one_generator (project, name, generator, target_type, properties, sources): """ Checks if generator invocation can be pruned, because ...
Ensures all 'targets' have types. If this is not so, exists with error. def __ensure_type (targets): """ Ensures all 'targets' have types. If this is not so, exists with error. """ assert is_iterable_typed(targets, virtual_target.VirtualTarget) for t in targets: if not t.type ()...
Returns generators which can be used to construct target of specified type with specified properties. Uses the following algorithm: - iterates over requested target_type and all it's bases (in the order returned bt type.all-bases. - for each type find all generators that generate that ...
Attempts to construct target by finding viable generators, running them and selecting the dependency graph. def __construct_really (project, name, target_type, prop_set, sources): """ Attempts to construct target by finding viable generators, running them and selecting the dependency graph. """...
Attempts to create target of 'target-type' with 'properties' from 'sources'. The 'sources' are treated as a collection of *possible* ingridients -- i.e. it is not required to consume them all. If 'multiple' is true, the rule is allowed to return several targets of 'target-type'. ...
Returns another generator which differers from $(self) in - id - value to <toolset> feature in properties def clone (self, new_id, new_toolset_properties): """ Returns another generator which differers from $(self) in - id - value to <toolset> feature in ...
Creates another generator that is the same as $(self), except that if 'base' is in target types of $(self), 'type' will in target types of the new generator. def clone_and_change_target_type(self, base, type): """Creates another generator that is the same as $(self), except that if 'bas...
Returns true if the generator can be run with the specified properties. def match_rank (self, ps): """ Returns true if the generator can be run with the specified properties. """ # See if generator's requirements are satisfied by # 'properties'. Treat a feature ...
Tries to invoke this generator on the given sources. Returns a list of generated targets (instances of 'virtual-target'). project: Project for which the targets are generated. name: Determines the name of 'name' attribute for all generat...
Constructs the dependency graph that will be returned by this generator. consumed: Already prepared list of consumable targets If generator requires several source files will contain exactly len $(self.source_types_) ta...
Determine the name of the produced target from the names of the sources. def determine_output_name(self, sources): """Determine the name of the produced target from the names of the sources.""" assert is_iterable_typed(sources, virtual_target.VirtualTarget) # The simple case if...
Constructs targets that are created after consuming 'sources'. The result will be the list of virtual-target, which the same length as 'target_types' attribute and with corresponding types. When 'name' is empty, all source targets must have the same value of the 'name' a...
Attempts to convert 'source' to the types that this generator can handle. The intention is to produce the set of targets can should be used when generator is run. only_one: convert 'source' to only one of source types if there's more that one possibility, re...
Converts several files to consumable types. def convert_multiple_sources_to_consumable_types (self, project, prop_set, sources): """ Converts several files to consumable types. """ if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget...
Returns the sketch summary for the given set of keys. This is only applicable for sketch summary created from SArray of sarray or dict type. For dict SArray, the keys are the keys in dict value. For array Sarray, the keys are indexes into the array value. The keys must be passed into or...
Convert a Nu-Support Vector Classification (NuSVC) model to the protobuf spec. Parameters ---------- model: NuSVC A trained NuSVC encoder model. feature_names: [str], optional (default=None) Name of the input columns. target: str, optional (default=None) Name of the output ...
Convert a linear regression model to the protobuf spec. Parameters ---------- model: LinearRegression A trained linear regression encoder model. feature_names: [str] Name of the input columns. target: str Name of the output column. Returns ------- model_spec: A...
Fetches all needed information from the top-level DBAPI module, guessing at the module if it wasn't passed as a parameter. Returns a dictionary of all the needed variables. This is put in one place to make sure the error message is clear if the module "guess" is wrong. def _get_global_dbapi_info(dbapi_modu...
Constructs an SFrame from a CSV file or a path to multiple CSVs, and returns a pair containing the SFrame and optionally (if store_errors=True) a dict of filenames to SArrays indicating for each file, what are the incorrectly parsed lines encountered. Parameters --------...
Constructs an SFrame from a CSV file or a path to multiple CSVs, and returns a pair containing the SFrame and a dict of filenames to SArrays indicating for each file, what are the incorrectly parsed lines encountered. Parameters ---------- url : string Locati...
Reads a JSON file representing a table into an SFrame. Parameters ---------- url : string Location of the CSV file or directory to load. If URL is a directory or a "glob" pattern, all matching files will be loaded. orient : string, optional. Either "records" or ...
Convert the result of a SQL database query to an SFrame. Parameters ---------- conn : dbapi2.Connection A DBAPI2 connection object. Any connection object originating from the 'connect' method of a DBAPI2-compliant package can be used. sql_statement : str T...
Convert an SFrame to a single table in a SQL database. This function does not attempt to create the table or check if a table named `table_name` exists in the database. It simply assumes that `table_name` exists in the database and appends to it. `to_sql` can be thought of as a conveni...
Print the first M rows and N columns of the SFrame in human readable format. Parameters ---------- num_rows : int, optional Number of rows to print. num_columns : int, optional Number of columns to print. max_column_width : int, optional ...
Where other is an SArray of identical length as the current Frame, this returns a selection of a subset of rows in the current SFrame where the corresponding row in the selector is non-zero. def _row_selector(self, other): """ Where other is an SArray of identical length as the current ...
Convert this SFrame to pandas.DataFrame. This operation will construct a pandas.DataFrame in memory. Care must be taken when size of the returned object is big. Returns ------- out : pandas.DataFrame The dataframe which contains all rows of SFrame def to_dataframe(...
Converts this SFrame to a numpy array This operation will construct a numpy array in memory. Care must be taken when size of the returned object is big. Returns ------- out : numpy.ndarray A Numpy Array containing all the values of the SFrame def to_numpy(self): ...
Transform each row to an :class:`~turicreate.SArray` according to a specified function. Returns a new SArray of ``dtype`` where each element in this SArray is transformed by `fn(x)` where `x` is a single row in the sframe represented as a dictionary. The ``fn`` should return exactly one...
Map each row of the SFrame to multiple rows in a new SFrame via a function. The output of `fn` must have type List[List[...]]. Each inner list will be a single row in the new output, and the collection of these rows within the outer list make up the data for the output SFrame. ...
Sample a fraction of the current SFrame's rows. Parameters ---------- fraction : float Fraction of the rows to fetch. Must be between 0 and 1. if exact is False (default), the number of rows returned is approximately the fraction times the number of rows. ...
Randomly split the rows of an SFrame into two SFrames. The first SFrame contains *M* rows, sampled uniformly (without replacement) from the original SFrame. *M* is approximately the fraction times the original number of rows. The second SFrame contains the remaining rows of the original ...
Get top k rows according to the given column. Result is according to and sorted by `column_name` in the given order (default is descending). When `k` is small, `topk` is more efficient than `sort`. Parameters ---------- column_name : string The column to sort on ...
Save the SFrame to a file system for later use. Parameters ---------- filename : string The location to save the SFrame. Either a local directory or a remote URL. If the format is 'binary', a directory will be created at the location which will contain the sf...
Writes an SFrame to a CSV file. Parameters ---------- filename : string The location to save the CSV. delimiter : string, optional This describes the delimiter used for writing csv files. line_terminator: string, optional The newline charact...
Writes an SFrame to a JSON file. Parameters ---------- filename : string The location to save the JSON file. orient : string, optional. Either "records" or "lines" If orient="records" the file is saved as a single JSON array. If orient="lines", the f...
Performs an incomplete save of an existing SFrame into a directory. This saved SFrame may reference SFrames in other locations in the same filesystem for certain resources. Parameters ---------- filename : string The location to save the SFrame. Either a local direct...
Get a reference to the :class:`~turicreate.SArray` that corresponds with the given column_name. Throws an exception if the column_name is something other than a string or if the column name is not found. Parameters ---------- column_name: str The column name. ...
Selects all columns where the name of the column or the type of column is included in the column_names. An exception is raised if duplicate columns are selected i.e. sf.select_columns(['a','a']), or non-existent columns are selected. Throws an exception for all other input types. ...
Returns an SFrame with a new column. The number of elements in the data given must match the length of every other column of the SFrame. If no name is given, a default name is chosen. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame...
Returns an SFrame with multiple columns added. The number of elements in all columns must match the length of every other column of the SFrame. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this oper...
Returns an SFrame with a column removed. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- column_name :...
Returns an SFrame with one or more columns removed. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- co...
Returns an SFrame with two column positions swapped. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- c...
Returns an SFrame with columns renamed. ``names`` is expected to be a dict specifying the old and new names. This changes the names of the columns given as the keys and replaces them with the names given as the values. If inplace == False (default) this operation does not modify the ...
Add the rows of an SFrame to the end of this SFrame. Both SFrames must have the same set of columns with the same column names and column types. Parameters ---------- other : SFrame Another SFrame whose rows are appended to the current SFrame. Returns ...
Perform a group on the key_column_names followed by aggregations on the columns listed in operations. The operations parameter is a dictionary that indicates which aggregation operators to use and which columns to use them on. The available operators are SUM, MAX, MIN, COUNT, AVG, VAR, ...
Merge two SFrames. Merges the current (left) SFrame with the given (right) SFrame using a SQL-style equi-join operation by columns. Parameters ---------- right : SFrame The SFrame to join. on : None | str | list | dict, optional The column name(s) repres...
Filter an SFrame by values inside an iterable object. Result is an SFrame that only includes (or excludes) the rows that have a column with the given ``column_name`` which holds one of the values in the given ``values`` :class:`~turicreate.SArray`. If ``values`` is not an SArray, we atte...
Explore the SFrame in an interactive GUI. Opens a new app window. Parameters ---------- title : str The plot title to show for the resulting visualization. Defaults to None. If the title is None, a default title will be provided. Returns ------- ...
Pack columns of the current SFrame into one single column. The result is a new SFrame with the unaffected columns from the original SFrame plus the newly created column. The list of columns that are packed is chosen through either the ``column_names`` or ``column_name_prefix`` parameter...
Splits a datetime column of SFrame to multiple columns, with each value in a separate column. Returns a new SFrame with the expanded column replaced with a list of new columns. The expanded column must be of datetime type. For more details regarding name generation and other, refer to :...
Expand one column of this SFrame to multiple columns with each value in a separate column. Returns a new SFrame with the unpacked column replaced with a list of new columns. The column must be of list/array/dict type. For more details regarding name generation, missing value handling a...
Convert a "wide" column of an SFrame to one or two "tall" columns by stacking all values. The stack works only for columns of dict, list, or array type. If the column is dict type, two new columns are created as a result of stacking: one column holds the key and another column holds th...
Concatenate values from one or two columns into one column, grouping by all other columns. The resulting column could be of type list, array or dictionary. If ``column_names`` is a numeric column, the result will be of array.array type. If ``column_names`` is a non-numeric column, the new colu...
Sort current SFrame by the given columns, using the given sort order. Only columns that are type of str, int and float can be sorted. Parameters ---------- key_column_names : str | list of str | list of (str, bool) pairs Names of columns to be sorted. The result will be sor...
Remove missing values from an SFrame. A missing value is either ``None`` or ``NaN``. If ``how`` is 'any', a row will be removed if any of the columns in the ``columns`` parameter contains at least one missing value. If ``how`` is 'all', a row will be removed if all of the columns in th...
Split rows with missing values from this SFrame. This function has the same functionality as :py:func:`~turicreate.SFrame.dropna`, but returns a tuple of two SFrames. The first item is the expected output from :py:func:`~turicreate.SFrame.dropna`, and the second item contains all the ro...
Fill all missing values with a given value in a given column. If the ``value`` is not the same type as the values in ``column_name``, this method attempts to convert the value to the original column's type. If this fails, an error is raised. Parameters ---------- column_...
Returns an SFrame with a new column that numbers each row sequentially. By default the count starts at 0, but this can be changed to a positive or negative number. The new column will be named with the given column name. An error will be raised if the given column name already exists i...
Adds the FileDescriptorProto and its types to this pool. Args: serialized_file_desc_proto: A bytes string, serialization of the FileDescriptorProto to add. def AddSerializedFile(self, serialized_file_desc_proto): """Adds the FileDescriptorProto and its types to this pool. Args: serial...
Adds a Descriptor to the pool, non-recursively. If the Descriptor contains nested messages or enums, the caller must explicitly register them. This method also registers the FileDescriptor associated with the message. Args: desc: A Descriptor. def AddDescriptor(self, desc): """Adds a Descri...
Adds a ServiceDescriptor to the pool. Args: service_desc: A ServiceDescriptor. def AddServiceDescriptor(self, service_desc): """Adds a ServiceDescriptor to the pool. Args: service_desc: A ServiceDescriptor. """ if not isinstance(service_desc, descriptor.ServiceDescriptor): rais...