INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Print message to the tracker.
def tracker_print(msg): """Print message to the tracker. This function can be used to communicate the information of the progress to the tracker Parameters ---------- msg : str The message to be printed to tracker. """ if not isinstance(msg, str): msg = str(msg) _LI...
Perform allreduce return the result.
def allreduce(data, op, prepare_fun=None): """Perform allreduce, return the result. Parameters ---------- data: numpy array Input data. op: int Reduction operators, can be MIN, MAX, SUM, BITOR prepare_fun: function Lazy preprocessing function, if it is not None, prepare_...
Internal function used by the module unpickle a model from a buffer specified by ptr length Arguments: ptr: ctypes. POINTER ( ctypes. _char ) pointer to the memory region of buffer length: int the length of buffer
def _load_model(ptr, length): """ Internal function used by the module, unpickle a model from a buffer specified by ptr, length Arguments: ptr: ctypes.POINTER(ctypes._char) pointer to the memory region of buffer length: int the length of buffer """ data = ...
Load latest check point.
def load_checkpoint(with_local=False): """Load latest check point. Parameters ---------- with_local: bool, optional whether the checkpoint contains local model Returns ------- tuple : tuple if with_local: return (version, gobal_model, local_model) else return (versi...
Checkpoint the model.
def checkpoint(global_model, local_model=None): """Checkpoint the model. This means we finished a stage of execution. Every time we call check point, there is a version number which will increase by one. Parameters ---------- global_model: anytype that can be pickled globally shared mo...
Converts object detection annotations ( ground truth or predictions ) to stacked format ( an SFrame where each row is one object instance ).
def stack_annotations(annotations_sarray): """ Converts object detection annotations (ground truth or predictions) to stacked format (an `SFrame` where each row is one object instance). Parameters ---------- annotations_sarray: SArray An `SArray` with unstacked predictions, exactly form...
Converts object detection annotations ( ground truth or predictions ) to unstacked format ( an SArray where each element is a list of object instances ).
def unstack_annotations(annotations_sframe, num_rows=None): """ Converts object detection annotations (ground truth or predictions) to unstacked format (an `SArray` where each element is a list of object instances). Parameters ---------- annotations_sframe: SFrame An `SFrame` with s...
Create a RankingFactorizationRecommender that learns latent factors for each user and item and uses them to make rating predictions.
def create(observation_data, user_id='user_id', item_id='item_id', target=None, user_data=None, item_data=None, num_factors=32, regularization=1e-9, linear_regularization=1e-9, side_data_factorization=True, ranking_regularization=0.25, ...
splits _sources/ reference. rst into separate files
def preprocess(): "splits _sources/reference.rst into separate files" text = open("./_sources/reference.rst", "r").read() os.remove("./_sources/reference.rst") if not os.path.exists("./_sources/reference"): os.makedirs("./_sources/reference") def pairwise(iterable): "s -> (s0, s1)...
Returns an unsigned 32 - bit integer that encodes the field number and wire type information in standard protocol message wire format.
def PackTag(field_number, wire_type): """Returns an unsigned 32-bit integer that encodes the field number and wire type information in standard protocol message wire format. Args: field_number: Expected to be an integer in the range [1, 1 << 29) wire_type: One of the WIRETYPE_* constants. """ if not ...
Returns the number of bytes required to serialize a single varint using boundary value comparisons. ( unrolled loop optimization - WPierce ) uint64 must be unsigned.
def _VarUInt64ByteSizeNoTag(uint64): """Returns the number of bytes required to serialize a single varint using boundary value comparisons. (unrolled loop optimization -WPierce) uint64 must be unsigned. """ if uint64 <= 0x7f: return 1 if uint64 <= 0x3fff: return 2 if uint64 <= 0x1fffff: return 3 if uint...
Returns seconds as a human - friendly string e. g. 1d 4h 47m 41s
def _seconds_as_string(seconds): """ Returns seconds as a human-friendly string, e.g. '1d 4h 47m 41s' """ TIME_UNITS = [('s', 60), ('m', 60), ('h', 24), ('d', None)] unit_strings = [] cur = max(int(seconds), 1) for suffix, size in TIME_UNITS: if size is not None: cur, res...
Returns the module holding the conversion functions for a particular model ).
def _get_converter_module(sk_obj): """ Returns the module holding the conversion functions for a particular model). """ try: cv_idx = _converter_lookup[sk_obj.__class__] except KeyError: raise ValueError( "Transformer '%s' not supported; supported transformers are...
Converts a generic sklearn pipeline transformer classifier or regressor into an coreML specification.
def _convert_sklearn_model(input_sk_obj, input_features = None, output_feature_names = None, class_labels = None): """ Converts a generic sklearn pipeline, transformer, classifier, or regressor into an coreML specification. """ if not(HAS_SKLEARN): raise RuntimeErr...
Set the default prediction value ( s ).
def set_default_prediction_value(self, values): """ Set the default prediction value(s). The values given here form the base prediction value that the values at activated leaves are added to. If values is a scalar, then the output of the tree must also be 1 dimensional; otherwi...
r Set the post processing transform applied after the prediction value from the tree ensemble.
def set_post_evaluation_transform(self, value): r""" Set the post processing transform applied after the prediction value from the tree ensemble. Parameters ---------- value: str A value denoting the transform applied. Possible values are: - "...
Add a branch node to the tree ensemble.
def add_branch_node(self, tree_id, node_id, feature_index, feature_value, branch_mode, true_child_id, false_child_id, relative_hit_rate = None, missing_value_tracks_true_child = False): """ Add a branch node to the tree ensemble. Parameters ---------- tre...
Add a leaf node to the tree ensemble.
def add_leaf_node(self, tree_id, node_id, values, relative_hit_rate = None): """ Add a leaf node to the tree ensemble. Parameters ---------- tree_id: int ID of the tree to add the node to. node_id: int ID of the node within the tree. val...
Creates a new PropertySet instance for the given raw properties or returns an already existing one.
def create (raw_properties = []): """ Creates a new 'PropertySet' instance for the given raw properties, or returns an already existing one. """ assert (is_iterable_typed(raw_properties, property.Property) or is_iterable_typed(raw_properties, basestring)) # FIXME: propagate to caller...
Creates new PropertySet instances after checking that all properties are valid and converting implicit properties into gristed form.
def create_with_validation (raw_properties): """ Creates new 'PropertySet' instances after checking that all properties are valid and converting implicit properties into gristed form. """ assert is_iterable_typed(raw_properties, basestring) properties = [property.create_from_string(s) fo...
Creates a property - set from the input given by the user in the context of jamfile - module at location
def create_from_user_input(raw_properties, jamfile_module, location): """Creates a property-set from the input given by the user, in the context of 'jamfile-module' at 'location'""" assert is_iterable_typed(raw_properties, basestring) assert isinstance(jamfile_module, basestring) assert isinstance(l...
Refines requirements with requirements provided by the user. Specially handles - <property > value syntax in specification to remove given requirements. - parent - requirements -- property - set object with requirements to refine - specification -- string list of requirements provided by the use - project - module -- t...
def refine_from_user_input(parent_requirements, specification, jamfile_module, location): """Refines requirements with requirements provided by the user. Specially handles "-<property>value" syntax in specification to remove given requirements. - parent-requirements -- prope...
Returns properties that are neither incidental nor free.
def base (self): """ Returns properties that are neither incidental nor free. """ result = [p for p in self.lazy_properties if not(p.feature.incidental or p.feature.free)] result.extend(self.base_) return result
Returns free properties which are not dependency properties.
def free (self): """ Returns free properties which are not dependency properties. """ result = [p for p in self.lazy_properties if not p.feature.incidental and p.feature.free] result.extend(self.free_) return result
Returns dependency properties.
def dependency (self): """ Returns dependency properties. """ result = [p for p in self.lazy_properties if p.feature.dependency] result.extend(self.dependency_) return self.dependency_
Returns properties that are not dependencies.
def non_dependency (self): """ Returns properties that are not dependencies. """ result = [p for p in self.lazy_properties if not p.feature.dependency] result.extend(self.non_dependency_) return result
Returns incidental properties.
def incidental (self): """ Returns incidental properties. """ result = [p for p in self.lazy_properties if p.feature.incidental] result.extend(self.incidental_) return result
Refines this set s properties using the requirements passed as an argument.
def refine (self, requirements): """ Refines this set's properties using the requirements passed as an argument. """ assert isinstance(requirements, PropertySet) if requirements not in self.refined_: r = property.refine(self.all_, requirements.all_) self.refined_...
Computes the target path that should be used for target with these properties. Returns a tuple of - the computed path - if the path is relative to build directory a value of true.
def target_path (self): """ Computes the target path that should be used for target with these properties. Returns a tuple of - the computed path - if the path is relative to build directory, a value of 'true'. """ if not self.t...
Creates a new property set containing the properties in this one plus the ones of the property set passed as argument.
def add (self, ps): """ Creates a new property set containing the properties in this one, plus the ones of the property set passed as argument. """ assert isinstance(ps, PropertySet) if ps not in self.added_: self.added_[ps] = create(self.all_ + ps.all()) ...
Returns all values of feature.
def get (self, feature): """ Returns all values of 'feature'. """ if type(feature) == type([]): feature = feature[0] if not isinstance(feature, b2.build.feature.Feature): feature = b2.build.feature.get(feature) assert isinstance(feature, b2.build.feature.F...
Returns all contained properties associated with feature
def get_properties(self, feature): """Returns all contained properties associated with 'feature'""" if not isinstance(feature, b2.build.feature.Feature): feature = b2.build.feature.get(feature) assert isinstance(feature, b2.build.feature.Feature) result = [] for p in...
A unified interface for training recommender models. Based on simple characteristics of the data a type of model is selected and trained. The trained model can be used to predict ratings and make recommendations.
def _create(observation_data, user_id='user_id', item_id='item_id', target=None, user_data=None, item_data=None, ranking=True, verbose=True): """ A unified interface for training recommender models. Based on simple characteristics of the data, a type of model is s...
Compare the prediction or recommendation performance of recommender models on a common test dataset.
def compare_models(dataset, models, model_names=None, user_sample=1.0, metric='auto', target=None, exclude_known_for_precision_recall=True, make_plot=False, verbose=True, **kwargs): """ Compare the ...
Compute precision and recall at a given cutoff for each user. In information retrieval terms precision represents the ratio of relevant retrieved items to the number of relevant items. Recall represents the ratio of relevant retrieved items to the number of relevant items.
def precision_recall_by_user(observed_user_items, recommendations, cutoffs=[10]): """ Compute precision and recall at a given cutoff for each user. In information retrieval terms, precision represents the ratio of relevant, retrieved items to the...
Create a recommender - friendly train - test split of the provided data set.
def random_split_by_user(dataset, user_id='user_id', item_id='item_id', max_num_users=1000, item_test_proportion=.2, random_seed=0): """Create a recommender-friendly train-test split of the p...
Get the current settings of the model. The keys depend on the type of model.
def _list_fields(self): """ Get the current settings of the model. The keys depend on the type of model. Returns ------- out : list A list of fields that can be queried using the ``get`` method. """ response = self.__proxy__.list_fields() ...
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...
Set current options for a model.
def _set_current_options(self, options): """ Set current options for a model. Parameters ---------- options : dict A dictionary of the desired option settings. The key should be the name of the option and each value is the desired value of the option. ...
Processes the dataset parameter for type correctness. Returns it as an SFrame.
def __prepare_dataset_parameter(self, dataset): """ Processes the dataset parameter for type correctness. Returns it as an SFrame. """ # Translate the dataset argument into the proper type if not isinstance(dataset, _SFrame): def raise_dataset_type_exception(...
Returns a dictionary of ( column: type ) for the data used in the model.
def _get_data_schema(self): """ Returns a dictionary of (column : type) for the data used in the model. """ if not hasattr(self, "_data_schema"): response = self.__proxy__.get_data_schema() self._data_schema = {k : _turicreate._cython.cy_flexible_type.py...
Return a score prediction for the user ids and item ids in the provided data set.
def predict(self, dataset, new_observation_data=None, new_user_data=None, new_item_data=None): """ Return a score prediction for the user ids and item ids in the provided data set. Parameters ---------- dataset : SFrame Dataset in the same for...
Get the k most similar items for each item in items.
def get_similar_items(self, items=None, k=10, verbose=False): """ Get the k most similar items for each item in items. Each type of recommender has its own model for the similarity between items. For example, the item_similarity_recommender will return the most similar items acc...
Get the k most similar users for each entry in users.
def get_similar_users(self, users=None, k=10): """Get the k most similar users for each entry in `users`. Each type of recommender has its own model for the similarity between users. For example, the factorization_recommender will return the nearest users based on the cosine similarity ...
Recommend the k highest scored items for each user.
def recommend(self, users=None, k=10, exclude=None, items=None, new_observation_data=None, new_user_data=None, new_item_data=None, exclude_known=True, diversity=0, random_seed=None, verbose=True): """ Recommend the ``k`` highest scored items for each...
Recommend the k highest scored items based on the interactions given in observed_items.
def recommend_from_interactions( self, observed_items, k=10, exclude=None, items=None, new_user_data=None, new_item_data=None, exclude_known=True, diversity=0, random_seed=None, verbose=True): """ Recommend the ``k`` highest scored items based on the ...
Compute a model s precision and recall scores for a particular dataset.
def evaluate_precision_recall(self, dataset, cutoffs=list(range(1,11,1))+list(range(11,50,5)), skip_set=None, exclude_known=True, verbose=True, **kwargs): """ Compute a model's precision and recall scores for a particular dataset. ...
Evaluate the prediction error for each user - item pair in the given data set.
def evaluate_rmse(self, dataset, target): """ Evaluate the prediction error for each user-item pair in the given data set. Parameters ---------- dataset : SFrame An SFrame in the same format as the one used during training. target : str T...
r Evaluate the model s ability to make rating predictions or recommendations.
def evaluate(self, dataset, metric='auto', exclude_known_for_precision_recall=True, target=None, verbose=True, **kwargs): r""" Evaluate the model's ability to make rating predictions or recommendations. If the model is trained to predic...
Returns a new popularity model matching the data set this model was trained with. Can be used for comparison purposes.
def _get_popularity_baseline(self): """ Returns a new popularity model matching the data set this model was trained with. Can be used for comparison purposes. """ response = self.__proxy__.get_popularity_baseline() from .popularity_recommender import PopularityRecommen...
For a collection of item - > item pairs returns information about the users in that intersection.
def _get_item_intersection_info(self, item_pairs): """ For a collection of item -> item pairs, returns information about the users in that intersection. Parameters ---------- item_pairs : 2-column SFrame of two item columns, or a list of (item_1, item_2) tupl...
Export the model in Core ML format.
def export_coreml(self, filename): """ Export the model in Core ML format. Parameters ---------- filename: str A valid filename where the model can be saved. Examples -------- >>> model.export_coreml('myModel.mlmodel') """ print...
Evaluate the model on the given dataset.
def evaluate(self, dataset, metric='auto', missing_value_action='auto'): """ Evaluate the model on the given dataset. Parameters ---------- dataset : SFrame Dataset in the same format used for training. The columns names and types of the dataset must be ...
Predict the target column of the given dataset.
def predict(self, dataset, missing_value_action='auto'): """ Predict the target column of the given dataset. The target column is provided during :func:`~turicreate.random_forest_regression.create`. If the target column is in the `dataset` it will be ignored. Parameters...
Creates a feature vectorizer from input features return the spec for a feature vectorizer that puts everything into a single array of length equal to the total size of all the input features. Returns a 2 - tuple ( spec num_dimension )
def create_feature_vectorizer(input_features, output_feature_name, known_size_map = {}): """ Creates a feature vectorizer from input features, return the spec for a feature vectorizer that puts everything into a single array of length equal to the total size of all the inpu...
Read in the Boost version from a given boost_root.
def query_boost_version(boost_root): ''' Read in the Boost version from a given boost_root. ''' boost_version = None if os.path.exists(os.path.join(boost_root,'Jamroot')): with codecs.open(os.path.join(boost_root,'Jamroot'), 'r', 'utf-8') as f: for lin...
This clone mimicks the way Travis - CI clones a project s repo. So far Travis - CI is the most limiting in the sense of only fetching partial history of the repo.
def git_clone(sub_repo, branch, commit = None, cwd = None, no_submodules = False): ''' This clone mimicks the way Travis-CI clones a project's repo. So far Travis-CI is the most limiting in the sense of only fetching partial history of the repo. ''' if not cwd: ...
Installs specific toolset on CI system.
def install_toolset(self, toolset): ''' Installs specific toolset on CI system. ''' info = toolset_info[toolset] if sys.platform.startswith('linux'): os.chdir(self.work_dir) if 'ppa' in info: for ppa in info['ppa']: util...
Create a: class: ~turicreate. svm_classifier. SVMClassifier to predict the class of a binary target variable based on a model of which side of a hyperplane the example falls on. In addition to standard numeric and categorical types features can also be extracted automatically from list - or dictionary - type SFrame col...
def create(dataset, target, features=None, penalty=1.0, solver='auto', feature_rescaling=True, convergence_threshold = _DEFAULT_SOLVER_OPTIONS['convergence_threshold'], lbfgs_memory_level = _DEFAULT_SOLVER_OPTIONS['lbfgs_memory_level'], max_iterations = _DEFAULT_SOLVER_OPTIONS['max_iterations'], ...
Return a classification for each example in the dataset using the trained SVM model. The output SFrame contains predictions as class labels ( 0 or 1 ) associated with the the example.
def classify(self, dataset, missing_value_action='auto'): """ Return a classification, for each example in the ``dataset``, using the trained SVM model. The output SFrame contains predictions as class labels (0 or 1) associated with the the example. Parameters ----------...
Get the right converter function for Keras
def _get_layer_converter_fn(layer, add_custom_layers = False): """Get the right converter function for Keras """ layer_type = type(layer) if layer_type in _KERAS_LAYER_REGISTRY: convert_func = _KERAS_LAYER_REGISTRY[layer_type] if convert_func is _layers2.convert_activation: a...
Load a keras model from disk
def _load_keras_model(model_network_path, model_weight_path, custom_objects=None): """Load a keras model from disk Parameters ---------- model_network_path: str Path where the model network path is (json file) model_weight_path: str Path where the model network weights are (hd5 fil...
A method for displaying the Plot object
def show(self): """ A method for displaying the Plot object Notes ----- - The plot will render either inline in a Jupyter Notebook, or in a native GUI window, depending on the value provided in `turicreate.visualization.set_target` (defaults to 'auto'). ...
A method for saving the Plot object in a vega representation
def save(self, filepath): """ A method for saving the Plot object in a vega representation Parameters ---------- filepath: string The destination filepath where the plot object must be saved as. The extension of this filepath determines what format the pl...
customized submit script that submit nslave jobs each must contain args as parameter note this can be a lambda function containing additional parameters in input Parameters nslave number of slave process to start up args arguments to launch each job this usually includes the parameters of master_uri and parameters pass...
def mthread_submit(nslave, worker_args, worker_envs): """ customized submit script, that submit nslave jobs, each must contain args as parameter note this can be a lambda function containing additional parameters in input Parameters nslave number of slave process to start up args...
Get the right value from the scikit - tree
def _get_value(scikit_value, mode = 'regressor', scaling = 1.0, n_classes = 2, tree_index = 0): """ Get the right value from the scikit-tree """ # Regression if mode == 'regressor': return scikit_value[0] * scaling # Binary classification if n_classes == 2: # Decision tree ...
Traverse through the tree and append to the tree spec.
def _recurse(coreml_tree, scikit_tree, tree_id, node_id, scaling = 1.0, mode = 'regressor', n_classes = 2, tree_index = 0): """Traverse through the tree and append to the tree spec. """ if not(HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disab...
Convert a generic tree regressor model to the protobuf spec.
def convert_tree_ensemble(model, input_features, output_features = ('predicted_class', float), mode = 'regressor', base_prediction = None, class_labels = None, post_evaluation_transform = No...
Takes images scaled to [ 0 1 ] and returns them appropriately scaled and mean - subtracted for VGG - 16
def _vgg16_data_prep(batch): """ Takes images scaled to [0, 1] and returns them appropriately scaled and mean-subtracted for VGG-16 """ from mxnet import nd mean = nd.array([123.68, 116.779, 103.939], ctx=batch.context) return nd.broadcast_sub(255 * batch, mean.reshape((-1, 1, 1)))
Create a: class: StyleTransfer model.
def create(style_dataset, content_dataset, style_feature=None, content_feature=None, max_iterations=None, model='resnet-16', verbose=True, batch_size = 6, **kwargs): """ Create a :class:`StyleTransfer` model. Parameters ---------- style_dataset: SFrame Input style images. Th...
Takes input and returns tuple of the input in canonical form ( SFrame ) along with an unpack callback function that can be applied to prediction results to undo the canonization.
def _canonize_content_input(self, dataset, single_style): """ Takes input and returns tuple of the input in canonical form (SFrame) along with an unpack callback function that can be applied to prediction results to "undo" the canonization. """ unpack = lambda x: x ...
Stylize an SFrame of Images given a style index or a list of styles.
def stylize(self, images, style=None, verbose=True, max_size=800, batch_size = 4): """ Stylize an SFrame of Images given a style index or a list of styles. Parameters ---------- images : SFrame | Image A dataset that has the same content image column that was...
Save the model in Core ML format. The Core ML model takes an image of fixed size and a style index inputs and produces an output of an image of fixed size
def export_coreml(self, path, image_shape=(256, 256), include_flexible_shape=True): """ Save the model in Core ML format. The Core ML model takes an image of fixed size, and a style index inputs and produces an output of an image of fixed size Parameters -------...
Returns SFrame of style images used for training the model
def get_styles(self, style=None): """ Returns SFrame of style images used for training the model Parameters ---------- style: int or list, optional The selected style or list of styles to return. If `None`, all styles will be returned See Also ...
Convert an MXNet model to the protobuf spec.
def convert(model, input_shape, class_labels=None, mode=None, preprocessor_args=None, builder=None, verbose=True): """Convert an MXNet model to the protobuf spec. Parameters ---------- model: MXNet model A trained MXNet neural network model. input_shape: list of tuples ...
Load a libsvm model from a path on disk.
def load_model(model_path): """Load a libsvm model from a path on disk. This currently supports: * C-SVC * NU-SVC * Epsilon-SVR * NU-SVR Parameters ---------- model_path: str Path on disk where the libsvm model representation is. Returns ------- model: ...
Annotate an input or output multiArray feature in a Neural Network spec to to accommodate a list of enumerated array shapes
def add_enumerated_multiarray_shapes(spec, feature_name, shapes): """ 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 Th...
Annotate an input or output image feature in a Neural Network spec to to accommodate a list of enumerated image sizes
def add_enumerated_image_sizes(spec, feature_name, sizes): """ 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...
Annotate an input or output Image feature in a Neural Network spec to to accommodate a range of image sizes
def update_image_size_range(spec, feature_name, size_range): """ 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 f...
Annotate an input or output MLMultiArray feature in a Neural Network spec to accommodate a range of shapes
def update_multiarray_shape_range(spec, feature_name, shape_range): """ 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 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) inputs = _get_input_names(spec) output = {} for input in inputs: output[input] = shaper...
Examines a model specification and determines if it can compute results for more than one output shape.
def can_allow_multiple_input_shapes(spec): """ 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, ...
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.arrayShapeRange.items(): if key in _CONSTRAINED_KEYS: if value.isFlexible: r...
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: arg_list = '({0})'.format(', '.join(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 - 1, length_limit_s...
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_ >= {0} ? {0} : ('.format(s) fo...
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: generate_take(out_f, steps, nsp.prefix(...
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{0}/cpp11/impl/concat....
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' ) parser.add_argument( '...
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.
def get_deep_features(audio_data, verbose=True): ''' 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 wil...
Creates a: class: SoundClassifier model.
def create(dataset, target, feature, max_iterations=10, custom_layer_sizes=[100, 100], verbose=True, validation_set='auto', batch_size=64): ''' Creates a :class:`SoundClassifier` model. Parameters ---------- dataset : SFrame Input data. The column named by the 'feature...
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 state['_feature_extractor'] = _get_feature_extractor(state['feat...
Return the classification for each examples in the dataset. The output SFrame contains predicted class labels and its probability.
def classify(self, dataset, verbose=True, batch_size=64): """ 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 aud...
Evaluate the model by making predictions of target values and comparing these to actual values.
def evaluate(self, dataset, metric='auto', verbose=True, batch_size=64): """ 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 c...
Save the model in Core ML format.
def export_coreml(self, filename): """ Save the model in Core ML format. See Also -------- save Examples -------- >>> model.export_coreml('./myModel.mlmodel') """ import coremltools from coremltools.proto.FeatureTypes_pb2 import A...