INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Same as select columns but redirect runtime error to ToolkitError. | def _toolkits_select_columns(dataset, columns):
"""
Same as select columns but redirect runtime error to ToolkitError.
"""
try:
return dataset.select_columns(columns)
except RuntimeError:
missing_features = list(set(columns).difference(set(dataset.column_names())))
raise Tool... |
Check if a column exists in an SFrame with error message. | def _raise_error_if_column_exists(dataset, column_name = 'dataset',
dataset_variable_name = 'dataset',
column_name_error_message_name = 'column_name'):
"""
Check if a column exists in an SFrame with error message.
"""
err_msg = 'The SFrame {0} must... |
Check whether or not the requested option is one of the allowed values. | def _check_categorical_option_type(option_name, option_value, possible_values):
"""
Check whether or not the requested option is one of the allowed values.
"""
err_msg = '{0} is not a valid option for {1}. '.format(option_value, option_name)
err_msg += ' Expected one of: '.format(possible_values)
... |
Check if the input is an SArray. Provide a proper error message otherwise. | def _raise_error_if_not_sarray(dataset, variable_name="SArray"):
"""
Check if the input is an SArray. Provide a proper error
message otherwise.
"""
err_msg = "Input %s is not an SArray."
if not isinstance(dataset, _SArray):
raise ToolkitError(err_msg % variable_name) |
Check if the input is an SFrame. Provide a proper error message otherwise. | def _raise_error_if_not_sframe(dataset, variable_name="SFrame"):
"""
Check if the input is an SFrame. Provide a proper error
message otherwise.
"""
err_msg = "Input %s is not an SFrame. If it is a Pandas DataFrame,"
err_msg += " you may use the to_sframe() function to convert it to an SFrame."
... |
Check if the input is empty. | def _raise_error_if_sframe_empty(dataset, variable_name="SFrame"):
"""
Check if the input is empty.
"""
err_msg = "Input %s either has no rows or no columns. A non-empty SFrame "
err_msg += "is required."
if dataset.num_rows() == 0 or dataset.num_columns() == 0:
raise ToolkitError(err_m... |
Check if the input is an SFrame. Provide a proper error message otherwise. | def _raise_error_evaluation_metric_is_valid(metric, allowed_metrics):
"""
Check if the input is an SFrame. Provide a proper error
message otherwise.
"""
err_msg = "Evaluation metric '%s' not recognized. The supported evaluation"
err_msg += " metrics are (%s)."
if metric not in allowed_metr... |
Checks if numeric parameter is within given range | def _numeric_param_check_range(variable_name, variable_value, range_bottom, range_top):
"""
Checks if numeric parameter is within given range
"""
err_msg = "%s must be between %i and %i"
if variable_value < range_bottom or variable_value > range_top:
raise ToolkitError(err_msg % (variable_n... |
Validate and canonicalize training and validation data. | def _validate_data(dataset, target, features=None, validation_set='auto'):
"""
Validate and canonicalize training and validation data.
Parameters
----------
dataset : SFrame
Dataset for training the model.
target : string
Name of the column containing the target variable.
... |
Validate a row label column. If the row label is not specified a column is created with row numbers named with the string in the default_label parameter. | def _validate_row_label(dataset, label=None, default_label='__id'):
"""
Validate a row label column. If the row label is not specified, a column is
created with row numbers, named with the string in the `default_label`
parameter.
Parameters
----------
dataset : SFrame
Input dataset.... |
Returns Mac version as a tuple of integers making it easy to do proper version comparisons. On non - Macs it returns an empty tuple. | def _mac_ver():
"""
Returns Mac version as a tuple of integers, making it easy to do proper
version comparisons. On non-Macs, it returns an empty tuple.
"""
import platform
import sys
if sys.platform == 'darwin':
ver_str = platform.mac_ver()[0]
return tuple([int(v) for v in v... |
Print a message making it clear to the user what compute resource is used in neural network training. | def _print_neural_compute_device(cuda_gpus, use_mps, cuda_mem_req=None, has_mps_impl=True):
"""
Print a message making it clear to the user what compute resource is used in
neural network training.
"""
num_cuda_gpus = len(cuda_gpus)
if num_cuda_gpus >= 1:
gpu_names = ', '.join(gpu['name'... |
Get a proto class from the MessageFactory by name. | def _GetMessageFromFactory(factory, full_name):
"""Get a proto class from the MessageFactory by name.
Args:
factory: a MessageFactory instance.
full_name: str, the fully qualified name of the proto type.
Returns:
A class, for the type identified by full_name.
Raises:
KeyError, if the proto is n... |
Create a Protobuf class whose fields are basic types. | def MakeSimpleProtoClass(fields, full_name=None, pool=None):
"""Create a Protobuf class whose fields are basic types.
Note: this doesn't validate field names!
Args:
fields: dict of {name: field_type} mappings for each field in the proto. If
this is an OrderedDict the order will be maintained, otherw... |
Populate FileDescriptorProto for MessageFactory s DescriptorPool. | def _MakeFileDescriptorProto(proto_file_name, full_name, field_items):
"""Populate FileDescriptorProto for MessageFactory's DescriptorPool."""
package, name = full_name.rsplit('.', 1)
file_proto = descriptor_pb2.FileDescriptorProto()
file_proto.name = os.path.join(package.replace('.', '/'), proto_file_name)
f... |
Convert a decision tree model to protobuf format. | def convert(model, input_name, output_features):
"""Convert a decision tree model to protobuf format.
Parameters
----------
decision_tree : DecisionTreeClassifier
A trained scikit-learn tree model.
input_name: str
Name of the input columns.
output_name: str
Name of the... |
Returns user - defined metadata making sure information all models should have is also available as a dictionary | def _get_model_metadata(model_class, metadata, version=None):
"""
Returns user-defined metadata, making sure information all models should
have is also available, as a dictionary
"""
from turicreate import __version__
info = {
'turicreate_version': __version__,
'type': model_cla... |
Sets user - defined metadata making sure information all models should have is also available | def _set_model_metadata(mlmodel, model_class, metadata, version=None):
"""
Sets user-defined metadata, making sure information all models should have
is also available
"""
info = _get_model_metadata(model_class, metadata, version)
mlmodel.user_defined_metadata.update(info) |
Converts name to camel - case and returns it. | def _ToCamelCase(name):
"""Converts name to camel-case and returns it."""
capitalize_next = False
result = []
for c in name:
if c == '_':
if result:
capitalize_next = True
elif capitalize_next:
result.append(c.upper())
capitalize_next = False
else:
result += c
# L... |
Converts name to Json name and returns it. | def _ToJsonName(name):
"""Converts name to Json name and returns it."""
capitalize_next = False
result = []
for c in name:
if c == '_':
capitalize_next = True
elif capitalize_next:
result.append(c.upper())
capitalize_next = False
else:
result += c
return ''.join(result) |
Sets the descriptor s options | def _SetOptions(self, options, options_class_name):
"""Sets the descriptor's options
This function is used in generated proto2 files to update descriptor
options. It must not be used outside proto2.
"""
self._options = options
self._options_class_name = options_class_name
# Does this descr... |
Retrieves descriptor options. | def GetOptions(self):
"""Retrieves descriptor options.
This method returns the options set or creates the default options for the
descriptor.
"""
if self._options:
return self._options
from google.protobuf import descriptor_pb2
try:
options_class = getattr(descriptor_pb2, self._... |
Copies this to the matching proto in descriptor_pb2. | def CopyToProto(self, proto):
"""Copies this to the matching proto in descriptor_pb2.
Args:
proto: An empty proto instance from descriptor_pb2.
Raises:
Error: If self couldnt be serialized, due to to few constructor arguments.
"""
if (self.file is not None and
self._serialized_... |
Returns the string name of an enum value. | def EnumValueName(self, enum, value):
"""Returns the string name of an enum value.
This is just a small helper method to simplify a common operation.
Args:
enum: string name of the Enum.
value: int, value of the enum.
Returns:
string name of the enum value.
Raises:
KeyErr... |
Given a target_reference made in context of project returns the AbstractTarget instance that is referred to as well as properties explicitly specified for this reference. | def resolve_reference(target_reference, project):
""" Given a target_reference, made in context of 'project',
returns the AbstractTarget instance that is referred to, as well
as properties explicitly specified for this reference.
"""
# Separate target name from properties override
assert isinsta... |
Attempts to generate the target given by target reference which can refer both to a main target or to a file. Returns a list consisting of - usage requirements - generated virtual targets if any target_reference: Target reference project: Project where the reference is made property_set: Properties of the main target t... | def generate_from_reference(target_reference, project, property_set_):
""" Attempts to generate the target given by target reference, which
can refer both to a main target or to a file.
Returns a list consisting of
- usage requirements
- generated virtual targets, if any
target_reference: Targe... |
Registers the specified target as a main target alternatives. Returns target. | def main_target_alternative (self, target):
""" Registers the specified target as a main target alternatives.
Returns 'target'.
"""
assert isinstance(target, AbstractTarget)
target.project ().add_alternative (target)
return target |
Return the list of sources to use if main target rule is invoked with sources. If there are any objects in sources they are treated as main target instances and the name of such targets are adjusted to be <name_of_this_target > __<name_of_source_target >. Such renaming is disabled is non - empty value is passed for no ... | def main_target_sources (self, sources, main_target_name, no_renaming=0):
"""Return the list of sources to use, if main target rule is invoked
with 'sources'. If there are any objects in 'sources', they are treated
as main target instances, and the name of such targets are adjusted to
be... |
Returns the requirement to use when declaring a main target which are obtained by - translating all specified property paths and - refining project requirements with the one specified for the target | def main_target_requirements(self, specification, project):
"""Returns the requirement to use when declaring a main target,
which are obtained by
- translating all specified property paths, and
- refining project requirements with the one specified for the target
'specificat... |
Returns the use requirement to use when declaraing a main target which are obtained by - translating all specified property paths and - adding project s usage requirements specification: Use - properties explicitly specified for a main target project: Project where the main target is to be declared | def main_target_usage_requirements (self, specification, project):
""" Returns the use requirement to use when declaraing a main target,
which are obtained by
- translating all specified property paths, and
- adding project's usage requirements
specification: Use... |
Return the default build value to use when declaring a main target which is obtained by using specified value if not empty and parent s default build attribute otherwise. specification: Default build explicitly specified for a main target project: Project where the main target is to be declared | def main_target_default_build (self, specification, project):
""" Return the default build value to use when declaring a main target,
which is obtained by using specified value if not empty and parent's
default build attribute otherwise.
specification: Default build explicit... |
Helper rules to detect cycles in main target references. | def start_building (self, main_target_instance):
""" Helper rules to detect cycles in main target references.
"""
assert isinstance(main_target_instance, MainTarget)
if id(main_target_instance) in self.targets_being_built_:
names = []
for t in self.targets_being_b... |
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. | 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... |
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... |
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.
"""
... |
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. | 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. | 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 ratings for example the ... | 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 | 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 | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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 or lists of st... | 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. | 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. | 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. | 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: | 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: | 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 is the number of t... | 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. | 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. | 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. | 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... |
Create a: class: ImageClassifier model. | 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... |
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']
... |
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 returns a vector of probabilities by e... | 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. | 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. | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.