text
stringlengths
81
112k
Returns the properties which specify implicit include paths to generated headers. This traverses all targets in this subvariant, and subvariants referred by <implcit-dependecy>properties. For all targets which are of type 'target-type' (or for all targets, if 'target_type...
Compare if two nodes are equal. def cmp_ast(node1, node2): ''' Compare if two nodes are equal. ''' if type(node1) != type(node2): return False if isinstance(node1, (list, tuple)): if len(node1) != len(node2): return False for left, right in zip(node1, node2): ...
Creates additional files for the individual MPL-containers. def create_more_container_files(sourceDir, suffix, maxElements, containers, containers2): """Creates additional files for the individual MPL-containers.""" # Create files for each MPL-container with 20 to 'maxElements' elements # which will be us...
Creates additional source- and header-files for the numbered sequence MPL-containers. def create_input_for_numbered_sequences(headerDir, sourceDir, containers, maxElements): """Creates additional source- and header-files for the numbered sequence MPL-containers.""" # Create additional container-list without "m...
Adjusts the limits of variadic sequence MPL-containers. def adjust_container_limits_for_variadic_sequences(headerDir, containers, maxElements): """Adjusts the limits of variadic sequence MPL-containers.""" for container in containers: headerFile = os.path.join( headerDir, "limits", container + ".hpp" )...
Returns the (relative) path to the Boost source-directory this file is located in (if any). def current_boost_dir(): """Returns the (relative) path to the Boost source-directory this file is located in (if any).""" # Path to directory containing this script. path = os.path.dirname( os.path.realpath(__file_...
Converts a string into its encoded positive integer (greater zero) or throws an exception. def to_positive_multiple_of_10(string): """Converts a string into its encoded positive integer (greater zero) or throws an exception.""" try: value = int(string) except ValueError: msg = '"%r" is not ...
The main function. def main(): """The main function.""" # Find the current Boost source-directory in which this script is located. sourceDir = current_boost_dir() if sourceDir == None: sourceDir = "" # Prepare and run cmdline-parser. cmdlineParser = argparse.ArgumentParser(des...
Add an inner product layer to the model. Parameters ---------- name: str The name of this layer W: numpy.array or bytes() Weight matrix of shape (output_channels, input_channels) If W is of type bytes(), i.e. quantized, other quantization related argu...
Add a convolution layer to the network. Please see the ConvolutionLayerParams in Core ML neural network protobuf message for more information about input and output blob dimensions. Parameters ---------- name: str The name of this layer. kernel_channels: int...
Add resize bilinear layer to the model. A layer that resizes the input to a given spatial size using bilinear interpolation. Parameters ---------- name: str The name of this layer. input_name: str The input blob name of this layer. output_name: str ...
Add crop resize layer to the model. A layer that extracts cropped spatial patches or RoIs (regions of interest) from the input and resizes them to a pre-specified size using bilinear interpolation. Note that RoI Align layer can be implemented with this layer followed by a pooling layer. Kindly r...
Serialize model summary into a dict with ordered lists of sections and section titles Parameters ---------- model : Model object sections : Ordered list of lists (sections) of tuples (field,value) [ [(field1, value1), (field2, value2)], [(field3, value3), (field4, value4)], ...
Format a doc-string on the fly. @arg format_dict: A dictionary to format the doc-strings Example: @add_docstring({'context': __doc_string_context}) def predict(x): ''' {context} >> model.predict(data) ''' return x def _add_docstring(f...
Finds the only column in `SFrame` with a type specified by `target_type`. If there are zero or more than one such columns, an exception will be raised. The name and type of the target column should be provided as strings for the purpose of error feedback. def _find_only_column_of_type(sframe, target_type, ...
Finds the only column in `sframe` with a type of turicreate.Image. If there are zero or more than one image columns, an exception will be raised. def _find_only_image_column(sframe): """ Finds the only column in `sframe` with a type of turicreate.Image. If there are zero or more than one image c...
Finds the only column that can be interpreted as a drawing feature column. A drawing column can be a stroke-based drawing column (with dtype list) or a bitmap-based drawing column (with dtype turicreate.Image) If there are zero or more than one drawing columns, an exception will be raised. def _fi...
Convert the Json Tree to SGraph def _SGraphFromJsonTree(json_str): """ Convert the Json Tree to SGraph """ g = json.loads(json_str) vertices = [_Vertex(x['id'], dict([(str(k), v) for k, v in _six.iteritems(x) if k != 'id'])) for ...
Return a tuple of sections and section titles. Sections are pretty print of model coefficients Parameters ---------- top_coefs : SFrame of top k coefficients bottom_coefs : SFrame of bottom k coefficients Returns ------- (sections, section_titles) : tuple sections : list ...
Returns a tuple of the top k values from the positive and negative values in a SArray Parameters ---------- values : SFrame of model coefficients k: Maximum number of largest positive and k lowest negative numbers to return Returns ------- (topk_positive, bottomk_positive) : tuple ...
Extract a model summary field value def __extract_model_summary_value(model, value): """ Extract a model summary field value """ field_value = None if isinstance(value, _precomputed_field): field_value = value.field else: field_value = model._get(value) if isinstance(field_v...
Serializes an SFrame to a list of strings, that, when printed, creates a well-formatted table. def _make_repr_table_from_sframe(X): """ Serializes an SFrame to a list of strings, that, when printed, creates a well-formatted table. """ assert isinstance(X, _SFrame) column_names = X.column_names() ...
Display a toolkit repr according to some simple rules. Parameters ---------- model : Turi Create model fields: List of lists of tuples Each tuple should be (display_name, field_name), where field_name can be a string or a _precomputed_field object. section_titles: List of section...
Map returning value, if it is unity SFrame, SArray, map it def _map_unity_proxy_to_object(value): """ Map returning value, if it is unity SFrame, SArray, map it """ vtype = type(value) if vtype in _proxy_map: return _proxy_map[vtype](value) elif vtype == list: return [_map_unity...
Same as select columns but redirect runtime error to ToolkitError. def _toolkits_select_columns(dataset, columns): """ Same as select columns but redirect runtime error to ToolkitError. """ try: return dataset.select_columns(columns) except RuntimeError: missing_features = list(set(...
Check if a column exists in an SFrame with error message. def _raise_error_if_column_exists(dataset, column_name = 'dataset', dataset_variable_name = 'dataset', column_name_error_message_name = 'column_name'): """ Check if a column exists in an SFrame wit...
Check whether or not the requested option is one of the allowed values. def _check_categorical_option_type(option_name, option_value, possible_values): """ Check whether or not the requested option is one of the allowed values. """ err_msg = '{0} is not a valid option for {1}. '.format(option_value, op...
Check if the input is an SArray. Provide a proper error message otherwise. def _raise_error_if_not_sarray(dataset, variable_name="SArray"): """ Check if the input is an SArray. Provide a proper error message otherwise. """ err_msg = "Input %s is not an SArray." if not isinstance(dataset, _S...
Check if the input is an SFrame. Provide a proper error message otherwise. def _raise_error_if_not_sframe(dataset, variable_name="SFrame"): """ Check if the input is an SFrame. Provide a proper error message otherwise. """ err_msg = "Input %s is not an SFrame. If it is a Pandas DataFrame," ...
Check if the input is empty. def _raise_error_if_sframe_empty(dataset, variable_name="SFrame"): """ Check if the input is empty. """ err_msg = "Input %s either has no rows or no columns. A non-empty SFrame " err_msg += "is required." if dataset.num_rows() == 0 or dataset.num_columns() == 0: ...
Check if the input is an SFrame. Provide a proper error message otherwise. def _raise_error_evaluation_metric_is_valid(metric, allowed_metrics): """ Check if the input is an SFrame. Provide a proper error message otherwise. """ err_msg = "Evaluation metric '%s' not recognized. The supported ev...
Checks if numeric parameter is within given range def _numeric_param_check_range(variable_name, variable_value, range_bottom, range_top): """ Checks if numeric parameter is within given range """ err_msg = "%s must be between %i and %i" if variable_value < range_bottom or variable_value > range_to...
Validate and canonicalize training and validation data. Parameters ---------- dataset : SFrame Dataset for training the model. target : string Name of the column containing the target variable. features : list[string], optional List of feature names used. validation_s...
Validate a row label column. If the row label is not specified, a column is created with row numbers, named with the string in the `default_label` parameter. Parameters ---------- dataset : SFrame Input dataset. label : str, optional Name of the column containing row labels. ...
Returns Mac version as a tuple of integers, making it easy to do proper version comparisons. On non-Macs, it returns an empty tuple. def _mac_ver(): """ Returns Mac version as a tuple of integers, making it easy to do proper version comparisons. On non-Macs, it returns an empty tuple. """ impor...
Print a message making it clear to the user what compute resource is used in neural network training. def _print_neural_compute_device(cuda_gpus, use_mps, cuda_mem_req=None, has_mps_impl=True): """ Print a message making it clear to the user what compute resource is used in neural network training. ...
Get a proto class from the MessageFactory by name. Args: factory: a MessageFactory instance. full_name: str, the fully qualified name of the proto type. Returns: A class, for the type identified by full_name. Raises: KeyError, if the proto is not found in the factory's descriptor pool. def _GetM...
Create a Protobuf class whose fields are basic types. Note: this doesn't validate field names! Args: fields: dict of {name: field_type} mappings for each field in the proto. If this is an OrderedDict the order will be maintained, otherwise the fields will be sorted by name. full_name: opti...
Populate FileDescriptorProto for MessageFactory's DescriptorPool. def _MakeFileDescriptorProto(proto_file_name, full_name, field_items): """Populate FileDescriptorProto for MessageFactory's DescriptorPool.""" package, name = full_name.rsplit('.', 1) file_proto = descriptor_pb2.FileDescriptorProto() file_proto....
Convert a decision tree model to protobuf format. Parameters ---------- decision_tree : DecisionTreeClassifier A trained scikit-learn tree model. input_name: str Name of the input columns. output_name: str Name of the output columns. Returns ------- model_spec...
Returns user-defined metadata, making sure information all models should have is also available, as a dictionary def _get_model_metadata(model_class, metadata, version=None): """ Returns user-defined metadata, making sure information all models should have is also available, as a dictionary """ ...
Sets user-defined metadata, making sure information all models should have is also available def _set_model_metadata(mlmodel, model_class, metadata, version=None): """ Sets user-defined metadata, making sure information all models should have is also available """ info = _get_model_metadata(mod...
Converts name to camel-case and returns it. def _ToCamelCase(name): """Converts name to camel-case and returns it.""" capitalize_next = False result = [] for c in name: if c == '_': if result: capitalize_next = True elif capitalize_next: result.append(c.upper()) capitalize_ne...
Converts name to Json name and returns it. def _ToJsonName(name): """Converts name to Json name and returns it.""" capitalize_next = False result = [] for c in name: if c == '_': capitalize_next = True elif capitalize_next: result.append(c.upper()) capitalize_next = False else: ...
Sets the descriptor's options This function is used in generated proto2 files to update descriptor options. It must not be used outside proto2. def _SetOptions(self, options, options_class_name): """Sets the descriptor's options This function is used in generated proto2 files to update descriptor ...
Retrieves descriptor options. This method returns the options set or creates the default options for the descriptor. def GetOptions(self): """Retrieves descriptor options. This method returns the options set or creates the default options for the descriptor. """ if self._options: re...
Copies this to the matching proto in descriptor_pb2. Args: proto: An empty proto instance from descriptor_pb2. Raises: Error: If self couldnt be serialized, due to to few constructor arguments. def CopyToProto(self, proto): """Copies this to the matching proto in descriptor_pb2. Args: ...
Returns the string name of an enum value. This is just a small helper method to simplify a common operation. Args: enum: string name of the Enum. value: int, value of the enum. Returns: string name of the enum value. Raises: KeyError if either the Enum doesn't exist or the va...
Given a target_reference, made in context of 'project', returns the AbstractTarget instance that is referred to, as well as properties explicitly specified for this reference. def resolve_reference(target_reference, project): """ Given a target_reference, made in context of 'project', returns the Abstr...
Attempts to generate the target given by target reference, which can refer both to a main target or to a file. Returns a list consisting of - usage requirements - generated virtual targets, if any target_reference: Target reference project: Project where the reference is made prop...
Registers the specified target as a main target alternatives. Returns 'target'. def main_target_alternative (self, target): """ Registers the specified target as a main target alternatives. Returns 'target'. """ assert isinstance(target, AbstractTarget) target.pr...
Return the list of sources to use, if main target rule is invoked with 'sources'. If there are any objects in 'sources', they are treated as main target instances, and the name of such targets are adjusted to be '<name_of_this_target>__<name_of_source_target>'. Such renaming is disabled ...
Returns the requirement to use when declaring a main target, which are obtained by - translating all specified property paths, and - refining project requirements with the one specified for the target 'specification' are the properties xplicitly specified for a main target...
Returns the use requirement to use when declaraing a main target, which are obtained by - translating all specified property paths, and - adding project's usage requirements specification: Use-properties explicitly specified for a main target project: ...
Return the default build value to use when declaring a main target, which is obtained by using specified value if not empty and parent's default build attribute otherwise. specification: Default build explicitly specified for a main target project: Project where t...
Helper rules to detect cycles in main target references. def start_building (self, main_target_instance): """ Helper rules to detect cycles in main target references. """ assert isinstance(main_target_instance, MainTarget) if id(main_target_instance) in self.targets_being_built_: ...
Creates a TypedTarget with the specified properties. The 'name', 'sources', 'requirements', 'default_build' and 'usage_requirements' are assumed to be in the form specified by the user in Jamfile corresponding to 'project'. def create_typed_target (self, type, project, name, sources...
Generates all possible targets contained in this project. def generate (self, ps): """ Generates all possible targets contained in this project. """ assert isinstance(ps, property_set.PropertySet) self.manager_.targets().log( "Building project '%s' with '%s'" % (self.name ()...
Computes and returns a list of AbstractTarget instances which must be built when this project is built. def targets_to_build (self): """ Computes and returns a list of AbstractTarget instances which must be built when this project is built. """ result = [] if no...
Add 'target' to the list of targets in this project that should be build only by explicit request. def mark_targets_as_explicit (self, target_names): """Add 'target' to the list of targets in this project that should be build only by explicit request.""" # Record the name of the target...
Add new target alternative. def add_alternative (self, target_instance): """ Add new target alternative. """ assert isinstance(target_instance, AbstractTarget) if self.built_main_targets_: raise IllegalOperation ("add-alternative called when main targets are already created ...
Tells if a main target with the specified name exists. def has_main_target (self, name): """Tells if a main target with the specified name exists.""" assert isinstance(name, basestring) if not self.built_main_targets_: self.build_main_targets() return name in self.main_targ...
Returns a 'MainTarget' class instance corresponding to the 'name'. def create_main_target (self, name): """ Returns a 'MainTarget' class instance corresponding to the 'name'. """ assert isinstance(name, basestring) if not self.built_main_targets_: self.build_main_targets () ...
Find and return the target with the specified id, treated relative to self. def find_really(self, id): """ Find and return the target with the specified id, treated relative to self. """ assert isinstance(id, basestring) result = None current_location = ...
Adds a new constant for this project. The constant will be available for use in Jamfile module for this project. If 'path' is true, the constant will be interpreted relatively to the location of project. def add_constant(self, name, value, path=0): """Adds a new constant for th...
Add a new alternative for this target. def add_alternative (self, target): """ Add a new alternative for this target. """ assert isinstance(target, BasicTarget) d = target.default_build () if self.alternatives_ and self.default_build_ != d: get_manager().errors()("d...
Returns the best viable alternative for this property_set See the documentation for selection rules. # TODO: shouldn't this be 'alternative' (singular)? def __select_alternatives (self, property_set_, debug): """ Returns the best viable alternative for this property_set See ...
Select an alternative for this main target, by finding all alternatives which requirements are satisfied by 'properties' and picking the one with longest requirements set. Returns the result of calling 'generate' on that alternative. def generate (self, ps): """ Select an al...
Generates the main target with the given property set and returns a list which first element is property_set object containing usage_requirements of generated target and with generated virtual target in other elements. It's possible that no targets are generated. def __g...
Returns the list of AbstractTargets which are used as sources. The extra properties specified for sources are not represented. The only used of this rule at the moment is the '--dump-tests' feature of the test system. def sources (self): """ Returns the list of AbstractTarge...
Given build request and requirements, return properties common to dependency build request and target build properties. def common_properties (self, build_request, requirements): """ Given build request and requirements, return properties common to dependency build request a...
Returns the alternative condition for this alternative, if the condition is satisfied by 'property_set'. def match (self, property_set_, debug): """ Returns the alternative condition for this alternative, if the condition is satisfied by 'property_set'. """ # The conditi...
Takes a target reference, which might be either target id or a dependency property, and generates that target using 'property_set' as build request. Returns a tuple (result, usage_requirements). def generate_dependency_properties(self, properties, ps): """ Takes a target re...
Determines final build properties, generates sources, and calls 'construct'. This method should not be overridden. def generate (self, ps): """ Determines final build properties, generates sources, and calls 'construct'. This method should not be overridden. """ ...
Given the set of generated targets, and refined build properties, determines and sets appripriate usage requirements on those targets. def compute_usage_requirements (self, subvariant): """ Given the set of generated targets, and refined build properties, determines and sets...
Creates a new subvariant-dg instances for 'targets' - 'root-targets' the virtual targets will be returned to dependents - 'all-targets' all virtual targets created while building this main target - 'build-request' is property-set instance with requested build properties...
Declares a new variant. First determines explicit properties for this variant, by refining parents' explicit properties with the passed explicit properties. The result is remembered and will be used if this variant is used as parent. Second, determines the full property set for ...
Registers all features and variants declared by this module. def register_globals (): """ Registers all features and variants declared by this module. """ # This feature is used to determine which OS we're on. # In future, this may become <target-os> and <host-os> # TODO: check this. Compatibility...
The implementation of the 'lib' rule. Beyond standard syntax that rule allows simplified: 'lib a b c ;'. def lib(names, sources=[], requirements=[], default_build=[], usage_requirements=[]): """The implementation of the 'lib' rule. Beyond standard syntax that rule allows simplified: 'lib a b c ;'.""" a...
For all virtual targets for the same dependency graph as self, i.e. which belong to the same main target, add their directories to include path. def adjust_properties (self, prop_set): """ For all virtual targets for the same dependency graph as self, i.e. which belong to th...
Create a model that makes recommendations using item popularity. When no target column is provided, the popularity is determined by the number of observations involving each item. When a target is provided, popularity is computed using the item's mean target value. When the target column contains rating...
Get parameter.s def get_params(self, deep=False): """Get parameter.s""" params = super(XGBModel, self).get_params(deep=deep) if params['missing'] is np.nan: params['missing'] = None # sklearn doesn't handle nan. see #4725 if not params.get('eval_metric', True): ...
Get xgboost type parameters. def get_xgb_params(self): """Get xgboost type parameters.""" xgb_params = self.get_params() xgb_params['silent'] = 1 if self.silent else 0 if self.nthread <= 0: xgb_params.pop('nthread', None) return xgb_params
Fit the gradient boosting model Parameters ---------- X : array_like Feature matrix y : array_like Labels eval_set : list, optional A list of (X, y) tuple pairs to use as a validation set for early-stopping eval_metric : st...
Fit gradient boosting classifier Parameters ---------- X : array_like Feature matrix y : array_like Labels sample_weight : array_like Weight for each instance eval_set : list, optional A list of (X, y) pairs to use as a val...
Transform a string by bracketing it with "<>". If already bracketed, does nothing. features: one string or a sequence of strings return: the gristed string, if features is a string, or a sequence of gristed strings, if features is a sequence def add_grist (features): """ Transform a string by brack...
Replaces the grist of a string by a new one. Returns the string with the new grist. def replace_grist (features, new_grist): """ Replaces the grist of a string by a new one. Returns the string with the new grist. """ assert is_iterable_typed(features, basestring) or isinstance(features, bas...
Gets the value of a property, that is, the part following the grist, if any. def get_value (property): """ Gets the value of a property, that is, the part following the grist, if any. """ assert is_iterable_typed(property, basestring) or isinstance(property, basestring) return replace_grist (property, ...
Returns the grist of a string. If value is a sequence, does it for every value and returns the result as a sequence. def get_grist (value): """ Returns the grist of a string. If value is a sequence, does it for every value and returns the result as a sequence. """ assert is_iterable_typed(v...
Returns the value without grist. If value is a sequence, does it for every value and returns the result as a sequence. def ungrist (value): """ Returns the value without grist. If value is a sequence, does it for every value and returns the result as a sequence. """ assert is_iterable_typed...
Replaces the suffix of name by new_suffix. If no suffix exists, the new one is added. def replace_suffix (name, new_suffix): """ Replaces the suffix of name by new_suffix. If no suffix exists, the new one is added. """ assert isinstance(name, basestring) assert isinstance(new_suffix, ba...
Splits an id in the toolset and specific rule parts. E.g. 'gcc.compile.c++' returns ('gcc', 'compile.c++') def split_action_id (id): """ Splits an id in the toolset and specific rule parts. E.g. 'gcc.compile.c++' returns ('gcc', 'compile.c++') """ assert isinstance(id, basestring) split...
Returns true if running on windows, whether in cygwin or not. def on_windows (): """ Returns true if running on windows, whether in cygwin or not. """ if bjam.variable("NT"): return True elif bjam.variable("UNIX"): uname = bjam.variable("JAMUNAME") if uname and uname[0].starts...
Validate the main Kmeans dataset. Parameters ---------- dataset: SFrame Input dataset. def _validate_dataset(dataset): """ Validate the main Kmeans dataset. Parameters ---------- dataset: SFrame Input dataset. """ if not (isinstance(dataset, _SFrame)): ...
Validate the initial centers. Parameters ---------- initial_centers : SFrame Initial cluster center locations, in SFrame form. def _validate_initial_centers(initial_centers): """ Validate the initial centers. Parameters ---------- initial_centers : SFrame Initial clust...
Validate the combination of the `num_clusters` and `initial_centers` parameters in the Kmeans model create function. If the combination is valid, determine and return the correct number of clusters. Parameters ---------- num_clusters : int Specified number of clusters. initial_centers ...
Identify the subset of desired `features` that are valid for the Kmeans model. A warning is emitted for each feature that is excluded. Parameters ---------- features : list[str] Desired feature names. column_type_map : dict[str, type] Dictionary mapping each column name to the type...
Create a k-means clustering model. The KmeansModel object contains the computed cluster centers and the cluster assignment for each instance in the input 'dataset'. Given a number of clusters, k-means iteratively chooses the best cluster centers and assigns nearby points to the best cluster. If no poin...
Return predicted cluster label for instances in the new 'dataset'. K-means predictions are made by assigning each new instance to the closest cluster center. Parameters ---------- dataset : SFrame Dataset of new observations. Must include the features used for ...
Return the value of a given field. +-----------------------+----------------------------------------------+ | Field | Description | +=======================+==============================================+ | batch_size | Number ...