INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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...
For each example in the dataset extract the leaf indices of each tree as features.
def extract_features(self, dataset, missing_value_action='auto'): """ For each example in the dataset, extract the leaf indices of each tree as features. For multiclass classification, each leaf index contains #num_class numbers. The returned feature vectors can be used...
Extract features along with all the missing features associated with a dataset.
def _extract_features_with_missing(self, dataset, tree_id = 0, missing_value_action = 'auto'): """ Extract features along with all the missing features associated with a dataset. Parameters ---------- dataset: bool Dataset on which to make predict...
Dump the models into a list of strings. Each string is a text representation of a tree.
def _dump_to_text(self, with_stats): """ Dump the models into a list of strings. Each string is a text representation of a tree. Parameters ---------- with_stats : bool If true, include node statistics in the output. Returns ------- o...
Dump the models into a list of strings. Each string is a text representation of a tree.
def _dump_to_json(self, with_stats): """ Dump the models into a list of strings. Each string is a text representation of a tree. Parameters ---------- with_stats : bool If true, include node statistics in the output. Returns ------- o...
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...
Convert a boosted tree model to protobuf format.
def convert(model, input_features, output_features): """Convert a boosted tree model to protobuf format. Parameters ---------- decision_tree : GradientBoostingRegressor A trained scikit-learn tree model. input_feature: [str] Name of the input columns. output_features: str ...
Sort a dictionary of classes and corresponding vote totals according to the votes then truncate to the highest k classes.
def _sort_topk_votes(x, k): """ Sort a dictionary of classes and corresponding vote totals according to the votes, then truncate to the highest 'k' classes. """ y = sorted(x.items(), key=lambda x: x[1], reverse=True)[:k] return [{'class': i[0], 'votes': i[1]} for i in y]
Construct a composite distance function for a set of features based on the types of those features.
def _construct_auto_distance(features, column_types): """ Construct a composite distance function for a set of features, based on the types of those features. NOTE: This function is very similar to `:func:_nearest_neighbors.choose_auto_distance`. The function is separate because the auto-distan...
Create a: class: ~turicreate. nearest_neighbor_classifier. NearestNeighborClassifier model. This model predicts the class of a query instance by finding the most common class among the query s nearest neighbors.
def create(dataset, target, features=None, distance=None, verbose=True): """ Create a :class:`~turicreate.nearest_neighbor_classifier.NearestNeighborClassifier` model. This model predicts the class of a query instance by finding the most common class among the query's nearest neighbors. .. warn...
A function to load a previously saved NearestNeighborClassifier model.
def _load_version(cls, state, version): """ A function to load a previously saved NearestNeighborClassifier model. Parameters ---------- unpickler : GLUnpickler A GLUnpickler file handler. version : int Version number maintained by the class writ...
Return the predicted class for each observation in * dataset *. This prediction is made based on the closest neighbors stored in the nearest neighbors classifier model.
def classify(self, dataset, max_neighbors=10, radius=None, verbose=True): """ Return the predicted class for each observation in *dataset*. This prediction is made based on the closest neighbors stored in the nearest neighbors classifier model. Parameters ---------- ...
Return predicted class labels for instances in * dataset *. This model makes predictions based on the closest neighbors stored in the nearest neighbors classifier model.
def predict(self, dataset, max_neighbors=10, radius=None, output_type='class', verbose=True): """ Return predicted class labels for instances in *dataset*. This model makes predictions based on the closest neighbors stored in the nearest neighbors classifier model. ...
Return top - k most likely predictions for each observation in dataset. Predictions are returned as an SFrame with three columns: row_id class and probability.
def predict_topk(self, dataset, max_neighbors=10, radius=None, k=3, verbose=False): """ Return top-k most likely predictions for each observation in ``dataset``. Predictions are returned as an SFrame with three columns: `row_id`, `class`, and `probability`. ...
Evaluate the model s predictive accuracy. This is done by predicting the target class for instances in a new dataset and comparing to known target values.
def evaluate(self, dataset, metric='auto', max_neighbors=10, radius=None): """ Evaluate the model's predictive accuracy. This is done by predicting the target class for instances in a new dataset and comparing to known target values. Parameters ---------- dataset...
A compact version of __repr__ for each of the steps.
def _compact_class_repr(obj): """ A compact version of __repr__ for each of the steps. """ dict_str_list = [] post_repr_string = "" # If features are present, then shorten it. init_func = obj.__init__ if _sys.version_info.major == 2: init_func = init_...
Internal function to perform fit_transform () on all but last step.
def _preprocess(self, data): """ Internal function to perform fit_transform() on all but last step. """ transformed_data = _copy(data) for name, step in self._transformers[:-1]: transformed_data = step.fit_transform(transformed_data) if type(transformed_da...
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...
First fit a transformer using the SFrame data and then return a transformed version of data.
def fit_transform(self, data): """ First fit a transformer using the SFrame `data` and then return a transformed version of `data`. Parameters ---------- data : SFrame The data used to fit the transformer. The same data is then also transformed. ...
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 ...
An function to load an object with a specific version of the class.
def _load_version(cls, unpickler, version): """ An function to load an object with a specific version of the class. Parameters ---------- pickler : file A GLUnpickler file handle. version : int A version number as maintained by the class writer. ...
Compute the PageRank for each vertex in the graph. Return a model object with total PageRank as well as the PageRank value for each vertex in the graph.
def create(graph, reset_probability=0.15, threshold=1e-2, max_iterations=20, _single_precision=False, _distributed='auto', verbose=True): """ Compute the PageRank for each vertex in the graph. Return a model object with total PageRank as well as the Pag...
Initializes the gcc toolset for the given version. If necessary command may be used to specify where the compiler is located. The parameter options is a space - delimited list of options each one specified as <option - name > option - value. Valid option names are: cxxflags linkflags and linker - type. Accepted linker ...
def init(version = None, command = None, options = None): """ Initializes the gcc toolset for the given version. If necessary, command may be used to specify where the compiler is located. The parameter 'options' is a space-delimited list of options, each one specified as <option-nam...
Now the vendor specific flags. The parameter linker can be either gnu darwin osf hpux or sun.
def init_link_flags(toolset, linker, condition): """ Now, the vendor specific flags. The parameter linker can be either gnu, darwin, osf, hpux or sun. """ toolset_link = toolset + '.link' if linker == 'gnu': # Strip the binary when no debugging is needed. We use --strip-all flag ...
Adds a dependency from targets to sources
def add_dependency (self, targets, sources): """Adds a dependency from 'targets' to 'sources' Both 'targets' and 'sources' can be either list of target names, or a single target name. """ if isinstance (targets, str): targets = [targets] if isinstance (source...
Gets the value of variable on set on the first target in targets.
def get_target_variable(self, targets, variable): """Gets the value of `variable` on set on the first target in `targets`. Args: targets (str or list): one or more targets to get the variable from. variable (str): the name of the variable Returns: the value...
Sets a target variable.
def set_target_variable (self, targets, variable, value, append=0): """ Sets a target variable. The 'variable' will be available to bjam when it decides where to generate targets, and will also be available to updating rule for that 'taret'. """ if isinstance (targets, s...
Binds a target to the corresponding update action. If target needs to be updated the action registered with action_name will be used. The action_name must be previously registered by either register_action or register_bjam_action method.
def set_update_action (self, action_name, targets, sources, properties=None): """ Binds a target to the corresponding update action. If target needs to be updated, the action registered with action_name will be used. The 'action_name' must be previously registered by ...
Creates a new build engine action.
def register_action (self, action_name, command='', bound_list = [], flags = [], function = None): """Creates a new build engine action. Creates on bjam side an action named 'action_name', with 'command' as the command to be executed, 'bound_variables' naming th...
Informs self that action_name is declared in bjam.
def register_bjam_action (self, action_name, function=None): """Informs self that 'action_name' is declared in bjam. From this point, 'action_name' is a valid argument to the set_update_action method. The action_name should be callable in the global module of bjam. """ ...
Returns the pixel data stored in the Image object.
def pixel_data(self): """ Returns the pixel data stored in the Image object. Returns ------- out : numpy.array The pixel data of the Image object. It returns a multi-dimensional numpy array, where the shape of the array represents the shape of ...
Displays the image. Requires PIL/ Pillow.
def show(self): """ Displays the image. Requires PIL/Pillow. Alternatively, you can create an :class:`turicreate.SArray` of this image and use py:func:`turicreate.SArray.show()` See Also -------- turicreate.image_analysis.resize Examples -------...
Return predictions for the model. The kwargs gets passed into the model as a dictionary.
def predict(self, data, useCPUOnly=False, **kwargs): """ Return predictions for the model. The kwargs gets passed into the model as a dictionary. Parameters ---------- data : dict[str, value] Dictionary of data to make predictions from where the keys are ...
Visualize the model.
def visualize_spec(self, port=None, input_shape_dict=None): """ Visualize the model. Parameters ---------- port : int if server is to be hosted on specific localhost port input_shape_dict : dict The shapes are calculat...
Construct composite distance parameters based on selected features and their types.
def _construct_auto_distance(feature_names, column_names, column_types, sample): """ Construct composite distance parameters based on selected features and their types. """ ## Make a dictionary from the column_names and column_types col_type_dict = {k: v for k, v in zip(column_names, column_typ...
Create a nearest neighbor model which can be searched efficiently and quickly for the nearest neighbors of a query observation. If the method argument is specified as auto the type of model is chosen automatically based on the type of data in dataset.
def create(dataset, label=None, features=None, distance=None, method='auto', verbose=True, **kwargs): """ Create a nearest neighbor model, which can be searched efficiently and quickly for the nearest neighbors of a query observation. If the `method` argument is specified as `auto`, the type ...
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...
List the fields stored in the model including data model and training options. Each field can be queried with the get method.
def _list_fields(self): """ List the fields stored in the model, including data, model, and training options. Each field can be queried with the ``get`` method. Returns ------- out : list List of fields queryable with the ``get`` method. """ o...
Return the value of a given field. The list of all queryable fields is detailed below and can be obtained with the: func: ~turicreate. nearest_neighbors. NearestNeighborsModel. _list_fields method.
def _get(self, field): """ Return the value of a given field. The list of all queryable fields is detailed below, and can be obtained with the :func:`~turicreate.nearest_neighbors.NearestNeighborsModel._list_fields` method. +-----------------------+----------------------...
Return a dictionary of statistics collected during creation of the model. These statistics are also available with the get method and are described in more detail in that method s documentation.
def _training_stats(self): """ Return a dictionary of statistics collected during creation of the model. These statistics are also available with the ``get`` method and are described in more detail in that method's documentation. Returns ------- out : dict ...
For each row of the input dataset retrieve the nearest neighbors from the model s stored data. In general the query dataset does not need to be the same as the reference data stored in the model but if it is the include_self_edges parameter can be set to False to exclude results that match query points to themselves.
def query(self, dataset, label=None, k=5, radius=None, verbose=True): """ For each row of the input 'dataset', retrieve the nearest neighbors from the model's stored data. In general, the query dataset does not need to be the same as the reference data stored in the model, but if ...
Construct the similarity graph on the reference dataset which is already stored in the model. This is conceptually very similar to running query with the reference set but this method is optimized for the purpose syntactically simpler and automatically removes self - edges.
def similarity_graph(self, k=5, radius=None, include_self_edges=False, output_type='SGraph', verbose=True): """ Construct the similarity graph on the reference dataset, which is already stored in the model. This is conceptually very similar to running `query` wit...
Randomly split an SFrame into two SFrames based on the session_id such that one split contains data for a fraction of the sessions while the second split contains all data for the rest of the sessions.
def random_split_by_session(dataset, session_id, fraction=0.9, seed=None): """ Randomly split an SFrame into two SFrames based on the `session_id` such that one split contains data for a `fraction` of the sessions while the second split contains all data for the rest of the sessions. Parameters ...
Reads the MS Build XML file at the path and returns its contents.
def read_msbuild_xml(path, values={}): """Reads the MS Build XML file at the path and returns its contents. Keyword arguments: values -- The map to append the contents to (default {}) """ # Attempt to read the file contents try: document = parse(path) except Exception as e: ...
Reads the MS Build JSON file at the path and returns its contents.
def read_msbuild_json(path, values=[]): """Reads the MS Build JSON file at the path and returns its contents. Keyword arguments: values -- The list to append the contents to (default []) """ if not os.path.exists(path): logging.info('Could not find MS Build JSON file at %s', path) r...
Script entrypoint.
def main(): """Script entrypoint.""" # Parse the arguments parser = argparse.ArgumentParser( description='Convert MSBuild XML to JSON format') parser.add_argument( '-t', '--toolchain', help='The name of the toolchain', required=True) parser.add_argument( '-o', '--output', he...
Merges the values between the current and previous run of the script.
def __merge_json_values(current, previous): """Merges the values between the current and previous run of the script.""" for value in current: name = value['name'] # Find the previous value previous_value = __find_and_remove_value(previous, value) if previous_value is not None: ...
Finds the value in the list that corresponds with the value of compare.
def __find_and_remove_value(list, compare): """Finds the value in the list that corresponds with the value of compare.""" # next throws if there are no matches try: found = next(value for value in list if value['name'] == compare['name'] and value['switch'] == ...
Converts the tag type found in the root and converts them using the func and appends them to the values.
def __convert(root, tag, values, func): """Converts the tag type found in the root and converts them using the func and appends them to the values. """ elements = root.getElementsByTagName(tag) for element in elements: converted = func(element) # Append to the list __append...
Converts an EnumProperty node to JSON format.
def __convert_enum(node): """Converts an EnumProperty node to JSON format.""" name = __get_attribute(node, 'Name') logging.debug('Found EnumProperty named %s', name) converted_values = [] for value in node.getElementsByTagName('EnumValue'): converted = __convert_node(value) conver...
Converts an BoolProperty node to JSON format.
def __convert_bool(node): """Converts an BoolProperty node to JSON format.""" converted = __convert_node(node, default_value='true') # Check for a switch for reversing the value reverse_switch = __get_attribute(node, 'ReverseSwitch') if reverse_switch: converted_reverse = copy.deepcopy(con...
Converts a StringListProperty node to JSON format.
def __convert_string_list(node): """Converts a StringListProperty node to JSON format.""" converted = __convert_node(node) # Determine flags for the string list flags = vsflags(VSFlags.UserValue) # Check for a separator to determine if it is semicolon appendable # If not present assume the val...
Converts a StringProperty node to JSON format.
def __convert_string(node): """Converts a StringProperty node to JSON format.""" converted = __convert_node(node, default_flags=vsflags(VSFlags.UserValue)) return __check_for_flag(converted)
Converts a XML node to a JSON equivalent.
def __convert_node(node, default_value='', default_flags=vsflags()): """Converts a XML node to a JSON equivalent.""" name = __get_attribute(node, 'Name') logging.debug('Found %s named %s', node.tagName, name) converted = {} converted['name'] = name converted['switch'] = __get_attribute(node, 'S...
Modifies the flags in value if the node contains an Argument.
def __with_argument(node, value): """Modifies the flags in value if the node contains an Argument.""" arguments = node.getElementsByTagName('Argument') if arguments: logging.debug('Found argument within %s', value['name']) value['flags'] = vsflags(VSFlags.UserValueIgnored, VSFlags.Continue)
Preprocesses occurrences of Argument within the root.
def __preprocess_arguments(root): """Preprocesses occurrences of Argument within the root. Argument XML values reference other values within the document by name. The referenced value does not contain a switch. This function will add the switch associated with the argument. """ # Set the flags ...
Retrieves the attribute of the given name from the node.
def __get_attribute(node, name, default_value=''): """Retrieves the attribute of the given name from the node. If not present then the default_value is used. """ if node.hasAttribute(name): return node.attributes[name].value.strip() else: return default_value
Gets the path to the file.
def __get_path(path): """Gets the path to the file.""" if not os.path.isabs(path): path = os.path.join(os.getcwd(), path) return os.path.normpath(path)
Gets the output path for a file given the toolchain rule and output_dir
def __output_path(toolchain, rule, output_dir): """Gets the output path for a file given the toolchain, rule and output_dir""" filename = '%s_%s.json' % (toolchain, rule) return os.path.join(output_dir, filename)
Writes a JSON file at the path with the values provided.
def __write_json_file(path, values): """Writes a JSON file at the path with the values provided.""" # Sort the keys to ensure ordering sort_order = ['name', 'switch', 'comment', 'value', 'flags'] sorted_values = [ OrderedDict( sorted( value.items(), key=lambda value: ...
Appends the value to the list.
def __append_list(append_to, value): """Appends the value to the list.""" if value is not None: if isinstance(value, list): append_to.extend(value) else: append_to.append(value)
Decompile a function into ast. FunctionDef node.: param func: python function ( can not be a built - in ): return: ast. FunctionDef instance.
def decompile_func(func): ''' Decompile a function into ast.FunctionDef node. :param func: python function (can not be a built-in) :return: ast.FunctionDef instance. ''' code = func.__code__ # For python 3 # defaults = func.func_defaults if sys.version_info.major < 3 else func....
Compile a function from an ast. FunctionDef instance.: param ast_node: ast. FunctionDef instance: param filename: path where function source can be found.: param globals: will be used as func_globals: return: A python function object
def compile_func(ast_node, filename, globals, **defaults): ''' Compile a function from an ast.FunctionDef instance. :param ast_node: ast.FunctionDef instance :param filename: path where function source can be found. :param globals: will be used as func_globals :return: A python functi...
decompile apython pyc or pyo binary file.: param bin_pyc: input file objects: param output: output file objects
def decompile_pyc(bin_pyc, output=sys.stdout): ''' decompile apython pyc or pyo binary file. :param bin_pyc: input file objects :param output: output file objects ''' from turicreate.meta.asttools import python_source bin = bin_pyc.read() code = marshal.loads(bin[8:])...
Consumes input extracting definitions.
def ParseInput(self, a_file): """Consumes input extracting definitions. Args: a_file: The file like stream to parse. Raises: PDDMError if there are any issues. """ input_lines = a_file.read().splitlines() self.ParseLines(input_lines)
Parses list of lines.
def ParseLines(self, input_lines): """Parses list of lines. Args: input_lines: A list of strings of input to parse (no newlines on the strings). Raises: PDDMError if there are any issues. """ current_macro = None for line in input_lines: if line.startswith(...
Expands the macro reference.
def Expand(self, macro_ref_str): """Expands the macro reference. Args: macro_ref_str: String of a macro reference (i.e. foo(a, b)). Returns: The text from the expansion. Raises: PDDMError if there are any issues. """ match = _MACRO_RE.match(macro_ref_str) if match is Non...
Processes the file contents.
def ProcessContent(self, strip_expansion=False): """Processes the file contents.""" self._ParseFile() if strip_expansion: # Without a collection the expansions become blank, removing them. collection = None else: collection = MacroCollection() for section in self._sections: s...
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...
Clear the module state. This is mainly for testing purposes.
def reset (): """ Clear the module state. This is mainly for testing purposes. """ global __all_attributes, __all_features, __implicit_features, __composite_properties global __subfeature_from_value, __all_top_features, __free_features global __all_subfeatures # sets the default value of False ...
Declares a new feature with the given name values and attributes. name: the feature name values: a sequence of the allowable values - may be extended later with feature. extend attributes: a sequence of the feature s attributes ( e. g. implicit free propagated... )
def feature (name, values, attributes = []): """ Declares a new feature with the given name, values, and attributes. name: the feature name values: a sequence of the allowable values - may be extended later with feature.extend attributes: a sequence of the feature's attributes (e.g. implicit...
Sets the default value of the given feature overriding any previous default. feature: the name of the feature value: the default value to assign
def set_default (feature, value): """ Sets the default value of the given feature, overriding any previous default. feature: the name of the feature value: the default value to assign """ f = __all_features[feature] bad_attribute = None if f.free: bad_attribute = "free" ...
Returns the default property values for the given features.
def defaults(features): """ Returns the default property values for the given features. """ assert is_iterable_typed(features, Feature) # FIXME: should merge feature and property modules. from . import property result = [] for f in features: if not f.free and not f.optional and f.de...
Returns true iff all elements of names are valid features.
def valid (names): """ Returns true iff all elements of names are valid features. """ if isinstance(names, str): names = [names] assert is_iterable_typed(names, basestring) return all(name in __all_features for name in names)
Return the values of the given feature.
def values (feature): """ Return the values of the given feature. """ assert isinstance(feature, basestring) validate_feature (feature) return __all_features[feature].values
Returns true iff value_string is a value_string of an implicit feature.
def is_implicit_value (value_string): """ Returns true iff 'value_string' is a value_string of an implicit feature. """ assert isinstance(value_string, basestring) if value_string in __implicit_features: return __implicit_features[value_string] v = value_string.split('-') if v[0] n...
Returns the implicit feature associated with the given implicit value.
def implied_feature (implicit_value): """ Returns the implicit feature associated with the given implicit value. """ assert isinstance(implicit_value, basestring) components = implicit_value.split('-') if components[0] not in __implicit_features: raise InvalidValue ("'%s' is not a value of ...
Checks if all name is a valid feature. Otherwise raises an exception.
def validate_feature (name): """ Checks if all name is a valid feature. Otherwise, raises an exception. """ assert isinstance(name, basestring) if name not in __all_features: raise InvalidFeature ("'%s' is not a valid feature name" % name) else: return __all_features[name]
Helper for expand_subfeatures. Given a feature and value or just a value corresponding to an implicit feature returns a property set consisting of all component subfeatures and their values. For example:
def __expand_subfeatures_aux (property_, dont_validate = False): """ Helper for expand_subfeatures. Given a feature and value, or just a value corresponding to an implicit feature, returns a property set consisting of all component subfeatures and their values. For example: expand...
Make all elements of properties corresponding to implicit features explicit and express all subfeature values as separate properties in their own right. For example the property
def expand_subfeatures(properties, dont_validate = False): """ Make all elements of properties corresponding to implicit features explicit, and express all subfeature values as separate properties in their own right. For example, the property gcc-2.95.2-linux-x86 might expand to <too...
Adds the given values to the given feature.
def extend (name, values): """ Adds the given values to the given feature. """ assert isinstance(name, basestring) assert is_iterable_typed(values, basestring) name = add_grist (name) __validate_feature (name) feature = __all_features [name] if feature.implicit: for v in values:...
Checks that value - string is a valid value - string for the given feature.
def validate_value_string (f, value_string): """ Checks that value-string is a valid value-string for the given feature. """ assert isinstance(f, Feature) assert isinstance(value_string, basestring) if f.free or value_string in f.values: return values = [value_string] if f.subfeatu...
Declares a subfeature. feature_name: Root feature that is not a subfeature. value_string: An optional value - string specifying which feature or subfeature values this subfeature is specific to if any. subfeature: The name of the subfeature being declared. subvalues: The allowed values of this subfeature. attributes: T...
def subfeature (feature_name, value_string, subfeature, subvalues, attributes = []): """ Declares a subfeature. feature_name: Root feature that is not a subfeature. value_string: An optional value-string specifying which feature or subfeature values this subfeature is spe...
Sets the components of the given composite property.
def compose (composite_property_s, component_properties_s): """ Sets the components of the given composite property. All parameters are <feature>value strings """ from . import property component_properties_s = to_seq (component_properties_s) composite_property = property.create_from_string(co...
Returns all values of the given feature specified by the given property set.
def get_values (feature, properties): """ Returns all values of the given feature specified by the given property set. """ if feature[0] != '<': feature = '<' + feature + '>' result = [] for p in properties: if get_grist (p) == feature: result.append (replace_grist (p, '')) ...
Expand all composite properties in the set so that all components are explicitly expressed.
def expand_composites (properties): """ Expand all composite properties in the set so that all components are explicitly expressed. """ if __debug__: from .property import Property assert is_iterable_typed(properties, Property) explicit_features = set(p.feature for p in propertie...
Return true iff f is an ordinary subfeature of the parent_property s feature or if f is a subfeature of the parent_property s feature specific to the parent_property s value.
def is_subfeature_of (parent_property, f): """ Return true iff f is an ordinary subfeature of the parent_property's feature, or if f is a subfeature of the parent_property's feature specific to the parent_property's value. """ if __debug__: from .property import Property asse...
As is_subfeature_of for subproperties.
def __is_subproperty_of (parent_property, p): """ As is_subfeature_of, for subproperties. """ if __debug__: from .property import Property assert isinstance(parent_property, Property) assert isinstance(p, Property) return is_subfeature_of (parent_property, p.feature)
Given a property set which may consist of composite and implicit properties and combined subfeature values returns an expanded normalized property set with all implicit features expressed explicitly all subfeature values individually expressed and all components of composite properties expanded. Non - free features dir...
def expand (properties): """ Given a property set which may consist of composite and implicit properties and combined subfeature values, returns an expanded, normalized property set with all implicit features expressed explicitly, all subfeature values individually expressed, and all ...
Given a set of properties add default values for features not represented in the set. Note: if there s there s ordinary feature F1 and composite feature F2 which includes some value for F1 and both feature have default values then the default value of F1 will be added not the value in F2. This might not be right idea: ...
def add_defaults (properties): """ Given a set of properties, add default values for features not represented in the set. Note: if there's there's ordinary feature F1 and composite feature F2, which includes some value for F1, and both feature have default values, then the default va...
Given an expanded property set eliminate all redundancy: properties which are elements of other ( composite ) properties in the set will be eliminated. Non - symmetric properties equal to default values will be eliminated unless the override a value from some composite property. Implicit properties will be expressed wi...
def minimize (properties): """ Given an expanded property set, eliminate all redundancy: properties which are elements of other (composite) properties in the set will be eliminated. Non-symmetric properties equal to default values will be eliminated, unless the override a value from some com...
Given a property - set of the form v1/ v2/... vN - 1/ <fN > vN/ <fN + 1 > vN + 1/... <fM > vM
def split (properties): """ Given a property-set of the form v1/v2/...vN-1/<fN>vN/<fN+1>vN+1/...<fM>vM Returns v1 v2 ... vN-1 <fN>vN <fN+1>vN+1 ... <fM>vM Note that vN...vM may contain slashes. This is resilient to the substitution of backslashes for slashes, since Jam, unbidden, s...
Combine all subproperties into their parent properties
def compress_subproperties (properties): """ Combine all subproperties into their parent properties Requires: for every subproperty, there is a parent property. All features are explicitly expressed. This rule probably shouldn't be needed, but build-request.expand-no-defaults is b...
Given a property return the subset of features consisting of all ordinary subfeatures of the property s feature and all specific subfeatures of the property s feature which are conditional on the property s value.
def __select_subfeatures (parent_property, features): """ Given a property, return the subset of features consisting of all ordinary subfeatures of the property's feature, and all specific subfeatures of the property's feature which are conditional on the property's value. """ if __d...
Retrieves the interpretation function used.
def _get_interpretation_function(interpretation, dtype): """ Retrieves the interpretation function used. """ type_string = dtype.__name__ name = "%s__%s" % (interpretation, type_string) global _interpretations if not hasattr(_interpretations, name): raise ValueError("No transform ...
Returns the description and output type for a given interpretation.
def _get_interpretation_description_and_output_type(interpretation, dtype): """ Returns the description and output type for a given interpretation. """ type_string = dtype.__name__ name = "%s__%s" % (interpretation, type_string) if not hasattr(_interpretations_class, name): raise Value...
Returns a list of the available interpretations and what they do.
def _get_embeddable_interpretation_doc(indent = 0): """ Returns a list of the available interpretations and what they do. If indent is specified, then the entire doc string is indented by that amount. """ output_rows = [] # Pull out the doc string and put it in a table. for name in sorted...
A function to load a previously saved SentenceSplitter instance.
def _load_version(cls, unpickler, version): """ A function to load a previously saved SentenceSplitter instance. Parameters ---------- unpickler : GLUnpickler A GLUnpickler file handler. version : int Version number maintained by the class writer...
Fits the transformer using the given data.
def fit(self, data): """ Fits the transformer using the given data. """ _raise_error_if_not_sframe(data, "data") fitted_state = {} feature_columns = _internal_utils.get_column_names(data, self._exclude, self._features) if not feature_columns: raise ...
Transforms the data.
def transform(self, data): """ Transforms the data. """ if not self._get("fitted"): raise RuntimeError("`transform` called before `fit` or `fit_transform`.") data = data.copy() output_column_prefix = self._get("output_column_prefix") if output_colum...