Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def main_target_usage_requirements (self, specification, project): assert is_iterable_typed(specification, basestring) assert isinstance(project, ProjectTarget) project_usage_requirements = project.get ('usage-requirements') # We don...
[ " Returns the use requirement to use when declaraing a main target,\n which are obtained by\n - translating all specified property paths, and\n - adding project's usage requirements\n specification: Use-properties explicitly specified for a main target\n proje...
Please provide a description of the function:def main_target_default_build (self, specification, project): assert is_iterable_typed(specification, basestring) assert isinstance(project, ProjectTarget) if specification: return property_set.create_with_validation(specification...
[ " Return the default build value to use when declaring a main target,\n which is obtained by using specified value if not empty and parent's\n default build attribute otherwise.\n specification: Default build explicitly specified for a main target\n project: Proje...
Please provide a description of the function:def start_building (self, main_target_instance): assert isinstance(main_target_instance, MainTarget) if id(main_target_instance) in self.targets_being_built_: names = [] for t in self.targets_being_built_.values() + [main_targ...
[ " Helper rules to detect cycles in main target references.\n " ]
Please provide a description of the function:def create_typed_target (self, type, project, name, sources, requirements, default_build, usage_requirements): assert isinstance(type, basestring) assert isinstance(project, ProjectTarget) assert is_iterable_typed(sources, basestring) ...
[ " Creates a TypedTarget with the specified properties.\n The 'name', 'sources', 'requirements', 'default_build' and\n 'usage_requirements' are assumed to be in the form specified\n by the user in Jamfile corresponding to 'project'.\n " ]
Please provide a description of the function:def generate (self, ps): assert isinstance(ps, property_set.PropertySet) self.manager_.targets().log( "Building project '%s' with '%s'" % (self.name (), str(ps))) self.manager_.targets().increase_indent () result = Genera...
[ " Generates all possible targets contained in this project.\n " ]
Please provide a description of the function:def targets_to_build (self): result = [] if not self.built_main_targets_: self.build_main_targets () # Collect all main targets here, except for "explicit" ones. for n, t in self.main_target_.iteritems (): i...
[ " Computes and returns a list of AbstractTarget instances which\n must be built when this project is built.\n " ]
Please provide a description of the function:def mark_targets_as_explicit (self, target_names): # Record the name of the target, not instance, since this # rule is called before main target instaces are created. assert is_iterable_typed(target_names, basestring) self.explicit_t...
[ "Add 'target' to the list of targets in this project\n that should be build only by explicit request." ]
Please provide a description of the function:def add_alternative (self, target_instance): assert isinstance(target_instance, AbstractTarget) if self.built_main_targets_: raise IllegalOperation ("add-alternative called when main targets are already created for project '%s'" % self.fu...
[ " Add new target alternative.\n " ]
Please provide a description of the function:def has_main_target (self, name): assert isinstance(name, basestring) if not self.built_main_targets_: self.build_main_targets() return name in self.main_target_
[ "Tells if a main target with the specified name exists." ]
Please provide a description of the function:def create_main_target (self, name): assert isinstance(name, basestring) if not self.built_main_targets_: self.build_main_targets () return self.main_targets_.get (name, None)
[ " Returns a 'MainTarget' class instance corresponding to the 'name'.\n " ]
Please provide a description of the function:def find_really(self, id): assert isinstance(id, basestring) result = None current_location = self.get ('location') __re_split_project_target = re.compile (r'(.*)//(.*)') split = __re_split_project_target.match (id) ...
[ " Find and return the target with the specified id, treated\n relative to self.\n " ]
Please provide a description of the function:def add_constant(self, name, value, path=0): assert isinstance(name, basestring) assert is_iterable_typed(value, basestring) assert isinstance(path, int) # will also match bools if path: l = self.location_ if ...
[ "Adds a new constant for this project.\n\n The constant will be available for use in Jamfile\n module for this project. If 'path' is true,\n the constant will be interpreted relatively\n to the location of project.\n " ]
Please provide a description of the function:def add_alternative (self, target): assert isinstance(target, BasicTarget) d = target.default_build () if self.alternatives_ and self.default_build_ != d: get_manager().errors()("default build must be identical in all alternative...
[ " Add a new alternative for this target.\n " ]
Please provide a description of the function:def __select_alternatives (self, property_set_, debug): # When selecting alternatives we have to consider defaults, # for example: # lib l : l.cpp : <variant>debug ; # lib l : l_opt.cpp : <variant>release ; # won't work ...
[ " Returns the best viable alternative for this property_set\n See the documentation for selection rules.\n # TODO: shouldn't this be 'alternative' (singular)?\n " ]
Please provide a description of the function:def generate (self, ps): assert isinstance(ps, property_set.PropertySet) self.manager_.targets ().start_building (self) # We want composite properties in build request act as if # all the properties it expands too are explicitly spec...
[ " Select an alternative for this main target, by finding all alternatives\n which requirements are satisfied by 'properties' and picking the one with\n longest requirements set.\n Returns the result of calling 'generate' on that alternative.\n " ]
Please provide a description of the function:def __generate_really (self, prop_set): assert isinstance(prop_set, property_set.PropertySet) best_alternative = self.__select_alternatives (prop_set, debug=0) self.best_alternative = best_alternative if not best_alternative: ...
[ " Generates the main target with the given property set\n and returns a list which first element is property_set object\n containing usage_requirements of generated target and with\n generated virtual target in other elements. It's possible\n that no targets are generated...
Please provide a description of the function:def sources (self): if self.source_targets_ == None: self.source_targets_ = [] for s in self.sources_: self.source_targets_.append(resolve_reference(s, self.project_)[0]) return self.source_targets_
[ " Returns the list of AbstractTargets which are used as sources.\n The extra properties specified for sources are not represented.\n The only used of this rule at the moment is the '--dump-tests'\n feature of the test system.\n " ]
Please provide a description of the function:def common_properties (self, build_request, requirements): # For optimization, we add free unconditional requirements directly, # without using complex algorithsm. # This gives the complex algorithm better chance of caching results. #...
[ " Given build request and requirements, return properties\n common to dependency build request and target build\n properties.\n " ]
Please provide a description of the function:def match (self, property_set_, debug): # The condition is composed of all base non-conditional properties. # It's not clear if we should expand 'self.requirements_' or not. # For one thing, it would be nice to be able to put # <to...
[ " Returns the alternative condition for this alternative, if\n the condition is satisfied by 'property_set'.\n " ]
Please provide a description of the function:def generate_dependency_properties(self, properties, ps): assert is_iterable_typed(properties, property.Property) assert isinstance(ps, property_set.PropertySet) result_properties = [] usage_requirements = [] for p in properti...
[ " Takes a target reference, which might be either target id\n or a dependency property, and generates that target using\n 'property_set' as build request.\n\n Returns a tuple (result, usage_requirements).\n " ]
Please provide a description of the function:def generate (self, ps): assert isinstance(ps, property_set.PropertySet) self.manager_.errors().push_user_context( "Generating target " + self.full_name(), self.user_context_) if self.manager().targets().logging(): se...
[ " Determines final build properties, generates sources,\n and calls 'construct'. This method should not be\n overridden.\n " ]
Please provide a description of the function:def compute_usage_requirements (self, subvariant): assert isinstance(subvariant, virtual_target.Subvariant) rproperties = subvariant.build_properties () xusage_requirements =self.evaluate_requirements( self.usage_requirements_, rp...
[ " Given the set of generated targets, and refined build\n properties, determines and sets appripriate usage requirements\n on those targets.\n " ]
Please provide a description of the function:def create_subvariant (self, root_targets, all_targets, build_request, sources, rproperties, usage_requirements): assert is_iterable_typed(root_targets, virtual_target.VirtualTarget) assert is_ite...
[ "Creates a new subvariant-dg instances for 'targets'\n - 'root-targets' the virtual targets will be returned to dependents\n - 'all-targets' all virtual\n targets created while building this main target\n - 'build-request' is property-set instance with\n requested build ...
Please provide a description of the function:def variant (name, parents_or_properties, explicit_properties = []): parents = [] if not explicit_properties: explicit_properties = parents_or_properties else: parents = parents_or_properties inherited = property_set.empty() if paren...
[ " Declares a new variant.\n First determines explicit properties for this variant, by\n refining parents' explicit properties with the passed explicit\n properties. The result is remembered and will be used if\n this variant is used as parent.\n\n Second, determines the full prope...
Please provide a description of the function:def register_globals (): # This feature is used to determine which OS we're on. # In future, this may become <target-os> and <host-os> # TODO: check this. Compatibility with bjam names? Subfeature for version? os = sys.platform feature.feature ('os'...
[ " Registers all features and variants declared by this module.\n " ]
Please provide a description of the function:def lib(names, sources=[], requirements=[], default_build=[], usage_requirements=[]): assert is_iterable_typed(names, basestring) assert is_iterable_typed(sources, basestring) assert is_iterable_typed(requirements, basestring) assert is_iterable_typed(de...
[ "The implementation of the 'lib' rule. Beyond standard syntax that rule allows\n simplified: 'lib a b c ;'." ]
Please provide a description of the function:def adjust_properties (self, prop_set): assert isinstance(prop_set, property_set.PropertySet) s = self.targets () [0].creating_subvariant () return prop_set.add_raw (s.implicit_includes ('include', 'H'))
[ " For all virtual targets for the same dependency graph as self,\n i.e. which belong to the same main target, add their directories\n to include path.\n " ]
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, random_seed=0, verbose=True): from turicreate._cython.cy_server import QuietProgress opts = {} model_...
[ "\n Create a model that makes recommendations using item popularity. When no\n target column is provided, the popularity is determined by the number of\n observations involving each item. When a target is provided, popularity\n is computed using the item's mean target value. When the target column\n ...
Please provide a description of the function:def get_params(self, deep=False): params = super(XGBModel, self).get_params(deep=deep) if params['missing'] is np.nan: params['missing'] = None # sklearn doesn't handle nan. see #4725 if not params.get('eval_metric', True): ...
[ "Get parameter.s" ]
Please provide a description of the function:def get_xgb_params(self): xgb_params = self.get_params() xgb_params['silent'] = 1 if self.silent else 0 if self.nthread <= 0: xgb_params.pop('nthread', None) return xgb_params
[ "Get xgboost type parameters." ]
Please provide a description of the function:def fit(self, X, y, eval_set=None, eval_metric=None, early_stopping_rounds=None, verbose=True): # pylint: disable=missing-docstring,invalid-name,attribute-defined-outside-init trainDmatrix = DMatrix(X, label=y, missing=self.missing) ...
[ "\n Fit the gradient boosting model\n\n Parameters\n ----------\n X : array_like\n Feature matrix\n y : array_like\n Labels\n eval_set : list, optional\n A list of (X, y) tuple pairs to use as a validation set for\n early-stopping...
Please provide a description of the function:def fit(self, X, y, sample_weight=None, eval_set=None, eval_metric=None, early_stopping_rounds=None, verbose=True): # pylint: disable = attribute-defined-outside-init,arguments-differ evals_result = {} self.classes_ = list(np.uniq...
[ "\n Fit gradient boosting classifier\n\n Parameters\n ----------\n X : array_like\n Feature matrix\n y : array_like\n Labels\n sample_weight : array_like\n Weight for each instance\n eval_set : list, optional\n A list of (X...
Please provide a description of the function:def add_grist (features): assert is_iterable_typed(features, basestring) or isinstance(features, basestring) def grist_one (feature): if feature [0] != '<' and feature [len (feature) - 1] != '>': return '<' + feature + '>' else: ...
[ " Transform a string by bracketing it with \"<>\". If already bracketed, does nothing.\n features: one string or a sequence of strings\n return: the gristed string, if features is a string, or a sequence of gristed strings, if features is a sequence\n " ]
Please provide a description of the function:def replace_grist (features, new_grist): assert is_iterable_typed(features, basestring) or isinstance(features, basestring) assert isinstance(new_grist, basestring) # this function is used a lot in the build phase and the original implementation # was ex...
[ " Replaces the grist of a string by a new one.\n Returns the string with the new grist.\n " ]
Please provide a description of the function:def get_value (property): assert is_iterable_typed(property, basestring) or isinstance(property, basestring) return replace_grist (property, '')
[ " Gets the value of a property, that is, the part following the grist, if any.\n " ]
Please provide a description of the function:def get_grist (value): assert is_iterable_typed(value, basestring) or isinstance(value, basestring) def get_grist_one (name): split = __re_grist_and_value.match (name) if not split: return '' else: return split.gro...
[ " Returns the grist of a string.\n If value is a sequence, does it for every value and returns the result as a sequence.\n " ]
Please provide a description of the function:def ungrist (value): assert is_iterable_typed(value, basestring) or isinstance(value, basestring) def ungrist_one (value): stripped = __re_grist_content.match (value) if not stripped: raise BaseException ("in ungrist: '%s' is not of t...
[ " Returns the value without grist.\n If value is a sequence, does it for every value and returns the result as a sequence.\n " ]
Please provide a description of the function:def replace_suffix (name, new_suffix): assert isinstance(name, basestring) assert isinstance(new_suffix, basestring) split = os.path.splitext (name) return split [0] + new_suffix
[ " Replaces the suffix of name by new_suffix.\n If no suffix exists, the new one is added.\n " ]
Please provide a description of the function:def split_action_id (id): assert isinstance(id, basestring) split = id.split ('.', 1) toolset = split [0] name = '' if len (split) > 1: name = split [1] return (toolset, name)
[ " Splits an id in the toolset and specific rule parts. E.g.\n 'gcc.compile.c++' returns ('gcc', 'compile.c++')\n " ]
Please provide a description of the function:def on_windows (): if bjam.variable("NT"): return True elif bjam.variable("UNIX"): uname = bjam.variable("JAMUNAME") if uname and uname[0].startswith("CYGWIN"): return True return False
[ " Returns true if running on windows, whether in cygwin or not.\n " ]
Please provide a description of the function:def _validate_dataset(dataset): if not (isinstance(dataset, _SFrame)): raise TypeError("Input 'dataset' must be an SFrame.") if dataset.num_rows() == 0 or dataset.num_columns() == 0: raise ValueError("Input 'dataset' has no data.")
[ "\n Validate the main Kmeans dataset.\n\n Parameters\n ----------\n dataset: SFrame\n Input dataset.\n " ]
Please provide a description of the function:def _validate_initial_centers(initial_centers): if not (isinstance(initial_centers, _SFrame)): raise TypeError("Input 'initial_centers' must be an SFrame.") if initial_centers.num_rows() == 0 or initial_centers.num_columns() == 0: raise ValueErr...
[ "\n Validate the initial centers.\n\n Parameters\n ----------\n initial_centers : SFrame\n Initial cluster center locations, in SFrame form.\n " ]
Please provide a description of the function:def _validate_num_clusters(num_clusters, initial_centers, num_rows): ## Basic validation if num_clusters is not None and not isinstance(num_clusters, int): raise _ToolkitError("Parameter 'num_clusters' must be an integer.") ## Determine the correct...
[ "\n Validate the combination of the `num_clusters` and `initial_centers`\n parameters in the Kmeans model create function. If the combination is\n valid, determine and return the correct number of clusters.\n\n Parameters\n ----------\n num_clusters : int\n Specified number of clusters.\n\n...
Please provide a description of the function:def _validate_features(features, column_type_map, valid_types, label): if not isinstance(features, list): raise TypeError("Input 'features' must be a list, if specified.") if len(features) == 0: raise ValueError("If specified, input 'features' m...
[ "\n Identify the subset of desired `features` that are valid for the Kmeans\n model. A warning is emitted for each feature that is excluded.\n\n Parameters\n ----------\n features : list[str]\n Desired feature names.\n\n column_type_map : dict[str, type]\n Dictionary mapping each col...
Please provide a description of the function:def create(dataset, num_clusters=None, features=None, label=None, initial_centers=None, max_iterations=10, batch_size=None, verbose=True): opts = {'model_name': 'kmeans', 'max_iterations': max_iterations, } ## Valid...
[ "\n Create a k-means clustering model. The KmeansModel object contains the\n computed cluster centers and the cluster assignment for each instance in\n the input 'dataset'.\n\n Given a number of clusters, k-means iteratively chooses the best cluster\n centers and assigns nearby points to the best clu...
Please provide a description of the function:def predict(self, dataset, output_type='cluster_id', verbose=True): ## Validate the input dataset. _tkutl._raise_error_if_not_sframe(dataset, "dataset") _tkutl._raise_error_if_sframe_empty(dataset, "dataset") ## Validate the output ...
[ "\n Return predicted cluster label for instances in the new 'dataset'.\n K-means predictions are made by assigning each new instance to the\n closest cluster center.\n\n Parameters\n ----------\n dataset : SFrame\n Dataset of new observations. Must include the fe...
Please provide a description of the function:def _get(self, field): opts = {'model': self.__proxy__, 'model_name': self.__name__, 'field': field} response = _tc.extensions._kmeans.get_value(opts) return response['value']
[ "\n Return the value of a given field.\n\n +-----------------------+----------------------------------------------+\n | Field | Description |\n +=======================+==============================================+\n | batch_size ...
Please provide a description of the function:def count_words(text, to_lower=True, delimiters=DEFAULT_DELIMITERS): _raise_error_if_not_sarray(text, "text") ## Compute word counts sf = _turicreate.SFrame({'docs': text}) fe = _feature_engineering.WordCounter(features='docs', ...
[ "\n If `text` is an SArray of strings or an SArray of lists of strings, the\n occurances of word are counted for each row in the SArray.\n\n If `text` is an SArray of dictionaries, the keys are tokenized and the\n values are the counts. Counts for the same word, in the same row, are\n added together....
Please provide a description of the function:def count_ngrams(text, n=2, method="word", to_lower=True, delimiters=DEFAULT_DELIMITERS, ignore_punct=True, ignore_space=True): _raise_error_if_not_sarray(text, "text") # Compute ngrams counts sf = _turicreate.SFrame({'doc...
[ "\n Return an SArray of ``dict`` type where each element contains the count\n for each of the n-grams that appear in the corresponding input element.\n The n-grams can be specified to be either character n-grams or word\n n-grams. The input SArray could contain strings, dicts with string keys\n and ...
Please provide a description of the function:def tf_idf(text): _raise_error_if_not_sarray(text, "text") if len(text) == 0: return _turicreate.SArray() dataset = _turicreate.SFrame({'docs': text}) scores = _feature_engineering.TFIDF('docs').fit_transform(dataset) return scores['docs']
[ "\n Compute the TF-IDF scores for each word in each document. The collection\n of documents must be in bag-of-words format.\n\n .. math::\n \\mbox{TF-IDF}(w, d) = tf(w, d) * log(N / f(w))\n\n where :math:`tf(w, d)` is the number of times word :math:`w` appeared in\n document :math:`d`, :math:`...
Please provide a description of the function:def drop_words(text, threshold=2, to_lower=True, delimiters=DEFAULT_DELIMITERS, stop_words=None): ''' Remove words that occur below a certain number of times in an SArray. This is a common method of cleaning text before it is used, and can increase...
[]
Please provide a description of the function:def tokenize(text, to_lower=False, delimiters=DEFAULT_DELIMITERS): _raise_error_if_not_sarray(text, "text") ## Compute word counts sf = _turicreate.SFrame({'docs': text}) fe = _feature_engineering.Tokenizer(features='docs', ...
[ "\n Tokenize the input SArray of text strings and return the list of tokens.\n\n Parameters\n ----------\n text : SArray[str]\n Input data of strings representing English text. This tokenizer is not\n intended to process XML, HTML, or other structured text formats.\n\n to_lower : bool, ...
Please provide a description of the function:def bm25(dataset, query, k1=1.5, b=.75): if type(dataset) != _turicreate.SArray: raise TypeError('bm25 requires an SArray of dict, list, or str type'+\ ', where each dictionary whose keys are words and whose values' + \ ' are word fr...
[ "\n For a given query and set of documents, compute the BM25 score for each\n document. If we have a query with words q_1, ..., q_n the BM25 score for\n a document is:\n\n .. math:: \\sum_{i=1}^N IDF(q_i)\\\\frac{f(q_i) * (k_1+1)}{f(q_i) + k_1 * (1-b+b*|D|/d_avg))}\n\n where\n\n * :math:`\\mbo...
Please provide a description of the function:def parse_sparse(filename, vocab_filename): vocab = _turicreate.SFrame.read_csv(vocab_filename, header=None)['X1'] vocab = list(vocab) docs = _turicreate.SFrame.read_csv(filename, header=None) # Remove first word docs = docs['X1'].apply(lambda x: x...
[ "\n Parse a file that's in libSVM format. In libSVM format each line of the text\n file represents a document in bag of words format:\n\n num_unique_words_in_doc word_id:count another_id:count\n\n The word_ids have 0-based indexing, i.e. 0 corresponds to the first\n word in the vocab filename.\n\n ...
Please provide a description of the function:def parse_docword(filename, vocab_filename): vocab = _turicreate.SFrame.read_csv(vocab_filename, header=None)['X1'] vocab = list(vocab) sf = _turicreate.SFrame.read_csv(filename, header=False) sf = sf[3:] sf['X2'] = sf['X1'].apply(lambda x: [int(z) ...
[ "\n Parse a file that's in \"docword\" format. This consists of a 3-line header\n comprised of the document count, the vocabulary count, and the number of\n tokens, i.e. unique (doc_id, word_id) pairs. After the header, each line\n contains a space-separated triple of (doc_id, word_id, frequency), where...
Please provide a description of the function:def random_split(dataset, prob=.5): def grab_values(x, train=True): if train: ix = 0 else: ix = 1 return dict([(key, value[ix]) for key, value in six.iteritems(x) \ if value[ix] != 0]) def wor...
[ "\n Utility for performing a random split for text data that is already in\n bag-of-words format. For each (word, count) pair in a particular element,\n the counts are uniformly partitioned in either a training set or a test\n set.\n\n Parameters\n ----------\n dataset : SArray of type dict, SF...
Please provide a description of the function:def train(params, dtrain, num_boost_round=10, evals=(), obj=None, feval=None, maximize=False, early_stopping_rounds=None, evals_result=None, verbose_eval=True, learning_rates=None, xgb_model=None): # pylint: disable=too-many-statements,too-many-branch...
[ "Train a booster with given parameters.\n\n Parameters\n ----------\n params : dict\n Booster params.\n dtrain : DMatrix\n Data to be trained.\n num_boost_round: int\n Number of boosting iterations.\n watchlist (evals): list of pairs (DMatrix, string)\n List of items to...
Please provide a description of the function:def mknfold(dall, nfold, param, seed, evals=(), fpreproc=None): evals = list(evals) np.random.seed(seed) randidx = np.random.permutation(dall.num_row()) kstep = len(randidx) / nfold idset = [randidx[(i * kstep): min(len(randidx), (i + 1) * kstep)] fo...
[ "\n Make an n-fold list of CVPack from random indices.\n " ]
Please provide a description of the function:def aggcv(rlist, show_stdv=True, show_progress=None, as_pandas=True): # pylint: disable=invalid-name cvmap = {} idx = rlist[0].split()[0] for line in rlist: arr = line.split() assert idx == arr[0] for it in arr[1:]: if...
[ "\n Aggregate cross-validation results.\n " ]
Please provide a description of the function:def cv(params, dtrain, num_boost_round=10, nfold=3, metrics=(), obj=None, feval=None, fpreproc=None, as_pandas=True, show_progress=None, show_stdv=True, seed=0): # pylint: disable = invalid-name results = [] cvfolds = mknfold(dtrain, nfold, par...
[ "Cross-validation with given paramaters.\n\n Parameters\n ----------\n params : dict\n Booster params.\n dtrain : DMatrix\n Data to be trained.\n num_boost_round : int\n Number of boosting iterations.\n nfold : int\n Number of folds in CV.\n metrics : list of strings...
Please provide a description of the function:def create(dataset, target, feature=None, model = 'resnet-50', l2_penalty=0.01, l1_penalty=0.0, solver='auto', feature_rescaling=True, convergence_threshold = _DEFAULT_SOLVER_OPTIONS['convergence_threshold'], step_size = _DEFAULT_SOLVER_OPTIONS['step_siz...
[ "\n Create a :class:`ImageClassifier` model.\n\n Parameters\n ----------\n dataset : SFrame\n Input data. The column named by the 'feature' parameter will be\n extracted for modeling.\n\n target : string, or int\n Name of the column containing the target variable. The values in t...
Please provide a description of the function:def _get_native_state(self): state = self.__proxy__.get_state() state['classifier'] = state['classifier'].__proxy__ del state['feature_extractor'] del state['classes'] return state
[ "\n Save the model as a dictionary, which can be loaded with the\n :py:func:`~turicreate.load_model` method.\n " ]
Please provide a description of the function:def _load_version(cls, state, version): _tkutl._model_version_check(version, cls._PYTHON_IMAGE_CLASSIFIER_VERSION) from turicreate.toolkits.classifier.logistic_classifier import LogisticClassifier state['classifier'] = LogisticClassifier(stat...
[ "\n A function to load a previously saved ImageClassifier\n instance.\n " ]
Please provide a description of the function:def predict(self, dataset, output_type='class', batch_size=64): if not isinstance(dataset, (_tc.SFrame, _tc.SArray, _tc.Image)): raise TypeError('dataset must be either an SFrame, SArray or turicreate.Image') if(batch_size < 1): ...
[ "\n Return predictions for ``dataset``, using the trained logistic\n regression model. Predictions can be generated as class labels,\n probabilities that the target value is True, or margins (i.e. the\n distance of the observations from the hyperplane separating the\n classes). `p...
Please provide a description of the function:def predict_topk(self, dataset, output_type="probability", k=3, batch_size=64): if not isinstance(dataset, (_tc.SFrame, _tc.SArray, _tc.Image)): raise TypeError('dataset must be either an SFrame, SArray or turicreate.Image') if(batch_size...
[ "\n Return top-k predictions for the ``dataset``, using the trained model.\n Predictions are returned as an SFrame with three columns: `id`,\n `class`, and `probability`, `margin`, or `rank`, depending on the ``output_type``\n parameter. Input dataset size must be the same as for traini...
Please provide a description of the function:def evaluate(self, dataset, metric='auto', verbose=True, batch_size=64): import os, json, math if(batch_size < 1): raise ValueError("'batch_size' must be greater than or equal to 1") extracted_features = self._extract_features(...
[ "\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 of new observations. Must include columns with the same\n names as the target and features used for ...
Please provide a description of the function:def export_coreml(self, filename): import coremltools # First define three internal helper functions # Internal helper function def _create_vision_feature_print_scene(): prob_name = self.target + 'Probability' ...
[ "\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 make_input_layers(self): self.input_layers = [] in_nodes = self.model._inbound_nodes if hasattr( self.model,'_inbound_nodes') else self.model.inbound_nodes if hasattr(self.model, 'input_layers'): input_keras_la...
[ "\n Extract the ordering of the input layers.\n " ]
Please provide a description of the function:def make_output_layers(self): self.output_layers = [] # import pytest; pytest.set_trace() if hasattr(self.model, 'output_layers'): # find corresponding output layers in CoreML model # assume output layers are not share...
[ "\n Extract the ordering of output layers.\n " ]
Please provide a description of the function:def _remove_layer_and_reconnect(self, layer): successors = self.get_successors(layer) predecessors = self.get_predecessors(layer) # remove layer's edges for succ in successors: self._remove_edge(layer, succ) for pr...
[ " Remove the layer, and reconnect each of its predecessor to each of\n its successor\n " ]
Please provide a description of the function:def defuse_activation(self): idx, nb_layers = 0, len(self.layer_list) while idx < nb_layers: layer = self.layer_list[idx] k_layer = self.keras_layer_map[layer] if (isinstance(k_layer, _keras.layers.TimeDistributed)...
[ " Defuse the fused activation layers in the network.\n " ]
Please provide a description of the function:def date_range(cls,start_time,end_time,freq): ''' Returns a new SArray that represents a fixed frequency datetime index. Parameters ---------- start_time : datetime.datetime Left bound for generating dates. end_time...
[]
Please provide a description of the function:def from_const(cls, value, size, dtype=type(None)): assert isinstance(size, (int, long)) and size >= 0, "size must be a positive int" if not isinstance(value, (type(None), int, float, str, array.array, list, dict, datetime.datetime)): rai...
[ "\n Constructs an SArray of size with a const value.\n\n Parameters\n ----------\n value : [int | float | str | array.array | list | dict | datetime]\n The value to fill the SArray\n size : int\n The size of the SArray\n dtype : type\n The type of...
Please provide a description of the function:def from_sequence(cls, *args): start = None stop = None # fill with args. This checks for from_sequence(100), from_sequence(10,100) if len(args) == 1: stop = args[0] elif len(args) == 2: start = args[0]...
[ "\n from_sequence(start=0, stop)\n\n Create an SArray from sequence\n\n .. sourcecode:: python\n\n Construct an SArray of integer values from 0 to 999\n\n >>> tc.SArray.from_sequence(1000)\n\n This is equivalent, but more efficient than:\n\n >>> tc.SA...
Please provide a description of the function:def read_json(cls, filename): proxy = UnitySArrayProxy() proxy.load_from_json_record_files(_make_internal_url(filename)) return cls(_proxy = proxy)
[ "\n Construct an SArray from a json file or glob of json files.\n The json file must contain a list of dictionaries. The returned\n SArray type will be of dict type\n\n Parameters\n ----------\n filename : str\n The filename or glob to load into an SArray.\n\n ...
Please provide a description of the function:def where(cls, condition, istrue, isfalse, dtype=None): true_is_sarray = isinstance(istrue, SArray) false_is_sarray = isinstance(isfalse, SArray) if not true_is_sarray and false_is_sarray: istrue = cls(_proxy=condition.__proxy__.t...
[ "\n Selects elements from either istrue or isfalse depending on the value\n of the condition SArray.\n\n Parameters\n ----------\n condition : SArray\n An SArray of values such that for each value, if non-zero, yields a\n value from istrue, otherwise from isfalse.\n\...
Please provide a description of the function:def save(self, filename, format=None): from .sframe import SFrame as _SFrame if format is None: if filename.endswith(('.csv', '.csv.gz', 'txt')): format = 'text' else: format = 'binary' ...
[ "\n Saves the SArray to file.\n\n The saved SArray will be in a directory named with the `targetfile`\n parameter.\n\n Parameters\n ----------\n filename : string\n A local path or a remote URL. If format is 'text', it will be\n saved as a text file. ...
Please provide a description of the function:def vector_slice(self, start, end=None): if (self.dtype != array.array) and (self.dtype != list): raise RuntimeError("Only Vector type can be sliced") if end is None: end = start + 1 with cython_context(): ...
[ "\n If this SArray contains vectors or lists, this returns a new SArray\n containing each individual element sliced, between start and\n end (exclusive).\n\n Parameters\n ----------\n start : int\n The start position of the slice.\n\n end : int, optional.\...
Please provide a description of the function:def element_slice(self, start=None, stop=None, step=None): if self.dtype not in [str, array.array, list]: raise TypeError("SArray must contain strings, arrays or lists") with cython_context(): return SArray(_proxy=self.__proxy...
[ "\n This returns an SArray with each element sliced accordingly to the\n slice specified. This is conceptually equivalent to:\n\n >>> g.apply(lambda x: x[start:step:stop])\n\n The SArray must be of type list, vector, or string.\n\n For instance:\n\n >>> g = SArray([\"abcdef...
Please provide a description of the function:def _count_words(self, to_lower=True, delimiters=["\r", "\v", "\n", "\f", "\t", " "]): if (self.dtype != str): raise TypeError("Only SArray of string type is supported for counting bag of words") if (not all([len(delim) == 1 for delim i...
[ "\n This returns an SArray with, for each input string, a dict from the unique,\n delimited substrings to their number of occurrences within the original\n string.\n\n The SArray must be of type string.\n\n ..WARNING:: This function is deprecated, and will be removed in future\n ...
Please provide a description of the function:def _count_ngrams(self, n=2, method="word", to_lower=True, ignore_space=True): if (self.dtype != str): raise TypeError("Only SArray of string type is supported for counting n-grams") if (type(n) != int): raise TypeError("Inpu...
[ "\n For documentation, see turicreate.text_analytics.count_ngrams().\n\n ..WARNING:: This function is deprecated, and will be removed in future\n versions of Turi Create. Please use the `text_analytics.count_words`\n function instead.\n " ]
Please provide a description of the function:def dict_trim_by_keys(self, keys, exclude=True): if not _is_non_string_iterable(keys): keys = [keys] with cython_context(): return SArray(_proxy=self.__proxy__.dict_trim_by_keys(keys, exclude))
[ "\n Filter an SArray of dictionary type by the given keys. By default, all\n keys that are in the provided list in ``keys`` are *excluded* from the\n returned SArray.\n\n Parameters\n ----------\n keys : list\n A collection of keys to trim down the elements in th...
Please provide a description of the function:def dict_trim_by_values(self, lower=None, upper=None): if not (lower is None or isinstance(lower, numbers.Number)): raise TypeError("lower bound has to be a numeric value") if not (upper is None or isinstance(upper, numbers.Number)): ...
[ "\n Filter dictionary values to a given range (inclusive). Trimming is only\n performed on values which can be compared to the bound values. Fails on\n SArrays whose data type is not ``dict``.\n\n Parameters\n ----------\n lower : int or long or float, optional\n ...
Please provide a description of the function:def dict_has_any_keys(self, keys): if not _is_non_string_iterable(keys): keys = [keys] with cython_context(): return SArray(_proxy=self.__proxy__.dict_has_any_keys(keys))
[ "\n Create a boolean SArray by checking the keys of an SArray of\n dictionaries. An element of the output SArray is True if the\n corresponding input element's dictionary has any of the given keys.\n Fails on SArrays whose data type is not ``dict``.\n\n Parameters\n -------...
Please provide a description of the function:def dict_has_all_keys(self, keys): if not _is_non_string_iterable(keys): keys = [keys] with cython_context(): return SArray(_proxy=self.__proxy__.dict_has_all_keys(keys))
[ "\n Create a boolean SArray by checking the keys of an SArray of\n dictionaries. An element of the output SArray is True if the\n corresponding input element's dictionary has all of the given keys.\n Fails on SArrays whose data type is not ``dict``.\n\n Parameters\n -------...
Please provide a description of the function:def apply(self, fn, dtype=None, skip_na=True, seed=None): assert callable(fn), "Input function must be callable." dryrun = [fn(i) for i in self.head(100) if i is not None] if dtype is None: dtype = infer_type_of_list(dryrun) ...
[ "\n apply(fn, dtype=None, skip_na=True, seed=None)\n\n Transform each element of the SArray by a given function. The result\n SArray is of type ``dtype``. ``fn`` should be a function that returns\n exactly one value which can be cast into the type specified by\n ``dtype``. If ``dt...
Please provide a description of the function:def filter(self, fn, skip_na=True, seed=None): assert callable(fn), "Input must be callable" if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) with cython_context(): return SArray(_proxy=self.__pr...
[ "\n Filter this SArray by a function.\n\n Returns a new SArray filtered by this SArray. If `fn` evaluates an\n element to true, this element is copied to the new SArray. If not, it\n isn't. Throws an exception if the return type of `fn` is not castable\n to a boolean value.\n\n ...
Please provide a description of the function:def sample(self, fraction, seed=None, exact=False): if (fraction > 1 or fraction < 0): raise ValueError('Invalid sampling rate: ' + str(fraction)) if (len(self) == 0): return SArray() if seed is None: seed ...
[ "\n Create an SArray which contains a subsample of the current SArray.\n\n Parameters\n ----------\n fraction : float\n Fraction of the rows to fetch. Must be between 0 and 1.\n if exact is False (default), the number of rows returned is\n approximately t...
Please provide a description of the function:def hash(self, seed=0): with cython_context(): return SArray(_proxy=self.__proxy__.hash(seed))
[ "\n Returns an SArray with a hash of each element. seed can be used\n to change the hash function to allow this method to be used for\n random number generation.\n\n Parameters\n ----------\n seed : int\n Defaults to 0. Can be changed to different values to get\n...
Please provide a description of the function:def random_integers(cls, size, seed=None): if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) return cls.from_sequence(size).hash(seed)
[ "\n Returns an SArray with random integer values.\n " ]
Please provide a description of the function:def argmin(self): from .sframe import SFrame as _SFrame if len(self) == 0: return None if not any([isinstance(self[0], i) for i in [int,float,long]]): raise TypeError("SArray must be of type 'int', 'long', or 'float'....
[ "\n Get the index of the minimum numeric value in SArray.\n\n Returns None on an empty SArray. Raises an exception if called on an\n SArray with non-numeric type.\n\n Returns\n -------\n out : int\n index of the minimum value of SArray\n\n See Also\n ...
Please provide a description of the function:def mean(self): with cython_context(): if self.dtype == _Image: from .. import extensions return extensions.generate_mean(self) else: return self.__proxy__.mean()
[ "\n Mean of all the values in the SArray, or mean image.\n\n Returns None on an empty SArray. Raises an exception if called on an\n SArray with non-numeric type or non-Image type.\n\n Returns\n -------\n out : float | turicreate.Image\n Mean of all values in SArr...
Please provide a description of the function:def datetime_to_str(self,format="%Y-%m-%dT%H:%M:%S%ZP"): if(self.dtype != datetime.datetime): raise TypeError("datetime_to_str expects SArray of datetime as input SArray") with cython_context(): return SArray(_proxy=self.__pr...
[ "\n Create a new SArray with all the values cast to str. The string format is\n specified by the 'format' parameter.\n\n Parameters\n ----------\n format : str\n The format to output the string. Default format is \"%Y-%m-%dT%H:%M:%S%ZP\".\n\n Returns\n ---...
Please provide a description of the function:def str_to_datetime(self,format="%Y-%m-%dT%H:%M:%S%ZP"): if(self.dtype != str): raise TypeError("str_to_datetime expects SArray of str as input SArray") with cython_context(): return SArray(_proxy=self.__proxy__.str_to_dateti...
[ "\n Create a new SArray with all the values cast to datetime. The string format is\n specified by the 'format' parameter.\n\n Parameters\n ----------\n format : str\n The string format of the input SArray. Default format is \"%Y-%m-%dT%H:%M:%S%ZP\".\n If form...
Please provide a description of the function:def pixel_array_to_image(self, width, height, channels, undefined_on_failure=True, allow_rounding=False): if(self.dtype != array.array): raise TypeError("array_to_img expects SArray of arrays as input SArray") num_to_test = 10 n...
[ "\n Create a new SArray with all the values cast to :py:class:`turicreate.image.Image`\n of uniform size.\n\n Parameters\n ----------\n width: int\n The width of the new images.\n\n height: int\n The height of the new images.\n\n channels: int.\...
Please provide a description of the function:def astype(self, dtype, undefined_on_failure=False): if (dtype == _Image) and (self.dtype == array.array): raise TypeError("Cannot cast from image type to array with sarray.astype(). Please use sarray.pixel_array_to_image() instead.") w...
[ "\n Create a new SArray with all values cast to the given type. Throws an\n exception if the types are not castable to the given type.\n\n Parameters\n ----------\n dtype : {int, float, str, list, array.array, dict, datetime.datetime}\n The type to cast the elements to ...
Please provide a description of the function:def clip(self, lower=float('nan'), upper=float('nan')): with cython_context(): return SArray(_proxy=self.__proxy__.clip(lower, upper))
[ "\n Create a new SArray with each value clipped to be within the given\n bounds.\n\n In this case, \"clipped\" means that values below the lower bound will be\n set to the lower bound value. Values above the upper bound will be set\n to the upper bound value. This function can ope...
Please provide a description of the function:def clip_lower(self, threshold): with cython_context(): return SArray(_proxy=self.__proxy__.clip(threshold, float('nan')))
[ "\n Create new SArray with all values clipped to the given lower bound. This\n function can operate on numeric arrays, as well as vector arrays, in\n which case each individual element in each vector is clipped. Throws an\n exception if the SArray is empty or the types are non-numeric.\n...
Please provide a description of the function:def tail(self, n=10): with cython_context(): return SArray(_proxy=self.__proxy__.tail(n))
[ "\n Get an SArray that contains the last n elements in the SArray.\n\n Parameters\n ----------\n n : int\n The number of elements to fetch\n\n Returns\n -------\n out : SArray\n A new SArray which contains the last n rows of the current SArray.\...
Please provide a description of the function:def fillna(self, value): with cython_context(): return SArray(_proxy = self.__proxy__.fill_missing_values(value))
[ "\n Create new SArray with all missing values (None or NaN) filled in\n with the given value.\n\n The size of the new SArray will be the same as the original SArray. If\n the given value is not the same type as the values in the SArray,\n `fillna` will attempt to convert the value...