INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Creates a TypedTarget with the specified properties.
The 'name', 'sources', 'requirements', 'default_build' and
'usage_requirements' are assumed to be in the form specified
by the user in Jamfile corresponding to 'project'. | def create_typed_target (self, type, project, name, sources, requirements, default_build, usage_requirements):
""" Creates a TypedTarget with the specified properties.
The 'name', 'sources', 'requirements', 'default_build' and
'usage_requirements' are assumed to be in the form specified
... |
Generates all possible targets contained in this project. | def generate (self, ps):
""" Generates all possible targets contained in this project.
"""
assert isinstance(ps, property_set.PropertySet)
self.manager_.targets().log(
"Building project '%s' with '%s'" % (self.name (), str(ps)))
self.manager_.targets().increase_indent... |
Computes and returns a list of AbstractTarget instances which
must be built when this project is built. | def targets_to_build (self):
""" Computes and returns a list of AbstractTarget instances which
must be built when this project is built.
"""
result = []
if not self.built_main_targets_:
self.build_main_targets ()
# Collect all main targets here, except f... |
Add 'target' to the list of targets in this project
that should be build only by explicit request. | def mark_targets_as_explicit (self, target_names):
"""Add 'target' to the list of targets in this project
that should be build only by explicit request."""
# Record the name of the target, not instance, since this
# rule is called before main target instaces are created.
assert ... |
Add new target alternative. | def add_alternative (self, target_instance):
""" Add new target alternative.
"""
assert isinstance(target_instance, AbstractTarget)
if self.built_main_targets_:
raise IllegalOperation ("add-alternative called when main targets are already created for project '%s'" % self.full... |
Tells if a main target with the specified name exists. | def has_main_target (self, name):
"""Tells if a main target with the specified name exists."""
assert isinstance(name, basestring)
if not self.built_main_targets_:
self.build_main_targets()
return name in self.main_target_ |
Returns a 'MainTarget' class instance corresponding to the 'name'. | def create_main_target (self, name):
""" Returns a 'MainTarget' class instance corresponding to the 'name'.
"""
assert isinstance(name, basestring)
if not self.built_main_targets_:
self.build_main_targets ()
return self.main_targets_.get (name, None) |
Find and return the target with the specified id, treated
relative to self. | def find_really(self, id):
""" Find and return the target with the specified id, treated
relative to self.
"""
assert isinstance(id, basestring)
result = None
current_location = self.get ('location')
__re_split_project_target = re.compile (r'(.*)//(.*)')
... |
Adds a new constant for this project.
The constant will be available for use in Jamfile
module for this project. If 'path' is true,
the constant will be interpreted relatively
to the location of project. | def add_constant(self, name, value, path=0):
"""Adds a new constant for this project.
The constant will be available for use in Jamfile
module for this project. If 'path' is true,
the constant will be interpreted relatively
to the location of project.
"""
assert ... |
Add a new alternative for this target. | def add_alternative (self, target):
""" Add a new alternative for this target.
"""
assert isinstance(target, BasicTarget)
d = target.default_build ()
if self.alternatives_ and self.default_build_ != d:
get_manager().errors()("default build must be identical in all al... |
Select an alternative for this main target, by finding all alternatives
which requirements are satisfied by 'properties' and picking the one with
longest requirements set.
Returns the result of calling 'generate' on that alternative. | def generate (self, ps):
""" Select an alternative for this main target, by finding all alternatives
which requirements are satisfied by 'properties' and picking the one with
longest requirements set.
Returns the result of calling 'generate' on that alternative.
"""
... |
Returns the best viable alternative for this property_set
See the documentation for selection rules.
# TODO: shouldn't this be 'alternative' (singular)? | def __select_alternatives (self, property_set_, debug):
""" Returns the best viable alternative for this property_set
See the documentation for selection rules.
# TODO: shouldn't this be 'alternative' (singular)?
"""
# When selecting alternatives we have to consider defau... |
Generates the main target with the given property set
and returns a list which first element is property_set object
containing usage_requirements of generated target and with
generated virtual target in other elements. It's possible
that no targets are generated. | def __generate_really (self, prop_set):
""" Generates the main target with the given property set
and returns a list which first element is property_set object
containing usage_requirements of generated target and with
generated virtual target in other elements. It's possible... |
Returns the list of AbstractTargets which are used as sources.
The extra properties specified for sources are not represented.
The only used of this rule at the moment is the '--dump-tests'
feature of the test system. | def sources (self):
""" Returns the list of AbstractTargets which are used as sources.
The extra properties specified for sources are not represented.
The only used of this rule at the moment is the '--dump-tests'
feature of the test system.
"""
if self.source... |
Given build request and requirements, return properties
common to dependency build request and target build
properties. | def common_properties (self, build_request, requirements):
""" Given build request and requirements, return properties
common to dependency build request and target build
properties.
"""
# For optimization, we add free unconditional requirements directly,
# withou... |
Returns the alternative condition for this alternative, if
the condition is satisfied by 'property_set'. | def match (self, property_set_, debug):
""" Returns the alternative condition for this alternative, if
the condition is satisfied by 'property_set'.
"""
# The condition is composed of all base non-conditional properties.
# It's not clear if we should expand 'self.requirements... |
Takes a target reference, which might be either target id
or a dependency property, and generates that target using
'property_set' as build request.
Returns a tuple (result, usage_requirements). | def generate_dependency_properties(self, properties, ps):
""" Takes a target reference, which might be either target id
or a dependency property, and generates that target using
'property_set' as build request.
Returns a tuple (result, usage_requirements).
"""
... |
Determines final build properties, generates sources,
and calls 'construct'. This method should not be
overridden. | def generate (self, ps):
""" Determines final build properties, generates sources,
and calls 'construct'. This method should not be
overridden.
"""
assert isinstance(ps, property_set.PropertySet)
self.manager_.errors().push_user_context(
"Generating target " +... |
Given the set of generated targets, and refined build
properties, determines and sets appripriate usage requirements
on those targets. | def compute_usage_requirements (self, subvariant):
""" Given the set of generated targets, and refined build
properties, determines and sets appripriate usage requirements
on those targets.
"""
assert isinstance(subvariant, virtual_target.Subvariant)
rproperties =... |
Creates a new subvariant-dg instances for 'targets'
- 'root-targets' the virtual targets will be returned to dependents
- 'all-targets' all virtual
targets created while building this main target
- 'build-request' is property-set instance with
requested build properties | def create_subvariant (self, root_targets, all_targets,
build_request, sources,
rproperties, usage_requirements):
"""Creates a new subvariant-dg instances for 'targets'
- 'root-targets' the virtual targets will be returned to dependents
- '... |
Declares a new variant.
First determines explicit properties for this variant, by
refining parents' explicit properties with the passed explicit
properties. The result is remembered and will be used if
this variant is used as parent.
Second, determines the full property set for ... | def variant (name, parents_or_properties, explicit_properties = []):
""" Declares a new variant.
First determines explicit properties for this variant, by
refining parents' explicit properties with the passed explicit
properties. The result is remembered and will be used if
this vari... |
Registers all features and variants declared by this module. | def register_globals ():
""" Registers all features and variants declared by this module.
"""
# This feature is used to determine which OS we're on.
# In future, this may become <target-os> and <host-os>
# TODO: check this. Compatibility with bjam names? Subfeature for version?
os = sys.platfor... |
The implementation of the 'lib' rule. Beyond standard syntax that rule allows
simplified: 'lib a b c ;'. | def lib(names, sources=[], requirements=[], default_build=[], usage_requirements=[]):
"""The implementation of the 'lib' rule. Beyond standard syntax that rule allows
simplified: 'lib a b c ;'."""
assert is_iterable_typed(names, basestring)
assert is_iterable_typed(sources, basestring)
assert is_ite... |
For all virtual targets for the same dependency graph as self,
i.e. which belong to the same main target, add their directories
to include path. | def adjust_properties (self, prop_set):
""" For all virtual targets for the same dependency graph as self,
i.e. which belong to the same main target, add their directories
to include path.
"""
assert isinstance(prop_set, property_set.PropertySet)
s = self.targets ... |
Create a model that makes recommendations using item popularity. When no
target column is provided, the popularity is determined by the number of
observations involving each item. When a target is provided, popularity
is computed using the item's mean target value. When the target column
contains rating... | 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):
"""
Create a model that makes recommendations using item popularity. When no
target column is provided, the popularity is ... |
Get parameter.s | def get_params(self, deep=False):
"""Get parameter.s"""
params = super(XGBModel, self).get_params(deep=deep)
if params['missing'] is np.nan:
params['missing'] = None # sklearn doesn't handle nan. see #4725
if not params.get('eval_metric', True):
del params['eval_... |
Get xgboost type parameters. | def get_xgb_params(self):
"""Get xgboost type parameters."""
xgb_params = self.get_params()
xgb_params['silent'] = 1 if self.silent else 0
if self.nthread <= 0:
xgb_params.pop('nthread', None)
return xgb_params |
Fit the gradient boosting model
Parameters
----------
X : array_like
Feature matrix
y : array_like
Labels
eval_set : list, optional
A list of (X, y) tuple pairs to use as a validation set for
early-stopping
eval_metric : st... | 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
"""
Fit the gradient boosting model
Parameters
----------
X : array_like
... |
Fit gradient boosting classifier
Parameters
----------
X : array_like
Feature matrix
y : array_like
Labels
sample_weight : array_like
Weight for each instance
eval_set : list, optional
A list of (X, y) pairs to use as a val... | 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
"""
Fit gradient boosting classifier
Parameters
----------
X : array_like
... |
Transform a string by bracketing it with "<>". If already bracketed, does nothing.
features: one string or a sequence of strings
return: the gristed string, if features is a string, or a sequence of gristed strings, if features is a sequence | def add_grist (features):
""" Transform a string by bracketing it with "<>". If already bracketed, does nothing.
features: one string or a sequence of strings
return: the gristed string, if features is a string, or a sequence of gristed strings, if features is a sequence
"""
assert is_iterab... |
Replaces the grist of a string by a new one.
Returns the string with the new grist. | def replace_grist (features, new_grist):
""" Replaces the grist of a string by a new one.
Returns the string with the new grist.
"""
assert is_iterable_typed(features, basestring) or isinstance(features, basestring)
assert isinstance(new_grist, basestring)
# this function is used a lot in th... |
Gets the value of a property, that is, the part following the grist, if any. | def get_value (property):
""" Gets the value of a property, that is, the part following the grist, if any.
"""
assert is_iterable_typed(property, basestring) or isinstance(property, basestring)
return replace_grist (property, '') |
Returns the grist of a string.
If value is a sequence, does it for every value and returns the result as a sequence. | def get_grist (value):
""" Returns the grist of a string.
If value is a sequence, does it for every value and returns the result as a sequence.
"""
assert is_iterable_typed(value, basestring) or isinstance(value, basestring)
def get_grist_one (name):
split = __re_grist_and_value.match (n... |
Returns the value without grist.
If value is a sequence, does it for every value and returns the result as a sequence. | def ungrist (value):
""" Returns the value without grist.
If value is a sequence, does it for every value and returns the result as a sequence.
"""
assert is_iterable_typed(value, basestring) or isinstance(value, basestring)
def ungrist_one (value):
stripped = __re_grist_content.match (v... |
Replaces the suffix of name by new_suffix.
If no suffix exists, the new one is added. | def replace_suffix (name, new_suffix):
""" Replaces the suffix of name by new_suffix.
If no suffix exists, the new one is added.
"""
assert isinstance(name, basestring)
assert isinstance(new_suffix, basestring)
split = os.path.splitext (name)
return split [0] + new_suffix |
Splits an id in the toolset and specific rule parts. E.g.
'gcc.compile.c++' returns ('gcc', 'compile.c++') | def split_action_id (id):
""" Splits an id in the toolset and specific rule parts. E.g.
'gcc.compile.c++' returns ('gcc', 'compile.c++')
"""
assert isinstance(id, basestring)
split = id.split ('.', 1)
toolset = split [0]
name = ''
if len (split) > 1:
name = split [1]
retu... |
Returns true if running on windows, whether in cygwin or not. | def on_windows ():
""" Returns true if running on windows, whether in cygwin or not.
"""
if bjam.variable("NT"):
return True
elif bjam.variable("UNIX"):
uname = bjam.variable("JAMUNAME")
if uname and uname[0].startswith("CYGWIN"):
return True
return False |
Validate the main Kmeans dataset.
Parameters
----------
dataset: SFrame
Input dataset. | def _validate_dataset(dataset):
"""
Validate the main Kmeans dataset.
Parameters
----------
dataset: SFrame
Input dataset.
"""
if not (isinstance(dataset, _SFrame)):
raise TypeError("Input 'dataset' must be an SFrame.")
if dataset.num_rows() == 0 or dataset.num_columns(... |
Validate the initial centers.
Parameters
----------
initial_centers : SFrame
Initial cluster center locations, in SFrame form. | def _validate_initial_centers(initial_centers):
"""
Validate the initial centers.
Parameters
----------
initial_centers : SFrame
Initial cluster center locations, in SFrame form.
"""
if not (isinstance(initial_centers, _SFrame)):
raise TypeError("Input 'initial_centers' must... |
Validate the combination of the `num_clusters` and `initial_centers`
parameters in the Kmeans model create function. If the combination is
valid, determine and return the correct number of clusters.
Parameters
----------
num_clusters : int
Specified number of clusters.
initial_centers ... | def _validate_num_clusters(num_clusters, initial_centers, num_rows):
"""
Validate the combination of the `num_clusters` and `initial_centers`
parameters in the Kmeans model create function. If the combination is
valid, determine and return the correct number of clusters.
Parameters
----------
... |
Identify the subset of desired `features` that are valid for the Kmeans
model. A warning is emitted for each feature that is excluded.
Parameters
----------
features : list[str]
Desired feature names.
column_type_map : dict[str, type]
Dictionary mapping each column name to the type... | def _validate_features(features, column_type_map, valid_types, label):
"""
Identify the subset of desired `features` that are valid for the Kmeans
model. A warning is emitted for each feature that is excluded.
Parameters
----------
features : list[str]
Desired feature names.
column... |
Create a k-means clustering model. The KmeansModel object contains the
computed cluster centers and the cluster assignment for each instance in
the input 'dataset'.
Given a number of clusters, k-means iteratively chooses the best cluster
centers and assigns nearby points to the best cluster. If no poin... | def create(dataset, num_clusters=None, features=None, label=None,
initial_centers=None, max_iterations=10, batch_size=None,
verbose=True):
"""
Create a k-means clustering model. The KmeansModel object contains the
computed cluster centers and the cluster assignment for each instance in... |
Return predicted cluster label for instances in the new 'dataset'.
K-means predictions are made by assigning each new instance to the
closest cluster center.
Parameters
----------
dataset : SFrame
Dataset of new observations. Must include the features used for
... | def predict(self, dataset, output_type='cluster_id', verbose=True):
"""
Return predicted cluster label for instances in the new 'dataset'.
K-means predictions are made by assigning each new instance to the
closest cluster center.
Parameters
----------
dataset : S... |
Return the value of a given field.
+-----------------------+----------------------------------------------+
| Field | Description |
+=======================+==============================================+
| batch_size | Number ... | def _get(self, field):
"""
Return the value of a given field.
+-----------------------+----------------------------------------------+
| Field | Description |
+=======================+==============================================... |
If `text` is an SArray of strings or an SArray of lists of strings, the
occurances of word are counted for each row in the SArray.
If `text` is an SArray of dictionaries, the keys are tokenized and the
values are the counts. Counts for the same word, in the same row, are
added together.
This outpu... | def count_words(text, to_lower=True, delimiters=DEFAULT_DELIMITERS):
"""
If `text` is an SArray of strings or an SArray of lists of strings, the
occurances of word are counted for each row in the SArray.
If `text` is an SArray of dictionaries, the keys are tokenized and the
values are the counts. C... |
Return an SArray of ``dict`` type where each element contains the count
for each of the n-grams that appear in the corresponding input element.
The n-grams can be specified to be either character n-grams or word
n-grams. The input SArray could contain strings, dicts with string keys
and numeric values,... | def count_ngrams(text, n=2, method="word", to_lower=True,
delimiters=DEFAULT_DELIMITERS,
ignore_punct=True, ignore_space=True):
"""
Return an SArray of ``dict`` type where each element contains the count
for each of the n-grams that appear in the corresponding input element... |
Compute the TF-IDF scores for each word in each document. The collection
of documents must be in bag-of-words format.
.. math::
\mbox{TF-IDF}(w, d) = tf(w, d) * log(N / f(w))
where :math:`tf(w, d)` is the number of times word :math:`w` appeared in
document :math:`d`, :math:`f(w)` is the number... | def tf_idf(text):
"""
Compute the TF-IDF scores for each word in each document. The collection
of documents must be in bag-of-words format.
.. math::
\mbox{TF-IDF}(w, d) = tf(w, d) * log(N / f(w))
where :math:`tf(w, d)` is the number of times word :math:`w` appeared in
document :math:`... |
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 the
quality and explainability of the models learned on the transformed data.
RareWordTrimmer can be applied to all the string-, dictionary-, and list-typed
... | 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 the
quality and explainability of the mo... |
Tokenize the input SArray of text strings and return the list of tokens.
Parameters
----------
text : SArray[str]
Input data of strings representing English text. This tokenizer is not
intended to process XML, HTML, or other structured text formats.
to_lower : bool, optional
If... | def tokenize(text, to_lower=False, delimiters=DEFAULT_DELIMITERS):
"""
Tokenize the input SArray of text strings and return the list of tokens.
Parameters
----------
text : SArray[str]
Input data of strings representing English text. This tokenizer is not
intended to process XML, HT... |
For a given query and set of documents, compute the BM25 score for each
document. If we have a query with words q_1, ..., q_n the BM25 score for
a document is:
.. 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))}
where
* :math:`\mbox{IDF}(q_i) = log((N - ... | def bm25(dataset, query, k1=1.5, b=.75):
"""
For a given query and set of documents, compute the BM25 score for each
document. If we have a query with words q_1, ..., q_n the BM25 score for
a document is:
.. 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))}... |
Parse a file that's in libSVM format. In libSVM format each line of the text
file represents a document in bag of words format:
num_unique_words_in_doc word_id:count another_id:count
The word_ids have 0-based indexing, i.e. 0 corresponds to the first
word in the vocab filename.
Parameters
---... | def parse_sparse(filename, vocab_filename):
"""
Parse a file that's in libSVM format. In libSVM format each line of the text
file represents a document in bag of words format:
num_unique_words_in_doc word_id:count another_id:count
The word_ids have 0-based indexing, i.e. 0 corresponds to the first... |
Parse a file that's in "docword" format. This consists of a 3-line header
comprised of the document count, the vocabulary count, and the number of
tokens, i.e. unique (doc_id, word_id) pairs. After the header, each line
contains a space-separated triple of (doc_id, word_id, frequency), where
frequency i... | def parse_docword(filename, vocab_filename):
"""
Parse a file that's in "docword" format. This consists of a 3-line header
comprised of the document count, the vocabulary count, and the number of
tokens, i.e. unique (doc_id, word_id) pairs. After the header, each line
contains a space-separated trip... |
Utility for performing a random split for text data that is already in
bag-of-words format. For each (word, count) pair in a particular element,
the counts are uniformly partitioned in either a training set or a test
set.
Parameters
----------
dataset : SArray of type dict, SFrame with columns ... | def random_split(dataset, prob=.5):
"""
Utility for performing a random split for text data that is already in
bag-of-words format. For each (word, count) pair in a particular element,
the counts are uniformly partitioned in either a training set or a test
set.
Parameters
----------
dat... |
Train a booster with given parameters.
Parameters
----------
params : dict
Booster params.
dtrain : DMatrix
Data to be trained.
num_boost_round: int
Number of boosting iterations.
watchlist (evals): list of pairs (DMatrix, string)
List of items to be evaluated du... | 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-branches, attribute-defined-outside-init
"""Tra... |
Make an n-fold list of CVPack from random indices. | def mknfold(dall, nfold, param, seed, evals=(), fpreproc=None):
"""
Make an n-fold list of CVPack from random indices.
"""
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),... |
Aggregate cross-validation results. | def aggcv(rlist, show_stdv=True, show_progress=None, as_pandas=True):
# pylint: disable=invalid-name
"""
Aggregate cross-validation results.
"""
cvmap = {}
idx = rlist[0].split()[0]
for line in rlist:
arr = line.split()
assert idx == arr[0]
for it in arr[1:]:
... |
Cross-validation with given paramaters.
Parameters
----------
params : dict
Booster params.
dtrain : DMatrix
Data to be trained.
num_boost_round : int
Number of boosting iterations.
nfold : int
Number of folds in CV.
metrics : list of strings
Evaluati... | 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
"""Cross-validation with given paramaters.
Parameters
----------
params : dict
Boo... |
Save the model as a dictionary, which can be loaded with the
:py:func:`~turicreate.load_model` method. | def _get_native_state(self):
"""
Save the model as a dictionary, which can be loaded with the
:py:func:`~turicreate.load_model` method.
"""
state = self.__proxy__.get_state()
state['classifier'] = state['classifier'].__proxy__
del state['feature_extractor']
... |
Create a :class:`ImageClassifier` 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=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_size'],
lbfgs_memory_level = _DEFAULT_SOLVER... |
A function to load a previously saved ImageClassifier
instance. | def _load_version(cls, state, version):
"""
A function to load a previously saved ImageClassifier
instance.
"""
_tkutl._model_version_check(version, cls._PYTHON_IMAGE_CLASSIFIER_VERSION)
from turicreate.toolkits.classifier.logistic_classifier import LogisticClassifier
... |
Return predictions for ``dataset``, using the trained logistic
regression model. Predictions can be generated as class labels,
probabilities that the target value is True, or margins (i.e. the
distance of the observations from the hyperplane separating the
classes). `probability_vector` ... | def predict(self, dataset, output_type='class', batch_size=64):
"""
Return predictions for ``dataset``, using the trained logistic
regression model. Predictions can be generated as class labels,
probabilities that the target value is True, or margins (i.e. the
distance of the obs... |
Return top-k predictions for the ``dataset``, using the trained model.
Predictions are returned as an SFrame with three columns: `id`,
`class`, and `probability`, `margin`, or `rank`, depending on the ``output_type``
parameter. Input dataset size must be the same as for training of the model.
... | def predict_topk(self, dataset, output_type="probability", k=3, batch_size=64):
"""
Return top-k predictions for the ``dataset``, using the trained model.
Predictions are returned as an SFrame with three columns: `id`,
`class`, and `probability`, `margin`, or `rank`, depending on the ``... |
Evaluate the model by making predictions of target values and comparing
these to actual values.
Parameters
----------
dataset : SFrame
Dataset of new observations. Must include columns with the same
names as the target and features used for model training. Additi... | 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 of new observations. Must include colum... |
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
# First define three internal helper functions
... |
Extract the ordering of the input layers. | def make_input_layers(self):
"""
Extract the ordering of the input layers.
"""
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'):
... |
Extract the ordering of output layers. | def make_output_layers(self):
"""
Extract the ordering of output layers.
"""
self.output_layers = []
# import pytest; pytest.set_trace()
if hasattr(self.model, 'output_layers'):
# find corresponding output layers in CoreML model
# assume output lay... |
Remove the layer, and reconnect each of its predecessor to each of
its successor | def _remove_layer_and_reconnect(self, layer):
""" Remove the layer, and reconnect each of its predecessor to each of
its successor
"""
successors = self.get_successors(layer)
predecessors = self.get_predecessors(layer)
# remove layer's edges
for succ in successors... |
Defuse the fused activation layers in the network. | def defuse_activation(self):
""" Defuse the fused activation layers in the network.
"""
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.la... |
Returns a new SArray that represents a fixed frequency datetime index.
Parameters
----------
start_time : datetime.datetime
Left bound for generating dates.
end_time : datetime.datetime
Right bound for generating dates.
freq : datetime.timedelta
F... | 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 : datetime.datetime
Right bound fo... |
Constructs an SArray of size with a const value.
Parameters
----------
value : [int | float | str | array.array | list | dict | datetime]
The value to fill the SArray
size : int
The size of the SArray
dtype : type
The type of the SArray. If not spec... | def from_const(cls, value, size, dtype=type(None)):
"""
Constructs an SArray of size with a const value.
Parameters
----------
value : [int | float | str | array.array | list | dict | datetime]
The value to fill the SArray
size : int
The size of the S... |
from_sequence(start=0, stop)
Create an SArray from sequence
.. sourcecode:: python
Construct an SArray of integer values from 0 to 999
>>> tc.SArray.from_sequence(1000)
This is equivalent, but more efficient than:
>>> tc.SArray(range(1000))
... | def from_sequence(cls, *args):
"""
from_sequence(start=0, stop)
Create an SArray from sequence
.. sourcecode:: python
Construct an SArray of integer values from 0 to 999
>>> tc.SArray.from_sequence(1000)
This is equivalent, but more efficient than... |
Construct an SArray from a json file or glob of json files.
The json file must contain a list of dictionaries. The returned
SArray type will be of dict type
Parameters
----------
filename : str
The filename or glob to load into an SArray.
Examples
----... | def read_json(cls, filename):
"""
Construct an SArray from a json file or glob of json files.
The json file must contain a list of dictionaries. The returned
SArray type will be of dict type
Parameters
----------
filename : str
The filename or glob to l... |
Selects elements from either istrue or isfalse depending on the value
of the condition SArray.
Parameters
----------
condition : SArray
An SArray of values such that for each value, if non-zero, yields a
value from istrue, otherwise from isfalse.
istrue : SArray... | def where(cls, condition, istrue, isfalse, dtype=None):
"""
Selects elements from either istrue or isfalse depending on the value
of the condition SArray.
Parameters
----------
condition : SArray
An SArray of values such that for each value, if non-zero, yields a... |
Saves the SArray to file.
The saved SArray will be in a directory named with the `targetfile`
parameter.
Parameters
----------
filename : string
A local path or a remote URL. If format is 'text', it will be
saved as a text file. If format is 'binary', a... | def save(self, filename, format=None):
"""
Saves the SArray to file.
The saved SArray will be in a directory named with the `targetfile`
parameter.
Parameters
----------
filename : string
A local path or a remote URL. If format is 'text', it will be... |
If this SArray contains vectors or lists, this returns a new SArray
containing each individual element sliced, between start and
end (exclusive).
Parameters
----------
start : int
The start position of the slice.
end : int, optional.
The end posi... | def vector_slice(self, start, end=None):
"""
If this SArray contains vectors or lists, this returns a new SArray
containing each individual element sliced, between start and
end (exclusive).
Parameters
----------
start : int
The start position of the ... |
This returns an SArray with each element sliced accordingly to the
slice specified. This is conceptually equivalent to:
>>> g.apply(lambda x: x[start:step:stop])
The SArray must be of type list, vector, or string.
For instance:
>>> g = SArray(["abcdef","qwerty"])
>>> ... | def element_slice(self, start=None, stop=None, step=None):
"""
This returns an SArray with each element sliced accordingly to the
slice specified. This is conceptually equivalent to:
>>> g.apply(lambda x: x[start:step:stop])
The SArray must be of type list, vector, or string.
... |
This returns an SArray with, for each input string, a dict from the unique,
delimited substrings to their number of occurrences within the original
string.
The SArray must be of type string.
..WARNING:: This function is deprecated, and will be removed in future
versions of Turi... | def _count_words(self, to_lower=True, delimiters=["\r", "\v", "\n", "\f", "\t", " "]):
"""
This returns an SArray with, for each input string, a dict from the unique,
delimited substrings to their number of occurrences within the original
string.
The SArray must be of type strin... |
For documentation, see turicreate.text_analytics.count_ngrams().
..WARNING:: This function is deprecated, and will be removed in future
versions of Turi Create. Please use the `text_analytics.count_words`
function instead. | def _count_ngrams(self, n=2, method="word", to_lower=True, ignore_space=True):
"""
For documentation, see turicreate.text_analytics.count_ngrams().
..WARNING:: This function is deprecated, and will be removed in future
versions of Turi Create. Please use the `text_analytics.count_words`... |
Filter an SArray of dictionary type by the given keys. By default, all
keys that are in the provided list in ``keys`` are *excluded* from the
returned SArray.
Parameters
----------
keys : list
A collection of keys to trim down the elements in the SArray.
exc... | def dict_trim_by_keys(self, keys, exclude=True):
"""
Filter an SArray of dictionary type by the given keys. By default, all
keys that are in the provided list in ``keys`` are *excluded* from the
returned SArray.
Parameters
----------
keys : list
A col... |
Filter dictionary values to a given range (inclusive). Trimming is only
performed on values which can be compared to the bound values. Fails on
SArrays whose data type is not ``dict``.
Parameters
----------
lower : int or long or float, optional
The lowest dictionary... | def dict_trim_by_values(self, lower=None, upper=None):
"""
Filter dictionary values to a given range (inclusive). Trimming is only
performed on values which can be compared to the bound values. Fails on
SArrays whose data type is not ``dict``.
Parameters
----------
... |
Create a boolean SArray by checking the keys of an SArray of
dictionaries. An element of the output SArray is True if the
corresponding input element's dictionary has any of the given keys.
Fails on SArrays whose data type is not ``dict``.
Parameters
----------
keys : li... | def dict_has_any_keys(self, keys):
"""
Create a boolean SArray by checking the keys of an SArray of
dictionaries. An element of the output SArray is True if the
corresponding input element's dictionary has any of the given keys.
Fails on SArrays whose data type is not ``dict``.
... |
Create a boolean SArray by checking the keys of an SArray of
dictionaries. An element of the output SArray is True if the
corresponding input element's dictionary has all of the given keys.
Fails on SArrays whose data type is not ``dict``.
Parameters
----------
keys : li... | def dict_has_all_keys(self, keys):
"""
Create a boolean SArray by checking the keys of an SArray of
dictionaries. An element of the output SArray is True if the
corresponding input element's dictionary has all of the given keys.
Fails on SArrays whose data type is not ``dict``.
... |
apply(fn, dtype=None, skip_na=True, seed=None)
Transform each element of the SArray by a given function. The result
SArray is of type ``dtype``. ``fn`` should be a function that returns
exactly one value which can be cast into the type specified by
``dtype``. If ``dtype`` is not specifi... | def apply(self, fn, dtype=None, skip_na=True, seed=None):
"""
apply(fn, dtype=None, skip_na=True, seed=None)
Transform each element of the SArray by a given function. The result
SArray is of type ``dtype``. ``fn`` should be a function that returns
exactly one value which can be ... |
Filter this SArray by a function.
Returns a new SArray filtered by this SArray. If `fn` evaluates an
element to true, this element is copied to the new SArray. If not, it
isn't. Throws an exception if the return type of `fn` is not castable
to a boolean value.
Parameters
... | def filter(self, fn, skip_na=True, seed=None):
"""
Filter this SArray by a function.
Returns a new SArray filtered by this SArray. If `fn` evaluates an
element to true, this element is copied to the new SArray. If not, it
isn't. Throws an exception if the return type of `fn` is... |
Create an SArray which contains a subsample of the current SArray.
Parameters
----------
fraction : float
Fraction of the rows to fetch. Must be between 0 and 1.
if exact is False (default), the number of rows returned is
approximately the fraction times the ... | def sample(self, fraction, seed=None, exact=False):
"""
Create an SArray which contains a subsample of the current SArray.
Parameters
----------
fraction : float
Fraction of the rows to fetch. Must be between 0 and 1.
if exact is False (default), the numb... |
Returns an SArray with a hash of each element. seed can be used
to change the hash function to allow this method to be used for
random number generation.
Parameters
----------
seed : int
Defaults to 0. Can be changed to different values to get
different h... | def hash(self, seed=0):
"""
Returns an SArray with a hash of each element. seed can be used
to change the hash function to allow this method to be used for
random number generation.
Parameters
----------
seed : int
Defaults to 0. Can be changed to dif... |
Returns an SArray with random integer values. | def random_integers(cls, size, seed=None):
"""
Returns an SArray with random integer values.
"""
if seed is None:
seed = abs(hash("%0.20f" % time.time())) % (2 ** 31)
return cls.from_sequence(size).hash(seed) |
Get the index of the minimum numeric value in SArray.
Returns None on an empty SArray. Raises an exception if called on an
SArray with non-numeric type.
Returns
-------
out : int
index of the minimum value of SArray
See Also
--------
argmax
... | def argmin(self):
"""
Get the index of the minimum numeric value in SArray.
Returns None on an empty SArray. Raises an exception if called on an
SArray with non-numeric type.
Returns
-------
out : int
index of the minimum value of SArray
See... |
Mean of all the values in the SArray, or mean image.
Returns None on an empty SArray. Raises an exception if called on an
SArray with non-numeric type or non-Image type.
Returns
-------
out : float | turicreate.Image
Mean of all values in SArray, or image holding pe... | def mean(self):
"""
Mean of all the values in the SArray, or mean image.
Returns None on an empty SArray. Raises an exception if called on an
SArray with non-numeric type or non-Image type.
Returns
-------
out : float | turicreate.Image
Mean of all v... |
Create a new SArray with all the values cast to str. The string format is
specified by the 'format' parameter.
Parameters
----------
format : str
The format to output the string. Default format is "%Y-%m-%dT%H:%M:%S%ZP".
Returns
-------
out : SArray[... | def datetime_to_str(self,format="%Y-%m-%dT%H:%M:%S%ZP"):
"""
Create a new SArray with all the values cast to str. The string format is
specified by the 'format' parameter.
Parameters
----------
format : str
The format to output the string. Default format is "... |
Create a new SArray with all the values cast to datetime. The string format is
specified by the 'format' parameter.
Parameters
----------
format : str
The string format of the input SArray. Default format is "%Y-%m-%dT%H:%M:%S%ZP".
If format is "ISO", the the for... | def str_to_datetime(self,format="%Y-%m-%dT%H:%M:%S%ZP"):
"""
Create a new SArray with all the values cast to datetime. The string format is
specified by the 'format' parameter.
Parameters
----------
format : str
The string format of the input SArray. Default ... |
Create a new SArray with all the values cast to :py:class:`turicreate.image.Image`
of uniform size.
Parameters
----------
width: int
The width of the new images.
height: int
The height of the new images.
channels: int.
Number of chan... | def pixel_array_to_image(self, width, height, channels, undefined_on_failure=True, allow_rounding=False):
"""
Create a new SArray with all the values cast to :py:class:`turicreate.image.Image`
of uniform size.
Parameters
----------
width: int
The width of the... |
Create a new SArray with all values cast to the given type. Throws an
exception if the types are not castable to the given type.
Parameters
----------
dtype : {int, float, str, list, array.array, dict, datetime.datetime}
The type to cast the elements to in SArray
un... | def astype(self, dtype, undefined_on_failure=False):
"""
Create a new SArray with all values cast to the given type. Throws an
exception if the types are not castable to the given type.
Parameters
----------
dtype : {int, float, str, list, array.array, dict, datetime.dat... |
Create a new SArray with each value clipped to be within the given
bounds.
In this case, "clipped" means that values below the lower bound will be
set to the lower bound value. Values above the upper bound will be set
to the upper bound value. This function can operate on SArrays of
... | def clip(self, lower=float('nan'), upper=float('nan')):
"""
Create a new SArray with each value clipped to be within the given
bounds.
In this case, "clipped" means that values below the lower bound will be
set to the lower bound value. Values above the upper bound will be set
... |
Create new SArray with all values clipped to the given lower bound. This
function can operate on numeric arrays, as well as vector arrays, in
which case each individual element in each vector is clipped. Throws an
exception if the SArray is empty or the types are non-numeric.
Parameters... | def clip_lower(self, threshold):
"""
Create new SArray with all values clipped to the given lower bound. This
function can operate on numeric arrays, as well as vector arrays, in
which case each individual element in each vector is clipped. Throws an
exception if the SArray is em... |
Get an SArray that contains the last n elements in the SArray.
Parameters
----------
n : int
The number of elements to fetch
Returns
-------
out : SArray
A new SArray which contains the last n rows of the current SArray. | def tail(self, n=10):
"""
Get an SArray that contains the last n elements in the SArray.
Parameters
----------
n : int
The number of elements to fetch
Returns
-------
out : SArray
A new SArray which contains the last n rows of the... |
Create new SArray with all missing values (None or NaN) filled in
with the given value.
The size of the new SArray will be the same as the original SArray. If
the given value is not the same type as the values in the SArray,
`fillna` will attempt to convert the value to the original SAr... | def fillna(self, value):
"""
Create new SArray with all missing values (None or NaN) filled in
with the given value.
The size of the new SArray will be the same as the original SArray. If
the given value is not the same type as the values in the SArray,
`fillna` will att... |
Create an SArray indicating which elements are in the top k.
Entries are '1' if the corresponding element in the current SArray is a
part of the top k elements, and '0' if that corresponding element is
not. Order is descending by default.
Parameters
----------
topk : in... | def is_topk(self, topk=10, reverse=False):
"""
Create an SArray indicating which elements are in the top k.
Entries are '1' if the corresponding element in the current SArray is a
part of the top k elements, and '0' if that corresponding element is
not. Order is descending by de... |
Summary statistics that can be calculated with one pass over the SArray.
Returns a turicreate.Sketch object which can be further queried for many
descriptive statistics over this SArray. Many of the statistics are
approximate. See the :class:`~turicreate.Sketch` documentation for more
d... | def summary(self, background=False, sub_sketch_keys=None):
"""
Summary statistics that can be calculated with one pass over the SArray.
Returns a turicreate.Sketch object which can be further queried for many
descriptive statistics over this SArray. Many of the statistics are
ap... |
Return an SFrame containing counts of unique values. The resulting
SFrame will be sorted in descending frequency.
Returns
-------
out : SFrame
An SFrame containing 2 columns : 'value', and 'count'. The SFrame will
be sorted in descending order by the column 'coun... | def value_counts(self):
"""
Return an SFrame containing counts of unique values. The resulting
SFrame will be sorted in descending frequency.
Returns
-------
out : SFrame
An SFrame containing 2 columns : 'value', and 'count'. The SFrame will
be so... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.