INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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. To use specific options of a desired model, use the ``create`` function of the correspond...
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. Models that are trained to predict ratings are compared separately from models that are trained without target ratings. The ratings prediction models are compared on root-mean-squared error, and the re...
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. Let :math:`p_k` be a vecto...
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. The test dataset is generated by first choosing `max_num_users` out of the total number of users in `dataset`. Then, for each of the chosen test users, a portion of the user's items (determined by `item_test_proportion`) is random...
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. Returns ------- out : list A list of fields that can be queried using the ``get`` method.
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. Returns ------- sections : list (of list of tuples) A list of summary sections...
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. 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.
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. Parameters ---------- dataset : SFrame Dataset in the same form used for training. new_observation_data : SFrame, optional ``new_observation_data`` gives additional observa...
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. 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 according to the user-chosen similarity; the factorization_recommender will r...
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`. 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 between latent user factors. (This method is not ...
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. Parameters ---------- users : SArray, SFrame, or list, optional Users or observation queries for which to make recommendations. For list, SArray, and single-column inputs, this is simply a set of user I...
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.` Parameters ---------- observed_items : SArray, SFrame, or list A list/SArray of items to use to make recommendations, or an SFrame of items and optionally ratings and/or...
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. Parameters ---------- dataset : SFrame An SFrame in the same format as the one used during training. This will be compared to the model's recommendations, which exclude the (user, item) p...
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. Parameters ---------- dataset : SFrame An SFrame in the same format as the one used during training. target : str The name of the target rating column in `dataset`. Ret...
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. If the model is trained to predict a particular target, the default metric used for model comparison is root-mean-squared error (RMSE). Suppose :math:`y` and :math:`\widehat{y}` are vectors of lengt...
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. Parameters ---------- item_pairs : 2-column SFrame of two item columns, or a list of (item_1, item_2) tuples. Returns ------- out : SFrame A ...
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. Parameters ---------- filename: str A valid filename where the model can be saved. Examples -------- >>> model.export_coreml('myModel.mlmodel')
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. Parameters ---------- dataset : SFrame Dataset in the same format used for training. The columns names and types of the dataset must be the same as that used in training. metric : str, optional Name of the ev...
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. 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 ---------- dataset : SFrame A dataset that has the...
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...
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...
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)` Parameters ---------- input_features: [list of 2-tuples] ...
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...
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 S...
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. Parameters ---------- dataset : SFrame Dataset of new observations. Must includ...
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 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 file) custom_objects: A dictionary of layers or other custom classes or ...
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 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'). Examples -------- ...
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 Parameters ---------- filepath: string The destination filepath where the plot object must be saved as. The extension of this filepath determines what format the plot will be saved as. Currently sup...
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 th...
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. This currently supports: * Decision tree regression * Gradient boosted tree regression * Random forest regression * Decision tree classifier. * Gradient boosted tree classifier. * Random forest classifier. -------...
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. Parameters ---------- style_dataset: SFrame Input style images. The columns named by the ``style_feature`` parameters will be extracted for training the model. content_dataset : SFrame Input content images. The columns named by the ``conte...
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. Parameters ---------- images : SFrame | Image A dataset that has the same content image column that was used during training. style : int or list, optional The selected styl...
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 Parameters ---------- path : string A string to the path for saving the Core ML model. image_shape: tu...
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 Parameters ---------- style: int or list, optional The selected style or list of styles to return. If `None`, all styles will be returned See Also -------- stylize Examples ...
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. Parameters ---------- model: MXNet model A trained MXNet neural network model. input_shape: list of tuples A list of (name, shape) tuples, defining the input names and their shapes. The list also serves to define the desired order of...
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. 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: libsvm_model A model of the...
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 :param spec: MLModel The MLModel spec containing the feature :param feature_name: str The name of the image feature for which to add shape information. If the...
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 :param spec: MLModel The MLModel spec containing the feature :param feature_name: str The name of the image feature for which to add size information. If the featur...
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 :param spec: MLModel The MLModel spec containing the feature :param feature_name: str The name of the Image feature for which to add shape information. If the feature is not ...
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 :param spec: MLModel The MLModel spec containing the feature :param feature_name: str The name of the feature for which to add shape range information. If the feature is not f...
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. :param spec: MLModel The protobuf specification of the model. :return: Bool Returns True if the model can allow multiple input shapes, False otherwise.
def can_allow_multiple_input_shapes(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. Internally the Sound Classifier calculates deep features for both model creation and predictions. If the same data will be used multiple times, calculating the deep features just once will result in a significant speed up. Parameters -...
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. Parameters ---------- dataset : SFrame Input data. The column named by the 'feature' parameter will be extracted for modeling. target : string or int Name of the column containing the target variable. The values in this column m...
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. Parameters ---------- dataset : SFrame | SArray | dict The audio data to be classified. If dataset is an SFrame, it must have a ...
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. Parameters ---------- dataset : SFrame Dataset to use for evaluation, must include a column with the same name as the features used for model training. Additional colu...
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. See Also -------- save Examples -------- >>> model.export_coreml('./myModel.mlmodel')
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...
Return predictions for ``dataset``. Predictions can be generated as class labels or probabilities. Parameters ---------- dataset : SFrame | SArray | dict The audio data to be classified. If dataset is an SFrame, it must have a column with the same name as ...
def predict(self, dataset, output_type='class', verbose=True, batch_size=64): """ Return predictions for ``dataset``. Predictions can be generated as class labels or probabilities. Parameters ---------- dataset : SFrame | SArray | dict The audio data to be cl...
Return top-k predictions for the ``dataset``. Predictions are returned as an SFrame with three columns: `id`, `class`, and `probability` or `rank` depending on the ``output_type`` parameter. Parameters ---------- dataset : SFrame | SArray | dict The audio dat...
def predict_topk(self, dataset, output_type='probability', k=3, verbose=True, batch_size=64): """ Return top-k predictions for the ``dataset``. Predictions are returned as an SFrame with three columns: `id`, `class`, and `probability` or `rank` depending on the ``output_type`` pa...
Convert data into canonical form.
def _init_data(data, allow_empty, default_name): """Convert data into canonical form.""" assert (data is not None) or allow_empty if data is None: data = [] if isinstance(data, (np.ndarray, NDArray)): data = [data] if isinstance(data, list): if not allow_empty: a...
The name and shape of data provided by this iterator
def provide_data(self): """The name and shape of data provided by this iterator""" return [(k, tuple([self.batch_size] + list(v.shape[1:]))) for k, v in self.data]
The name and shape of label provided by this iterator
def provide_label(self): """The name and shape of label provided by this iterator""" return [(k, tuple([self.batch_size] + list(v.shape[1:]))) for k, v in self.label]
Clear the module state. This is mainly for testing purposes.
def reset (): """ Clear the module state. This is mainly for testing purposes. """ global __generators, __type_to_generators, __generators_for_toolset, __construct_stack global __overrides, __active_generators global __viable_generators_cache, __viable_source_types_cache global __vstg_cached_gen...
Registers new generator instance 'g'.
def register (g): """ Registers new generator instance 'g'. """ assert isinstance(g, Generator) id = g.id() __generators [id] = g # A generator can produce several targets of the # same type. We want unique occurence of that generator # in .generators.$(t) in that case, otherwise, it w...
Creates new instance of the 'generator' class and registers it. Returns the creates instance. Rationale: the instance is returned so that it's possible to first register a generator and then call 'run' method on that generator, bypassing all generator selection.
def register_standard (id, source_types, target_types, requirements = []): """ Creates new instance of the 'generator' class and registers it. Returns the creates instance. Rationale: the instance is returned so that it's possible to first register a generator and then call 'run' method on t...
Make generator 'overrider-id' be preferred to 'overridee-id'. If, when searching for generators that could produce a target of certain type, both those generators are amoung viable generators, the overridden generator is immediately discarded. The overridden generators are discarded immediately ...
def override (overrider_id, overridee_id): """Make generator 'overrider-id' be preferred to 'overridee-id'. If, when searching for generators that could produce a target of certain type, both those generators are amoung viable generators, the overridden generator is immediately discarded. The o...
Returns a list of source type which can possibly be converted to 'target_type' by some chain of generator invocation. More formally, takes all generators for 'target_type' and returns union of source types for those generators and result of calling itself recusrively on source types.
def __viable_source_types_real (target_type): """ Returns a list of source type which can possibly be converted to 'target_type' by some chain of generator invocation. More formally, takes all generators for 'target_type' and returns union of source types for those generators and result ...
Helper rule, caches the result of '__viable_source_types_real'.
def viable_source_types (target_type): """ Helper rule, caches the result of '__viable_source_types_real'. """ assert isinstance(target_type, basestring) if target_type not in __viable_source_types_cache: __vst_cached_types.append(target_type) __viable_source_types_cache [target_type] = ...
Returns the list of source types, which, when passed to 'run' method of 'generator', has some change of being eventually used (probably after conversion by other generators)
def viable_source_types_for_generator_real (generator): """ Returns the list of source types, which, when passed to 'run' method of 'generator', has some change of being eventually used (probably after conversion by other generators) """ assert isinstance(generator, Generator) source_typ...
Caches the result of 'viable_source_types_for_generator'.
def viable_source_types_for_generator (generator): """ Caches the result of 'viable_source_types_for_generator'. """ assert isinstance(generator, Generator) if generator not in __viable_source_types_cache: __vstg_cached_generators.append(generator) __viable_source_types_cache[generator] ...
Returns usage requirements + list of created targets.
def try_one_generator_really (project, name, generator, target_type, properties, sources): """ Returns usage requirements + list of created targets. """ if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(name, basestring) or n...
Checks if generator invocation can be pruned, because it's guaranteed to fail. If so, quickly returns empty list. Otherwise, calls try_one_generator_really.
def try_one_generator (project, name, generator, target_type, properties, sources): """ Checks if generator invocation can be pruned, because it's guaranteed to fail. If so, quickly returns empty list. Otherwise, calls try_one_generator_really. """ if __debug__: from .targets import ...
Ensures all 'targets' have types. If this is not so, exists with error.
def __ensure_type (targets): """ Ensures all 'targets' have types. If this is not so, exists with error. """ assert is_iterable_typed(targets, virtual_target.VirtualTarget) for t in targets: if not t.type (): get_manager().errors()("target '%s' has no type" % str (t))
Returns generators which can be used to construct target of specified type with specified properties. Uses the following algorithm: - iterates over requested target_type and all it's bases (in the order returned bt type.all-bases. - for each type find all generators that generate that ...
def find_viable_generators_aux (target_type, prop_set): """ Returns generators which can be used to construct target of specified type with specified properties. Uses the following algorithm: - iterates over requested target_type and all it's bases (in the order returned bt type.all-bases....
Attempts to construct target by finding viable generators, running them and selecting the dependency graph.
def __construct_really (project, name, target_type, prop_set, sources): """ Attempts to construct target by finding viable generators, running them and selecting the dependency graph. """ if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) ...
Attempts to create target of 'target-type' with 'properties' from 'sources'. The 'sources' are treated as a collection of *possible* ingridients -- i.e. it is not required to consume them all. If 'multiple' is true, the rule is allowed to return several targets of 'target-type'. ...
def construct (project, name, target_type, prop_set, sources, top_level=False): """ Attempts to create target of 'target-type' with 'properties' from 'sources'. The 'sources' are treated as a collection of *possible* ingridients -- i.e. it is not required to consume them all. If 'multiple' i...
Returns another generator which differers from $(self) in - id - value to <toolset> feature in properties
def clone (self, new_id, new_toolset_properties): """ Returns another generator which differers from $(self) in - id - value to <toolset> feature in properties """ assert isinstance(new_id, basestring) assert is_iterable_typed(new_toolset_properties, basestrin...
Creates another generator that is the same as $(self), except that if 'base' is in target types of $(self), 'type' will in target types of the new generator.
def clone_and_change_target_type(self, base, type): """Creates another generator that is the same as $(self), except that if 'base' is in target types of $(self), 'type' will in target types of the new generator.""" assert isinstance(base, basestring) assert isinstance(type, base...
Returns true if the generator can be run with the specified properties.
def match_rank (self, ps): """ Returns true if the generator can be run with the specified properties. """ # See if generator's requirements are satisfied by # 'properties'. Treat a feature name in requirements # (i.e. grist-only element), as matching any value of th...
Tries to invoke this generator on the given sources. Returns a list of generated targets (instances of 'virtual-target'). project: Project for which the targets are generated. name: Determines the name of 'name' attribute for all generat...
def run (self, project, name, prop_set, sources): """ Tries to invoke this generator on the given sources. Returns a list of generated targets (instances of 'virtual-target'). project: Project for which the targets are generated. name: Determines the name o...