Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def refine (self, requirements): assert isinstance(requirements, PropertySet) if requirements not in self.refined_: r = property.refine(self.all_, requirements.all_) self.refined_[requirements] = create(r) return sel...
[ " Refines this set's properties using the requirements passed as an argument.\n " ]
Please provide a description of the function:def target_path (self): if not self.target_path_: # The <location> feature can be used to explicitly # change the location of generated targets l = self.get ('<location>') if l: computed = l[0] ...
[ " Computes the target path that should be used for\n target with these properties.\n Returns a tuple of\n - the computed path\n - if the path is relative to build directory, a value of\n 'true'.\n " ]
Please provide a description of the function:def add (self, ps): assert isinstance(ps, PropertySet) if ps not in self.added_: self.added_[ps] = create(self.all_ + ps.all()) return self.added_[ps]
[ " Creates a new property set containing the properties in this one,\n plus the ones of the property set passed as argument.\n " ]
Please provide a description of the function:def get (self, 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.Feat...
[ " Returns all values of 'feature'.\n " ]
Please provide a description of the function:def get_properties(self, 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 self.all_: ...
[ "Returns all contained properties associated with 'feature'" ]
Please provide a description of the function:def _create(observation_data, user_id='user_id', item_id='item_id', target=None, user_data=None, item_data=None, ranking=True, verbose=True): if not (isinstance(observation_data, _SFrame)): raise TypeError('observ...
[ "\n A unified interface for training recommender models. Based on simple\n characteristics of the data, a type of model is selected and trained. The\n trained model can be used to predict ratings and make recommendations.\n\n To use specific options of a desired model, use the ``create`` function\n o...
Please provide a description of the function: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, ...
[ "\n Compare the prediction or recommendation performance of recommender models\n on a common test dataset.\n\n Models that are trained to predict ratings are compared separately from\n models that are trained without target ratings. The ratings prediction\n models are compared on root-mean-squared e...
Please provide a description of the function:def precision_recall_by_user(observed_user_items, recommendations, cutoffs=[10]): assert type(observed_user_items) == _SFrame assert type(recommendations) == _SFrame assert type(cutoffs) == list ...
[ "\n Compute precision and recall at a given cutoff for each user. In information\n retrieval terms, precision represents the ratio of relevant, retrieved items\n to the number of relevant items. Recall represents the ratio of relevant,\n retrieved items to the number of relevant items.\n\n Let :math:...
Please provide a description of the function: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): assert ...
[ "Create a recommender-friendly train-test split of the provided data set.\n\n The test dataset is generated by first choosing `max_num_users` out of the\n total number of users in `dataset`. Then, for each of the chosen test users,\n a portion of the user's items (determined by `item_test_proportion`) is\n...
Please provide a description of the function:def _list_fields(self): response = self.__proxy__.list_fields() return [s for s in response['value'] if not s.startswith("_")]
[ "\n Get the current settings of the model. The keys depend on the type of\n model.\n\n Returns\n -------\n out : list\n A list of fields that can be queried using the ``get`` method.\n " ]
Please provide a description of the function:def _get_summary_struct(self): stats = self._list_fields() options = self._get_current_options() section_titles = [] sections = [] observation_columns = set(self.observation_data_column_names) not_needed = set([self...
[ "\n Returns a structured description of the model, including (where relevant)\n the schema of the training data, description of the training data,\n training statistics, and model hyperparameters.\n\n Returns\n -------\n sections : list (of list of tuples)\n A li...
Please provide a description of the function:def _set_current_options(self, options): opts = self._get_current_options() opts.update(options) response = self.__proxy__.set_current_options(opts) return response
[ "\n Set current options for a model.\n\n Parameters\n ----------\n options : dict\n A dictionary of the desired option settings. The key should be the name\n of the option and each value is the desired value of the option.\n " ]
Please provide a description of the function:def __prepare_dataset_parameter(self, dataset): # Translate the dataset argument into the proper type if not isinstance(dataset, _SFrame): def raise_dataset_type_exception(): raise TypeError("The dataset parameter must be...
[ "\n Processes the dataset parameter for type correctness.\n Returns it as an SFrame.\n " ]
Please provide a description of the function:def _get_data_schema(self): if not hasattr(self, "_data_schema"): response = self.__proxy__.get_data_schema() self._data_schema = {k : _turicreate._cython.cy_flexible_type.pytype_from_type_name(v) fo...
[ "\n Returns a dictionary of (column : type) for the data used in the\n model.\n " ]
Please provide a description of the function:def predict(self, dataset, new_observation_data=None, new_user_data=None, new_item_data=None): if new_observation_data is None: new_observation_data = _SFrame() if new_user_data is None: new_user_data = _SFram...
[ "\n Return a score prediction for the user ids and item ids in the provided\n data set.\n\n Parameters\n ----------\n dataset : SFrame\n Dataset in the same form used for training.\n\n new_observation_data : SFrame, optional\n ``new_observation_data`` ...
Please provide a description of the function:def get_similar_items(self, items=None, k=10, verbose=False): if items is None: get_all_items = True items = _SArray() else: get_all_items = False if isinstance(items, list): items = _SArray(i...
[ "\n Get the k most similar items for each item in items.\n\n Each type of recommender has its own model for the similarity\n between items. For example, the item_similarity_recommender will\n return the most similar items according to the user-chosen\n similarity; the factorizatio...
Please provide a description of the function:def get_similar_users(self, users=None, k=10): if users is None: get_all_users = True users = _SArray() else: get_all_users = False if isinstance(users, list): users = _SArray(users) ...
[ "Get the k most similar users for each entry in `users`.\n\n Each type of recommender has its own model for the similarity\n between users. For example, the factorization_recommender will\n return the nearest users based on the cosine similarity\n between latent user factors. (This meth...
Please provide a description of the function: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): from tu...
[ "\n Recommend the ``k`` highest scored items for each user.\n\n Parameters\n ----------\n users : SArray, SFrame, or list, optional\n Users or observation queries for which to make recommendations.\n For list, SArray, and single-column inputs, this is simply a set\...
Please provide a description of the function: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): column_types = s...
[ "\n Recommend the ``k`` highest scored items based on the\n interactions given in `observed_items.`\n\n Parameters\n ----------\n observed_items : SArray, SFrame, or list\n A list/SArray of items to use to make recommendations, or\n an SFrame of items and opt...
Please provide a description of the function: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): user_column = self.user_id ...
[ "\n Compute a model's precision and recall scores for a particular dataset.\n\n Parameters\n ----------\n dataset : SFrame\n An SFrame in the same format as the one used during training.\n This will be compared to the model's recommendations, which exclude\n ...
Please provide a description of the function:def evaluate_rmse(self, dataset, target): assert target in dataset.column_names(), \ 'Provided dataset must contain a target column with the same \ name as the target used during training.' y = dataset[target] ...
[ "\n Evaluate the prediction error for each user-item pair in the given data\n set.\n\n Parameters\n ----------\n dataset : SFrame\n An SFrame in the same format as the one used during training.\n\n target : str\n The name of the target rating column in...
Please provide a description of the function:def evaluate(self, dataset, metric='auto', exclude_known_for_precision_recall=True, target=None, verbose=True, **kwargs): r ret = {} dataset = self.__prepare_dataset_parameter(dataset) # If...
[ "\n Evaluate the model's ability to make rating predictions or\n recommendations.\n\n If the model is trained to predict a particular target, the\n default metric used for model comparison is root-mean-squared error\n (RMSE). Suppose :math:`y` and :math:`\\widehat{y}` are vectors ...
Please provide a description of the function:def _get_popularity_baseline(self): response = self.__proxy__.get_popularity_baseline() from .popularity_recommender import PopularityRecommender return PopularityRecommender(response)
[ "\n Returns a new popularity model matching the data set this model was\n trained with. Can be used for comparison purposes.\n " ]
Please provide a description of the function:def _get_item_intersection_info(self, item_pairs): if type(item_pairs) is list: if not all(type(t) in [list, tuple] and len(t) == 2 for t in item_pairs): raise TypeError("item_pairs must be 2-column SFrame of two item " ...
[ "\n For a collection of item -> item pairs, returns information about the\n users in that intersection.\n\n Parameters\n ----------\n\n item_pairs : 2-column SFrame of two item columns, or a list of\n (item_1, item_2) tuples.\n\n Returns\n -------\n ...
Please provide a description of the function:def export_coreml(self, filename): print('This model is exported as a custom Core ML model. In order to use it in your\n' 'application, you must also include "libRecommender.dylib". For additional\n' 'details see:\n' ...
[ "\n Export the model in Core ML format.\n\n Parameters\n ----------\n filename: str\n A valid filename where the model can be saved.\n\n Examples\n --------\n >>> model.export_coreml('myModel.mlmodel')\n " ]
Please provide a description of the function:def evaluate(self, dataset, metric='auto', missing_value_action='auto'): _raise_error_evaluation_metric_is_valid( metric, ['auto', 'rmse', 'max_error']) return super(RandomForestRegression, self).evaluate(dataset, ...
[ "\n Evaluate the model on the given dataset.\n\n\n Parameters\n ----------\n dataset : SFrame\n Dataset in the same format used for training. The columns names and\n types of the dataset must be the same as that used in training.\n\n metric : str, optional\n ...
Please provide a description of the function:def predict(self, dataset, missing_value_action='auto'): return super(RandomForestRegression, self).predict(dataset, output_type='margin', m...
[ "\n Predict the target column of the given dataset.\n\n The target column is provided during\n :func:`~turicreate.random_forest_regression.create`. If the target column is in the\n `dataset` it will be ignored.\n\n Parameters\n ----------\n dataset : SFrame\n ...
Please provide a description of the function:def create_feature_vectorizer(input_features, output_feature_name, known_size_map = {}): spec = _Model_pb2.Model() spec.specificationVersion = SPECIFICATION_VERSION input_features = process_or_validate_features(input_features)...
[ "\n Creates a feature vectorizer from input features, return the spec for\n a feature vectorizer that puts everything into a single array of length\n equal to the total size of all the input features. Returns a 2-tuple\n `(spec, num_dimension)`\n\n Parameters\n ----------\n input_features: [li...
Please provide a description of the function: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')...
[]
Please provide a description of the function: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 rep...
[]
Please provide a description of the function: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...
[]
Please provide a description of the function: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 = _...
[ "\n Create a :class:`~turicreate.svm_classifier.SVMClassifier` to predict the class of a binary\n target variable based on a model of which side of a hyperplane the example\n falls on. In addition to standard numeric and categorical types, features\n can also be extracted automatically from list- or dic...
Please provide a description of the function:def classify(self, dataset, missing_value_action='auto'): return super(SVMClassifier, self).classify(dataset, missing_value_action=missing_value_action)
[ "\n Return a classification, for each example in the ``dataset``, using the\n trained SVM model. The output SFrame contains predictions\n as class labels (0 or 1) associated with the the example.\n\n Parameters\n ----------\n dataset : SFrame\n Dataset of new obs...
Please provide a description of the function:def _get_layer_converter_fn(layer, add_custom_layers = False): 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: act_name ...
[ "Get the right converter function for Keras\n " ]
Please provide a description of the function:def _load_keras_model(model_network_path, model_weight_path, custom_objects=None): from keras.models import model_from_json import json # Load the model network json_file = open(model_network_path, 'r') loaded_model_json = json_file.read() json_...
[ "Load a keras model from disk\n\n Parameters\n ----------\n model_network_path: str\n Path where the model network path is (json file)\n\n model_weight_path: str\n Path where the model network weights are (hd5 file)\n\n custom_objects:\n A dictionary of layers or other custom cla...
Please provide a description of the function:def show(self): global _target display = False try: if _target == 'auto' and \ get_ipython().__class__.__name__ == "ZMQInteractiveShell": self._repr_javascript_() display = True ...
[ "\n A method for displaying the Plot object\n\n Notes\n -----\n - The plot will render either inline in a Jupyter Notebook, or in a\n native GUI window, depending on the value provided in\n `turicreate.visualization.set_target` (defaults to 'auto').\n\n Examples\...
Please provide a description of the function:def save(self, filepath): if type(filepath) != str: raise ValueError("filepath provided is not a string") if filepath.endswith(".json"): # save as vega json spec = self.get_vega(include_data = True) wi...
[ "\n A method for saving the Plot object in a vega representation\n\n Parameters\n ----------\n filepath: string\n The destination filepath where the plot object must be saved as.\n The extension of this filepath determines what format the plot will\n be s...
Please provide a description of the function:def mthread_submit(nslave, worker_args, worker_envs): procs = {} for i in range(nslave): procs[i] = Thread(target = exec_cmd, args = (args.command + worker_args, i, worker_envs)) procs[i].daemon = True procs[i].start() for i in...
[ "\n customized submit script, that submit nslave jobs, each must contain args as parameter\n note this can be a lambda function containing additional parameters in input\n Parameters\n nslave number of slave process to start up\n args arguments to launch each job\n this u...
Please provide a description of the function:def _get_value(scikit_value, mode = 'regressor', scaling = 1.0, n_classes = 2, tree_index = 0): # Regression if mode == 'regressor': return scikit_value[0] * scaling # Binary classification if n_classes == 2: # Decision tree if l...
[ " Get the right value from the scikit-tree\n " ]
Please provide a description of the function:def _recurse(coreml_tree, scikit_tree, tree_id, node_id, scaling = 1.0, mode = 'regressor', n_classes = 2, tree_index = 0): if not(HAS_SKLEARN): raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.') ## Recur...
[ "Traverse through the tree and append to the tree spec.\n " ]
Please provide a description of the function:def convert_tree_ensemble(model, input_features, output_features = ('predicted_class', float), mode = 'regressor', base_prediction = None, class_labels = None, ...
[ "\n Convert a generic tree regressor model to the protobuf spec.\n\n This currently supports:\n * Decision tree regression\n * Gradient boosted tree regression\n * Random forest regression\n * Decision tree classifier.\n * Gradient boosted tree classifier.\n * Random forest class...
Please provide a description of the function:def _vgg16_data_prep(batch): 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)))
[ "\n Takes images scaled to [0, 1] and returns them appropriately scaled and\n mean-subtracted for VGG-16\n " ]
Please provide a description of the function:def create(style_dataset, content_dataset, style_feature=None, content_feature=None, max_iterations=None, model='resnet-16', verbose=True, batch_size = 6, **kwargs): if len(style_dataset) == 0: raise _ToolkitError("style_dataset SFrame cannot...
[ "\n Create a :class:`StyleTransfer` model.\n\n Parameters\n ----------\n style_dataset: SFrame\n Input style images. The columns named by the ``style_feature`` parameters will\n be extracted for training the model.\n\n content_dataset : SFrame\n Input content images. The columns ...
Please provide a description of the function:def _canonize_content_input(self, dataset, single_style): unpack = lambda x: x if isinstance(dataset, _tc.SArray): dataset = _tc.SFrame({self.content_feature: dataset}) if single_style: unpack = lambda sf: sf['...
[ "\n Takes input and returns tuple of the input in canonical form (SFrame)\n along with an unpack callback function that can be applied to\n prediction results to \"undo\" the canonization.\n " ]
Please provide a description of the function:def stylize(self, images, style=None, verbose=True, max_size=800, batch_size = 4): if(batch_size < 1): raise _ToolkitError("'batch_size' must be greater than or equal to 1") from ._sframe_loader import SFrameSTIter as _SFrameSTIter ...
[ "\n Stylize an SFrame of Images given a style index or a list of\n styles.\n\n Parameters\n ----------\n images : SFrame | Image\n A dataset that has the same content image column that was used\n during training.\n\n style : int or list, optional\n ...
Please provide a description of the function:def export_coreml(self, path, image_shape=(256, 256), include_flexible_shape=True): import mxnet as _mx from .._mxnet._mxnet_to_coreml import _mxnet_converter import coremltools transformer = self._model index = _mx....
[ "\n Save the model in Core ML format. The Core ML model takes an image of\n fixed size, and a style index inputs and produces an output\n of an image of fixed size\n\n Parameters\n ----------\n path : string\n A string to the path for saving the Core ML model.\n\...
Please provide a description of the function:def get_styles(self, style=None): style, _ = self._style_input_check(style) return self.styles.filter_by(style, self._index_column)
[ "\n Returns SFrame of style images used for training the model\n\n Parameters\n ----------\n style: int or list, optional\n The selected style or list of styles to return. If `None`, all\n styles will be returned\n\n See Also\n --------\n styliz...
Please provide a description of the function:def convert(model, input_shape, class_labels=None, mode=None, preprocessor_args=None, builder=None, verbose=True): if not isinstance(input_shape, list): raise TypeError("Must provide a list for input shape. e.g input_shape=[('data', (3,224,224))...
[ "Convert an MXNet model to the protobuf spec.\n\n Parameters\n ----------\n model: MXNet model\n A trained MXNet neural network model.\n\n input_shape: list of tuples\n A list of (name, shape) tuples, defining the input names and their\n shapes. The list also serves to define the de...
Please provide a description of the function:def load_model(model_path): if not(HAS_LIBSVM): raise RuntimeError('libsvm not found. libsvm conversion API is disabled.') from svmutil import svm_load_model # From libsvm import os if (not os.path.exists(model_path)): raise IOError("Exp...
[ "Load a libsvm model from a path on disk.\n\n This currently supports:\n * C-SVC\n * NU-SVC\n * Epsilon-SVR\n * NU-SVR\n\n Parameters\n ----------\n model_path: str\n Path on disk where the libsvm model representation is.\n\n Returns\n -------\n model: libsvm_model\n ...
Please provide a description of the function:def add_enumerated_multiarray_shapes(spec, feature_name, shapes): if not isinstance(shapes, list): shapes = [shapes] for shape in shapes: if not isinstance(shape, NeuralNetworkMultiArrayShape): raise Exception( 'Shap...
[ "\n Annotate an input or output multiArray feature in a Neural Network spec to\n to accommodate a list of enumerated array shapes\n\n :param spec: MLModel\n The MLModel spec containing the feature\n\n :param feature_name: str\n The name of the image feature for which to add shape informati...
Please provide a description of the function:def add_enumerated_image_sizes(spec, feature_name, sizes): if not isinstance(sizes, list): sizes = [sizes] for size in sizes: if not isinstance(size, NeuralNetworkImageSize): raise Exception( 'Shape ranges should be o...
[ "\n Annotate an input or output image feature in a Neural Network spec to\n to accommodate a list of enumerated image sizes\n\n :param spec: MLModel\n The MLModel spec containing the feature\n\n :param feature_name: str\n The name of the image feature for which to add size information.\n ...
Please provide a description of the function:def update_image_size_range(spec, feature_name, size_range): if not isinstance(size_range, NeuralNetworkImageSizeRange): raise Exception( 'Shape ranges should be of type NeuralNetworkImageSizeRange') feature = _get_feature(spec, feature_name...
[ "\n Annotate an input or output Image feature in a Neural Network spec to\n to accommodate a range of image sizes\n\n :param spec: MLModel\n The MLModel spec containing the feature\n\n :param feature_name: str\n The name of the Image feature for which to add shape information.\n If ...
Please provide a description of the function:def update_multiarray_shape_range(spec, feature_name, shape_range): if not isinstance(shape_range, NeuralNetworkMultiArrayShapeRange): raise Exception('Shape range should be of type MultiArrayShapeRange') shape_range.validate_array_shape_range() fea...
[ "\n Annotate an input or output MLMultiArray feature in a Neural Network spec\n to accommodate a range of shapes\n\n :param spec: MLModel\n The MLModel spec containing the feature\n\n :param feature_name: str\n The name of the feature for which to add shape range\n information. If t...
Please provide a description of the function:def get_allowed_shape_ranges(spec): shaper = NeuralNetworkShaper(spec, False) inputs = _get_input_names(spec) output = {} for input in inputs: output[input] = shaper.shape(input) return output
[ "\n For a given model specification, returns a dictionary with a shape range object for each input feature name.\n " ]
Please provide a description of the function:def can_allow_multiple_input_shapes(spec): # First, check that the model actually has a neural network in it try: layers = _get_nn_layers(spec) except: raise Exception('Unable to verify that this model contains a neural network.') try: ...
[ "\n Examines a model specification and determines if it can compute results for more than one output shape.\n\n :param spec: MLModel\n The protobuf specification of the model.\n\n :return: Bool\n Returns True if the model can allow multiple input shapes, False otherwise.\n " ]
Please provide a description of the function:def isFlexible(self): for key, value in self.arrayShapeRange.items(): if key in _CONSTRAINED_KEYS: if value.isFlexible: return True return False
[ "\n Returns true if any one of the channel, height, or width ranges of this shape allow more than one input value.\n " ]
Please provide a description of the function:def define_macro(out_f, (name, args, body), undefine=False, check=True): if undefine: out_f.write( '#undef {0}\n' .format(macro_name(name)) ) else: if args: arg_list = '({0})'.format(', '.join(args)) ...
[ "Generate a macro definition or undefinition" ]
Please provide a description of the function:def filename(out_dir, name, undefine=False): if undefine: prefix = 'undef_' else: prefix = '' return os.path.join(out_dir, '{0}{1}.hpp'.format(prefix, name.lower()))
[ "Generate the filename" ]
Please provide a description of the function:def length_limits(max_length_limit, length_limit_step): 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, le...
[ "Generates the length limits" ]
Please provide a description of the function:def generate_take(out_f, steps, line_prefix): 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} : ('...
[ "Generate the take function" ]
Please provide a description of the function:def generate_make_string(out_f, max_step): 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.p...
[ "Generate the make_string template" ]
Please provide a description of the function:def generate_string(out_dir, limits): 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...
[ "Generate string.hpp" ]
Please provide a description of the function:def existing_path(value): if os.path.exists(value): return value else: raise argparse.ArgumentTypeError("Path {0} not found".format(value))
[ "Throws when the path does not exist" ]
Please provide a description of the function:def main(): 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( ...
[ "The main function of the script" ]
Please provide a description of the function:def begin(self): 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 beginning part" ]
Please provide a description of the function:def end(self): for depth in xrange(len(self.names) - 1, -1, -1): self.out_f.write('{0}}}\n'.format(self.prefix(depth)))
[ "Generate the closing part" ]
Please provide a description of the function:def begin(self): 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)
[ "Generate the beginning part" ]
Please provide a description of the function: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, ...
[]
Please provide a description of the function: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 ...
[]
Please provide a description of the function:def _load_version(cls, state, version): from ._audio_feature_extractor import _get_feature_extractor from .._mxnet import _mxnet_utils state['_feature_extractor'] = _get_feature_extractor(state['feature_extractor_name']) # Load the ...
[ "\n A function to load a previously saved SoundClassifier instance.\n " ]
Please provide a description of the function:def classify(self, dataset, verbose=True, batch_size=64): prob_vector = self.predict(dataset, output_type='probability_vector', verbose=verbose, batch_size=batch_size) id_to_label = self._id_to_class_label ...
[ "\n Return the classification for each examples in the ``dataset``.\n The output SFrame contains predicted class labels and its probability.\n\n Parameters\n ----------\n dataset : SFrame | SArray | dict\n The audio data to be classified.\n If dataset is an S...
Please provide a description of the function:def evaluate(self, dataset, metric='auto', verbose=True, batch_size=64): from turicreate.toolkits import evaluation # parameter checking if not isinstance(dataset, _tc.SFrame): raise TypeError('\'dataset\' parameter must be an SF...
[ "\n Evaluate the model by making predictions of target values and comparing\n these to actual values.\n\n Parameters\n ----------\n dataset : SFrame\n Dataset to use for evaluation, must include a column with the same\n name as the features used for model tra...
Please provide a description of the function:def export_coreml(self, filename): import coremltools from coremltools.proto.FeatureTypes_pb2 import ArrayFeatureType from .._mxnet import _mxnet_utils prob_name = self.target + 'Probability' def get_custom_model_spec(): ...
[ "\n Save the model in Core ML format.\n\n See Also\n --------\n save\n\n Examples\n --------\n >>> model.export_coreml('./myModel.mlmodel')\n " ]
Please provide a description of the function:def predict(self, dataset, output_type='class', verbose=True, batch_size=64): from .._mxnet import _mxnet_utils import mxnet as mx if not isinstance(dataset, (_tc.SFrame, _tc.SArray, dict)): raise TypeError('\'dataset\' parameter...
[ "\n Return predictions for ``dataset``. Predictions can be generated\n as class labels or probabilities.\n\n Parameters\n ----------\n dataset : SFrame | SArray | dict\n The audio data to be classified.\n If dataset is an SFrame, it must have a column with th...
Please provide a description of the function:def predict_topk(self, dataset, output_type='probability', k=3, verbose=True, batch_size=64): prob_vector = self.predict(dataset, output_type='probability_vector', verbose=verbose, batch_size=64) id_to_label = self....
[ "\n Return top-k predictions for the ``dataset``.\n Predictions are returned as an SFrame with three columns: `id`,\n `class`, and `probability` or `rank` depending on the ``output_type``\n parameter.\n\n Parameters\n ----------\n dataset : SFrame | SArray | dict\n ...
Please provide a description of the function:def _init_data(data, allow_empty, default_name): 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: ...
[ "Convert data into canonical form." ]
Please provide a description of the function:def provide_data(self): return [(k, tuple([self.batch_size] + list(v.shape[1:]))) for k, v in self.data]
[ "The name and shape of data provided by this iterator" ]
Please provide a description of the function:def provide_label(self): return [(k, tuple([self.batch_size] + list(v.shape[1:]))) for k, v in self.label]
[ "The name and shape of label provided by this iterator" ]
Please provide a description of the function:def reset (): 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_generators, __vst_cached_types...
[ " Clear the module state. This is mainly for testing purposes.\n " ]
Please provide a description of the function:def register (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 will ...
[ " Registers new generator instance 'g'.\n " ]
Please provide a description of the function:def register_standard (id, source_types, target_types, requirements = []): g = Generator (id, False, source_types, target_types, requirements) register (g) return g
[ " Creates new instance of the 'generator' class and registers it.\n Returns the creates instance.\n Rationale: the instance is returned so that it's possible to first register\n a generator and then call 'run' method on that generator, bypassing all\n generator selection.\n " ]
Please provide a description of the function:def override (overrider_id, overridee_id): assert isinstance(overrider_id, basestring) assert isinstance(overridee_id, basestring) __overrides.setdefault(overrider_id, []).append(overridee_id)
[ "Make generator 'overrider-id' be preferred to\n 'overridee-id'. If, when searching for generators\n that could produce a target of certain type,\n both those generators are amoung viable generators,\n the overridden generator is immediately discarded.\n\n The overridden generators are discarded imme...
Please provide a description of the function:def __viable_source_types_real (target_type): assert isinstance(target_type, basestring) generators = [] # 't0' is the initial list of target types we need to process to get a list # of their viable source target types. New target types will not be adde...
[ " Returns a list of source type which can possibly be converted\n to 'target_type' by some chain of generator invocation.\n\n More formally, takes all generators for 'target_type' and\n returns union of source types for those generators and result\n of calling itself recusrively on sourc...
Please provide a description of the function:def viable_source_types (target_type): 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] = __viable_source_types_real (ta...
[ " Helper rule, caches the result of '__viable_source_types_real'.\n " ]
Please provide a description of the function:def viable_source_types_for_generator_real (generator): assert isinstance(generator, Generator) source_types = generator.source_types () if not source_types: # If generator does not specify any source types, # it might be special generator l...
[ " Returns the list of source types, which, when passed to 'run'\n method of 'generator', has some change of being eventually used\n (probably after conversion by other generators)\n " ]
Please provide a description of the function:def viable_source_types_for_generator (generator): assert isinstance(generator, Generator) if generator not in __viable_source_types_cache: __vstg_cached_generators.append(generator) __viable_source_types_cache[generator] = viable_source_types_fo...
[ " Caches the result of 'viable_source_types_for_generator'.\n " ]
Please provide a description of the function:def try_one_generator_really (project, name, generator, target_type, properties, sources): if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(name, basestring) or name is None ...
[ " Returns usage requirements + list of created targets.\n " ]
Please provide a description of the function:def try_one_generator (project, name, generator, target_type, properties, sources): if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(name, basestring) or name is None assert ...
[ " Checks if generator invocation can be pruned, because it's guaranteed\n to fail. If so, quickly returns empty list. Otherwise, calls\n try_one_generator_really.\n " ]
Please provide a description of the function:def __ensure_type (targets): 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))
[ " Ensures all 'targets' have types. If this is not so, exists with\n error.\n " ]
Please provide a description of the function:def find_viable_generators_aux (target_type, prop_set): assert isinstance(target_type, basestring) assert isinstance(prop_set, property_set.PropertySet) # Select generators that can create the required target type. viable_generators = [] initial_gene...
[ " Returns generators which can be used to construct target of specified type\n with specified properties. Uses the following algorithm:\n - iterates over requested target_type and all it's bases (in the order returned bt\n type.all-bases.\n - for each type find all generators that gene...
Please provide a description of the function:def __construct_really (project, name, target_type, prop_set, sources): if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(name, basestring) or name is None assert isinstance(t...
[ " Attempts to construct target by finding viable generators, running them\n and selecting the dependency graph.\n " ]
Please provide a description of the function:def construct (project, name, target_type, prop_set, sources, top_level=False): if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) assert isinstance(name, basestring) or name is None assert isin...
[ " Attempts to create target of 'target-type' with 'properties'\n from 'sources'. The 'sources' are treated as a collection of\n *possible* ingridients -- i.e. it is not required to consume\n them all. If 'multiple' is true, the rule is allowed to return\n several targets of 'target-type'...
Please provide a description of the function:def clone (self, new_id, new_toolset_properties): assert isinstance(new_id, basestring) assert is_iterable_typed(new_toolset_properties, basestring) return self.__class__ (new_id, self.composing_, ...
[ " Returns another generator which differers from $(self) in\n - id\n - value to <toolset> feature in properties\n " ]
Please provide a description of the function:def clone_and_change_target_type(self, base, type): assert isinstance(base, basestring) assert isinstance(type, basestring) target_types = [] for t in self.target_types_and_names_: m = _re_match_type.match(t) a...
[ "Creates another generator that is the same as $(self), except that\n if 'base' is in target types of $(self), 'type' will in target types\n of the new generator." ]
Please provide a description of the function:def match_rank (self, ps): # 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 the # feature. assert isinstance(ps, pro...
[ " Returns true if the generator can be run with the specified\n properties.\n " ]
Please provide a description of the function:def run (self, project, name, prop_set, sources): if __debug__: from .targets import ProjectTarget assert isinstance(project, ProjectTarget) # intermediary targets don't have names, so None is possible assert i...
[ " Tries to invoke this generator on the given sources. Returns a\n list of generated targets (instances of 'virtual-target').\n\n project: Project for which the targets are generated.\n\n name: Determines the name of 'name' attribute for\n ...
Please provide a description of the function:def construct_result (self, consumed, project, name, prop_set): if __debug__: from .targets import ProjectTarget assert is_iterable_typed(consumed, virtual_target.VirtualTarget) assert isinstance(project, ProjectTarget) ...
[ " Constructs the dependency graph that will be returned by this\n generator.\n consumed: Already prepared list of consumable targets\n If generator requires several source files will contain\n exactly len $(self.source_...
Please provide a description of the function:def determine_output_name(self, sources): assert is_iterable_typed(sources, virtual_target.VirtualTarget) # The simple case if when a name # of source has single dot. Then, we take the part before # dot. Several dots can be caused by...
[ "Determine the name of the produced target from the\n names of the sources." ]
Please provide a description of the function:def generated_targets (self, sources, prop_set, project, name): if __debug__: from .targets import ProjectTarget assert is_iterable_typed(sources, virtual_target.VirtualTarget) assert isinstance(prop_set, property_set.Prop...
[ " Constructs targets that are created after consuming 'sources'.\n The result will be the list of virtual-target, which the same length\n as 'target_types' attribute and with corresponding types.\n\n When 'name' is empty, all source targets must have the same value of\n t...
Please provide a description of the function:def convert_to_consumable_types (self, project, name, prop_set, sources, only_one=False): if __debug__: from .targets import ProjectTarget assert isinstance(name, basestring) or name is None assert isinstance(project, Proj...
[ " Attempts to convert 'source' to the types that this generator can\n handle. The intention is to produce the set of targets can should be\n used when generator is run.\n only_one: convert 'source' to only one of source types\n if there's more that one possi...