sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def subject(self, value):
"""
An asn1crypto.x509.Name object, or a dict with at least the
following keys:
- country_name
- state_or_province_name
- locality_name
- organization_name
- common_name
Less common keys include:
- organiz... | An asn1crypto.x509.Name object, or a dict with at least the
following keys:
- country_name
- state_or_province_name
- locality_name
- organization_name
- common_name
Less common keys include:
- organizational_unit_name
- email_address
... | entailment |
def subject_public_key(self, value):
"""
An asn1crypto.keys.PublicKeyInfo or oscrypto.asymmetric.PublicKey
object of the subject's public key.
"""
is_oscrypto = isinstance(value, asymmetric.PublicKey)
if not isinstance(value, keys.PublicKeyInfo) and not is_oscrypto:
... | An asn1crypto.keys.PublicKeyInfo or oscrypto.asymmetric.PublicKey
object of the subject's public key. | entailment |
def hash_algo(self, value):
"""
A unicode string of the hash algorithm to use when signing the
request - "sha1" (not recommended), "sha256" or "sha512"
"""
if value not in set(['sha1', 'sha256', 'sha512']):
raise ValueError(_pretty_message(
'''
... | A unicode string of the hash algorithm to use when signing the
request - "sha1" (not recommended), "sha256" or "sha512" | entailment |
def _get_subject_alt(self, name):
"""
Returns the native value for each value in the subject alt name
extension reqiest that is an asn1crypto.x509.GeneralName of the type
specified by the name param
:param name:
A unicode string use to filter the x509.GeneralName obj... | Returns the native value for each value in the subject alt name
extension reqiest that is an asn1crypto.x509.GeneralName of the type
specified by the name param
:param name:
A unicode string use to filter the x509.GeneralName objects by -
is the choice name x509.GeneralN... | entailment |
def _set_subject_alt(self, name, values):
"""
Replaces all existing asn1crypto.x509.GeneralName objects of the choice
represented by the name parameter with the values
:param name:
A unicode string of the choice name of the x509.GeneralName object
:param values:
... | Replaces all existing asn1crypto.x509.GeneralName objects of the choice
represented by the name parameter with the values
:param name:
A unicode string of the choice name of the x509.GeneralName object
:param values:
A list of unicode strings to use as the values for th... | entailment |
def set_extension(self, name, value):
"""
Sets the value for an extension using a fully constructed Asn1Value
object from asn1crypto. Normally this should not be needed, and the
convenience attributes should be sufficient.
See the definition of asn1crypto.x509.Extension to deter... | Sets the value for an extension using a fully constructed Asn1Value
object from asn1crypto. Normally this should not be needed, and the
convenience attributes should be sufficient.
See the definition of asn1crypto.x509.Extension to determine the
appropriate object type for a given exten... | entailment |
def _determine_critical(self, name):
"""
:return:
A boolean indicating the correct value of the critical flag for
an extension, based on information from RFC5280 and RFC 6960. The
correct value is based on the terminology SHOULD or MUST.
"""
if name =... | :return:
A boolean indicating the correct value of the critical flag for
an extension, based on information from RFC5280 and RFC 6960. The
correct value is based on the terminology SHOULD or MUST. | entailment |
def build(self, signing_private_key):
"""
Validates the certificate information, constructs an X.509 certificate
and then signs it
:param signing_private_key:
An asn1crypto.keys.PrivateKeyInfo or oscrypto.asymmetric.PrivateKey
object for the private key to sign t... | Validates the certificate information, constructs an X.509 certificate
and then signs it
:param signing_private_key:
An asn1crypto.keys.PrivateKeyInfo or oscrypto.asymmetric.PrivateKey
object for the private key to sign the request with. This should be
the private ke... | entailment |
def compute_metrics_cv(self, X, y, **kwargs):
'''Compute cross-validated metrics.
Trains this model on data X with labels y.
Returns a list of dict with keys name, scoring_name, value.
Args:
X (Union[np.array, pd.DataFrame]): data
y (Union[np.array, pd.DataFrame, pd.Ser... | Compute cross-validated metrics.
Trains this model on data X with labels y.
Returns a list of dict with keys name, scoring_name, value.
Args:
X (Union[np.array, pd.DataFrame]): data
y (Union[np.array, pd.DataFrame, pd.Series]): labels | entailment |
def cv_score_mean(self, X, y):
'''Compute mean score across cross validation folds.
Split data and labels into cross validation folds and fit the model for
each fold. Then, for each scoring type in scorings, compute the score.
Finally, average the scores across folds. Returns a dictiona... | Compute mean score across cross validation folds.
Split data and labels into cross validation folds and fit the model for
each fold. Then, for each scoring type in scorings, compute the score.
Finally, average the scores across folds. Returns a dictionary mapping
scoring to score.
... | entailment |
def get_contrib_features(project_root):
"""Get contributed features for a project at project_root
For a project ``foo``, walks modules within the ``foo.features.contrib``
subpackage. A single object that is an instance of ``ballet.Feature`` is
imported if present in each module. The resulting ``Feature... | Get contributed features for a project at project_root
For a project ``foo``, walks modules within the ``foo.features.contrib``
subpackage. A single object that is an instance of ``ballet.Feature`` is
imported if present in each module. The resulting ``Feature`` objects are
collected.
Args:
... | entailment |
def _get_contrib_features(module):
"""Get contributed features from within given module
Be very careful with untrusted code. The module/package will be
walked, every submodule will be imported, and all the code therein will be
executed. But why would you be trying to import from an untrusted package
... | Get contributed features from within given module
Be very careful with untrusted code. The module/package will be
walked, every submodule will be imported, and all the code therein will be
executed. But why would you be trying to import from an untrusted package
anyway?
Args:
contrib (modu... | entailment |
def quickstart():
"""Generate a brand-new ballet project"""
import ballet.templating
import ballet.util.log
ballet.util.log.enable(level='INFO',
format=ballet.util.log.SIMPLE_LOG_FORMAT,
echo=False)
ballet.templating.render_project_template() | Generate a brand-new ballet project | entailment |
def update_project_template(push):
"""Update an existing ballet project from the upstream template"""
import ballet.update
import ballet.util.log
ballet.util.log.enable(level='INFO',
format=ballet.util.log.SIMPLE_LOG_FORMAT,
echo=False)
ballet.up... | Update an existing ballet project from the upstream template | entailment |
def start_new_feature():
"""Start working on a new feature from a template"""
import ballet.templating
import ballet.util.log
ballet.util.log.enable(level='INFO',
format=ballet.util.log.SIMPLE_LOG_FORMAT,
echo=False)
ballet.templating.start_new_f... | Start working on a new feature from a template | entailment |
def write_tabular(obj, filepath):
"""Write tabular object in HDF5 or pickle format
Args:
obj (array or DataFrame): tabular object to write
filepath (path-like): path to write to; must end in '.h5' or '.pkl'
"""
_, fn, ext = splitext2(filepath)
if ext == '.h5':
_write_tabular... | Write tabular object in HDF5 or pickle format
Args:
obj (array or DataFrame): tabular object to write
filepath (path-like): path to write to; must end in '.h5' or '.pkl' | entailment |
def read_tabular(filepath):
"""Read tabular object in HDF5 or pickle format
Args:
filepath (path-like): path to read to; must end in '.h5' or '.pkl'
"""
_, fn, ext = splitext2(filepath)
if ext == '.h5':
return _read_tabular_h5(filepath)
elif ext == '.pkl':
return _read_t... | Read tabular object in HDF5 or pickle format
Args:
filepath (path-like): path to read to; must end in '.h5' or '.pkl' | entailment |
def load_table_from_config(input_dir, config):
"""Load table from table config dict
Args:
input_dir (path-like): directory containing input files
config (dict): mapping with keys 'name', 'path', and 'pd_read_kwargs'.
Returns:
pd.DataFrame
"""
path = pathlib.Path(input_dir).... | Load table from table config dict
Args:
input_dir (path-like): directory containing input files
config (dict): mapping with keys 'name', 'path', and 'pd_read_kwargs'.
Returns:
pd.DataFrame | entailment |
def validate_feature_api(project, force=False):
"""Validate feature API"""
if not force and not project.on_pr():
raise SkippedValidationTest('Not on PR')
validator = FeatureApiValidator(project)
result = validator.validate()
if not result:
raise InvalidFeatureApi | Validate feature API | entailment |
def evaluate_feature_performance(project, force=False):
"""Evaluate feature performance"""
if not force and not project.on_pr():
raise SkippedValidationTest('Not on PR')
out = project.build()
X_df, y, features = out['X_df'], out['y'], out['features']
proposed_feature = get_proposed_feature... | Evaluate feature performance | entailment |
def prune_existing_features(project, force=False):
"""Prune existing features"""
if not force and not project.on_master_after_merge():
raise SkippedValidationTest('Not on master')
out = project.build()
X_df, y, features = out['X_df'], out['y'], out['features']
proposed_feature = get_propose... | Prune existing features | entailment |
def validate(package, test_target_type=None):
"""Entrypoint for ./validate.py script in ballet projects"""
project = Project(package)
if test_target_type is None:
test_target_type = detect_target_type()
if test_target_type == BalletTestTypes.PROJECT_STRUCTURE_VALIDATION:
check_project_... | Entrypoint for ./validate.py script in ballet projects | entailment |
def spliceext(filepath, s):
"""Add s into filepath before the extension
Args:
filepath (str, path): file path
s (str): string to splice
Returns:
str
"""
root, ext = os.path.splitext(safepath(filepath))
return root + s + ext | Add s into filepath before the extension
Args:
filepath (str, path): file path
s (str): string to splice
Returns:
str | entailment |
def replaceext(filepath, new_ext):
"""Replace any existing file extension with a new one
Example::
>>> replaceext('/foo/bar.txt', 'py')
'/foo/bar.py'
>>> replaceext('/foo/bar.txt', '.doc')
'/foo/bar.doc'
Args:
filepath (str, path): file path
new_ext (str): ... | Replace any existing file extension with a new one
Example::
>>> replaceext('/foo/bar.txt', 'py')
'/foo/bar.py'
>>> replaceext('/foo/bar.txt', '.doc')
'/foo/bar.doc'
Args:
filepath (str, path): file path
new_ext (str): new file extension; if a leading dot is no... | entailment |
def splitext2(filepath):
"""Split filepath into root, filename, ext
Args:
filepath (str, path): file path
Returns:
str
"""
root, filename = os.path.split(safepath(filepath))
filename, ext = os.path.splitext(safepath(filename))
return root, filename, ext | Split filepath into root, filename, ext
Args:
filepath (str, path): file path
Returns:
str | entailment |
def isemptyfile(filepath):
"""Determine if the file both exists and isempty
Args:
filepath (str, path): file path
Returns:
bool
"""
exists = os.path.exists(safepath(filepath))
if exists:
filesize = os.path.getsize(safepath(filepath))
return filesize == 0
els... | Determine if the file both exists and isempty
Args:
filepath (str, path): file path
Returns:
bool | entailment |
def synctree(src, dst, onexist=None):
"""Recursively sync files at directory src to dst
This is more or less equivalent to::
cp -n -R ${src}/ ${dst}/
If a file at the same path exists in src and dst, it is NOT overwritten
in dst. Pass ``onexist`` in order to raise an error on such conditions.
... | Recursively sync files at directory src to dst
This is more or less equivalent to::
cp -n -R ${src}/ ${dst}/
If a file at the same path exists in src and dst, it is NOT overwritten
in dst. Pass ``onexist`` in order to raise an error on such conditions.
Args:
src (path-like): source di... | entailment |
def calculate_disc_entropy(X):
r"""Calculates the exact Shannon entropy of a discrete dataset,
using empirical probabilities according to the equation:
$ H(X) = -\sum(c \in X) p(c) \times \log(p(c)) $
Where $ p(c) $ is calculated as the frequency of c in X.
If X's columns logically represent contin... | r"""Calculates the exact Shannon entropy of a discrete dataset,
using empirical probabilities according to the equation:
$ H(X) = -\sum(c \in X) p(c) \times \log(p(c)) $
Where $ p(c) $ is calculated as the frequency of c in X.
If X's columns logically represent continuous features,
it is better to ... | entailment |
def estimate_cont_entropy(X, epsilon=None):
"""Estimate the Shannon entropy of a discrete dataset.
Based off the Kraskov Estimator [1] and Kozachenko [2]
estimators for a dataset's Shannon entropy.
The function relies on nonparametric methods based on entropy
estimation from k-nearest neighbors di... | Estimate the Shannon entropy of a discrete dataset.
Based off the Kraskov Estimator [1] and Kozachenko [2]
estimators for a dataset's Shannon entropy.
The function relies on nonparametric methods based on entropy
estimation from k-nearest neighbors distances as proposed
in [1] and augmented in [2]... | entailment |
def estimate_entropy(X, epsilon=None):
r"""Estimate a dataset's Shannon entropy.
This function can take datasets of mixed discrete and continuous
features, and uses a set of heuristics to determine which functions
to apply to each.
Because this function is a subroutine in a mutual information esti... | r"""Estimate a dataset's Shannon entropy.
This function can take datasets of mixed discrete and continuous
features, and uses a set of heuristics to determine which functions
to apply to each.
Because this function is a subroutine in a mutual information estimator,
we employ the Kozachenko Estimat... | entailment |
def _calculate_epsilon(X):
"""Calculates epsilon, a subroutine for the Kraskov Estimator [1]
Represents the chebyshev distance of each dataset element to its
K-th nearest neighbor.
Args:
X (array-like): An array with shape (n_samples, n_features)
Returns:
array-like: An array with ... | Calculates epsilon, a subroutine for the Kraskov Estimator [1]
Represents the chebyshev distance of each dataset element to its
K-th nearest neighbor.
Args:
X (array-like): An array with shape (n_samples, n_features)
Returns:
array-like: An array with shape (n_samples, 1) representing
... | entailment |
def estimate_conditional_information(x, y, z):
""" Estimate the conditional mutual information of three datasets.
Conditional mutual information is the
mutual information of two datasets, given a third:
$ I(x;y|z) = H(x,z) + H(y,z) - H(x,y,z) - H(z) $
Where H(x) is the Shannon entropy of x. F... | Estimate the conditional mutual information of three datasets.
Conditional mutual information is the
mutual information of two datasets, given a third:
$ I(x;y|z) = H(x,z) + H(y,z) - H(x,y,z) - H(z) $
Where H(x) is the Shannon entropy of x. For continuous datasets,
adapts the Kraskov Estimato... | entailment |
def estimate_mutual_information(x, y):
"""Estimate the mutual information of two datasets.
Mutual information is a measure of dependence between
two datasets and is calculated as:
$I(x;y) = H(x) + H(y) - H(x,y)$
Where H(x) is the Shannon entropy of x. For continuous datasets,
adapts the K... | Estimate the mutual information of two datasets.
Mutual information is a measure of dependence between
two datasets and is calculated as:
$I(x;y) = H(x) + H(y) - H(x,y)$
Where H(x) is the Shannon entropy of x. For continuous datasets,
adapts the Kraskov Estimator [1] for mutual information.
... | entailment |
def get_diff_endpoints_from_commit_range(repo, commit_range):
"""Get endpoints of a diff given a commit range
The resulting endpoints can be diffed directly::
a, b = get_diff_endpoints_from_commit_range(repo, commit_range)
a.diff(b)
For details on specifying git diffs, see ``git diff --he... | Get endpoints of a diff given a commit range
The resulting endpoints can be diffed directly::
a, b = get_diff_endpoints_from_commit_range(repo, commit_range)
a.diff(b)
For details on specifying git diffs, see ``git diff --help``.
For details on specifying revisions, see ``git help revisio... | entailment |
def set_config_variables(repo, variables):
"""Set config variables
Args:
repo (git.Repo): repo
variables (dict): entries of the form 'user.email': 'you@example.com'
"""
with repo.config_writer() as writer:
for k, value in variables.items():
section, option = k.split(... | Set config variables
Args:
repo (git.Repo): repo
variables (dict): entries of the form 'user.email': 'you@example.com' | entailment |
def validate(self):
"""Collect and validate all new features"""
changes = self.change_collector.collect_changes()
features = []
imported_okay = True
for importer, modname, modpath in changes.new_feature_info:
try:
mod = importer()
fea... | Collect and validate all new features | entailment |
def load_config_at_path(path):
"""Load config at exact path
Args:
path (path-like): path to config file
Returns:
dict: config dict
"""
if path.exists() and path.is_file():
with path.open('r') as f:
return yaml.load(f, Loader=yaml.SafeLoader)
else:
ra... | Load config at exact path
Args:
path (path-like): path to config file
Returns:
dict: config dict | entailment |
def config_get(config, *path, default=None):
"""Get a configuration option following a path through the config
Example usage:
>>> config_get(config,
'problem', 'problem_type_details', 'scorer',
default='accuracy')
Args:
config (dict): config d... | Get a configuration option following a path through the config
Example usage:
>>> config_get(config,
'problem', 'problem_type_details', 'scorer',
default='accuracy')
Args:
config (dict): config dict
*path (list[str]): List of config sectio... | entailment |
def make_config_get(conf_path):
"""Return a function to get configuration options for a specific project
Args:
conf_path (path-like): path to project's conf file (i.e. foo.conf
module)
"""
project_root = _get_project_root_from_conf_path(conf_path)
config = load_config_in_dir(pro... | Return a function to get configuration options for a specific project
Args:
conf_path (path-like): path to project's conf file (i.e. foo.conf
module) | entailment |
def relative_to_contrib(diff, project):
"""Compute relative path of changed file to contrib dir
Args:
diff (git.diff.Diff): file diff
project (Project): project
Returns:
Path
"""
path = pathlib.Path(diff.b_path)
contrib_path = project.contrib_module_path
return path... | Compute relative path of changed file to contrib dir
Args:
diff (git.diff.Diff): file diff
project (Project): project
Returns:
Path | entailment |
def pr_num(self):
"""Return the PR number or None if not on a PR"""
result = get_pr_num(repo=self.repo)
if result is None:
result = get_travis_pr_num()
return result | Return the PR number or None if not on a PR | entailment |
def branch(self):
"""Return whether the project is on master branch"""
result = get_branch(repo=self.repo)
if result is None:
result = get_travis_branch()
return result | Return whether the project is on master branch | entailment |
def path(self):
"""Return the project path (aka project root)
If ``package.__file__`` is ``/foo/foo/__init__.py``, then project.path
should be ``/foo``.
"""
return pathlib.Path(self.package.__file__).resolve().parent.parent | Return the project path (aka project root)
If ``package.__file__`` is ``/foo/foo/__init__.py``, then project.path
should be ``/foo``. | entailment |
def asarray2d(a):
"""Cast to 2d array"""
arr = np.asarray(a)
if arr.ndim == 1:
arr = arr.reshape(-1, 1)
return arr | Cast to 2d array | entailment |
def get_arr_desc(arr):
"""Get array description, in the form '<array type> <array shape>'"""
type_ = type(arr).__name__ # see also __qualname__
shape = getattr(arr, 'shape', None)
if shape is not None:
desc = '{type_} {shape}'
else:
desc = '{type_} <no shape>'
return desc.format... | Get array description, in the form '<array type> <array shape> | entailment |
def indent(text, n=4):
"""Indent each line of text by n spaces"""
_indent = ' ' * n
return '\n'.join(_indent + line for line in text.split('\n')) | Indent each line of text by n spaces | entailment |
def has_nans(obj):
"""Check if obj has any NaNs
Compatible with different behavior of np.isnan, which sometimes applies
over all axes (py35, py35) and sometimes does not (py34).
"""
nans = np.isnan(obj)
while np.ndim(nans):
nans = np.any(nans)
return bool(nans) | Check if obj has any NaNs
Compatible with different behavior of np.isnan, which sometimes applies
over all axes (py35, py35) and sometimes does not (py34). | entailment |
def needs_path(f):
"""Wraps a function that accepts path-like to give it a pathlib.Path"""
@wraps(f)
def wrapped(pathlike, *args, **kwargs):
path = pathlib.Path(pathlike)
return f(path, *args, **kwargs)
return wrapped | Wraps a function that accepts path-like to give it a pathlib.Path | entailment |
def import_module_at_path(modname, modpath):
"""Import module from path that may not be on system path
Args:
modname (str): module name from package root, e.g. foo.bar
modpath (str): absolute path to module itself,
e.g. /home/user/foo/bar.py. In the case of a module that is a
... | Import module from path that may not be on system path
Args:
modname (str): module name from package root, e.g. foo.bar
modpath (str): absolute path to module itself,
e.g. /home/user/foo/bar.py. In the case of a module that is a
package, then the path should be specified as ... | entailment |
def relpath_to_modname(relpath):
"""Convert relative path to module name
Within a project, a path to the source file is uniquely identified with a
module name. Relative paths of the form 'foo/bar' are *not* converted to
module names 'foo.bar', because (1) they identify directories, not regular
file... | Convert relative path to module name
Within a project, a path to the source file is uniquely identified with a
module name. Relative paths of the form 'foo/bar' are *not* converted to
module names 'foo.bar', because (1) they identify directories, not regular
files, and (2) already 'foo/bar/__init__.py'... | entailment |
def modname_to_relpath(modname, project_root=None, add_init=True):
"""Convert module name to relative path.
The project root is usually needed to detect if the module is a package, in
which case the relevant file is the `__init__.py` within the subdirectory.
Example:
>>> modname_to_relpath('fo... | Convert module name to relative path.
The project root is usually needed to detect if the module is a package, in
which case the relevant file is the `__init__.py` within the subdirectory.
Example:
>>> modname_to_relpath('foo.features')
'foo/features.py'
>>> modname_to_relpath('foo... | entailment |
def check(self, feature):
"""Check that the feature's `input` is a str or Iterable[str]"""
input = feature.input
is_str = isa(str)
is_nested_str = all_fn(
iterable, lambda x: all(is_str, x))
assert is_str(input) or is_nested_str(input) | Check that the feature's `input` is a str or Iterable[str] | entailment |
def check(self, feature):
"""Check that the feature has a fit/transform/fit_tranform interface"""
assert hasattr(feature.transformer, 'fit')
assert hasattr(feature.transformer, 'transform')
assert hasattr(feature.transformer, 'fit_transform') | Check that the feature has a fit/transform/fit_tranform interface | entailment |
def check(self, feature):
"""Check that fit can be called on reference data"""
mapper = feature.as_dataframe_mapper()
mapper.fit(self.X, y=self.y) | Check that fit can be called on reference data | entailment |
def check(self, feature):
"""Check that fit_transform can be called on reference data"""
mapper = feature.as_dataframe_mapper()
mapper.fit_transform(self.X, y=self.y) | Check that fit_transform can be called on reference data | entailment |
def check(self, feature):
"""Check that the dimensions of the transformed data are correct
For input X, an n x p array, a n x q array should be produced,
where q is the number of features produced by the logical feature.
"""
mapper = feature.as_dataframe_mapper()
X = map... | Check that the dimensions of the transformed data are correct
For input X, an n x p array, a n x q array should be produced,
where q is the number of features produced by the logical feature. | entailment |
def check(self, feature):
"""Check that the feature can be pickled
This is needed for saving the pipeline to disk
"""
try:
buf = io.BytesIO()
pickle.dump(feature, buf, protocol=pickle.HIGHEST_PROTOCOL)
buf.seek(0)
new_feature = pickle.load... | Check that the feature can be pickled
This is needed for saving the pipeline to disk | entailment |
def check(self, feature):
"""Check that the output of the transformer has no missing values"""
mapper = feature.as_dataframe_mapper()
X = mapper.fit_transform(self.X, y=self.y)
assert not np.any(np.isnan(X)) | Check that the output of the transformer has no missing values | entailment |
def make_multi_lagger(lags, groupby_kwargs=None):
"""Return a union of transformers that apply different lags
Args:
lags (Collection[int]): collection of lags to apply
groupby_kwargs (dict): keyword arguments to pd.DataFrame.groupby
"""
laggers = [SingleLagger(l, groupby_kwargs=groupby_... | Return a union of transformers that apply different lags
Args:
lags (Collection[int]): collection of lags to apply
groupby_kwargs (dict): keyword arguments to pd.DataFrame.groupby | entailment |
def start_new_feature(**cc_kwargs):
"""Start a new feature within a ballet project
Renders the feature template into a temporary directory, then copies the
feature files into the proper path within the contrib directory.
Args:
**cc_kwargs: options for the cookiecutter template
Raises:
... | Start a new feature within a ballet project
Renders the feature template into a temporary directory, then copies the
feature files into the proper path within the contrib directory.
Args:
**cc_kwargs: options for the cookiecutter template
Raises:
ballet.exc.BalletError: the new featur... | entailment |
def get_proposed_feature(project):
"""Get the proposed feature
The path of the proposed feature is determined by diffing the project
against a comparison branch, such as master. The feature is then imported
from that path and returned.
Args:
project (ballet.project.Project): project info
... | Get the proposed feature
The path of the proposed feature is determined by diffing the project
against a comparison branch, such as master. The feature is then imported
from that path and returned.
Args:
project (ballet.project.Project): project info
Raises:
ballet.exc.BalletError... | entailment |
def get_accepted_features(features, proposed_feature):
"""Deselect candidate features from list of all features
Args:
features (List[Feature]): collection of all features in the ballet
project: both accepted features and candidate ones that have not
been accepted
propose... | Deselect candidate features from list of all features
Args:
features (List[Feature]): collection of all features in the ballet
project: both accepted features and candidate ones that have not
been accepted
proposed_feature (Feature): candidate feature that has not been
... | entailment |
def collect_changes(self):
"""Collect file and feature changes
Steps
1. Collects the files that have changed in this pull request as
compared to a comparison branch.
2. Categorize these file changes into admissible or inadmissible file
changes. Admissible file chan... | Collect file and feature changes
Steps
1. Collects the files that have changed in this pull request as
compared to a comparison branch.
2. Categorize these file changes into admissible or inadmissible file
changes. Admissible file changes solely contribute python files to
... | entailment |
def _categorize_file_diffs(self, file_diffs):
"""Partition file changes into admissible and inadmissible changes"""
# TODO move this into a new validator
candidate_feature_diffs = []
valid_init_diffs = []
inadmissible_files = []
for diff in file_diffs:
valid,... | Partition file changes into admissible and inadmissible changes | entailment |
def _collect_feature_info(self, candidate_feature_diffs):
"""Collect feature info
Args:
candidate_feature_diffs (List[git.diff.Diff]): list of Diffs
corresponding to admissible file changes compared to
comparison ref
Returns:
List[Tuple]:... | Collect feature info
Args:
candidate_feature_diffs (List[git.diff.Diff]): list of Diffs
corresponding to admissible file changes compared to
comparison ref
Returns:
List[Tuple]: list of tuple of importer, module name, and module
p... | entailment |
def get_travis_branch():
"""Get current branch per Travis environment variables
If travis is building a PR, then TRAVIS_PULL_REQUEST is truthy and the
name of the branch corresponding to the PR is stored in the
TRAVIS_PULL_REQUEST_BRANCH environment variable. Else, the name of the
branch is stored ... | Get current branch per Travis environment variables
If travis is building a PR, then TRAVIS_PULL_REQUEST is truthy and the
name of the branch corresponding to the PR is stored in the
TRAVIS_PULL_REQUEST_BRANCH environment variable. Else, the name of the
branch is stored in the TRAVIS_BRANCH environment... | entailment |
def make_mapper(features):
"""Make a DataFrameMapper from a feature or list of features
Args:
features (Union[Feature, List[Feature]]): feature or list of features
Returns:
DataFrameMapper: mapper made from features
"""
if not features:
features = Feature(input=[], transfor... | Make a DataFrameMapper from a feature or list of features
Args:
features (Union[Feature, List[Feature]]): feature or list of features
Returns:
DataFrameMapper: mapper made from features | entailment |
def _name_estimators(estimators):
"""Generate names for estimators.
Adapted from sklearn.pipeline._name_estimators
"""
def get_name(estimator):
if isinstance(estimator, DelegatingRobustTransformer):
return get_name(estimator._transformer)
return type(estimator).__name__.lo... | Generate names for estimators.
Adapted from sklearn.pipeline._name_estimators | entailment |
def _push(project):
"""Push default branch and project template branch to remote
With default config (i.e. remote and branch names), equivalent to::
$ git push origin master:master project-template:project-template
Raises:
ballet.exc.BalletError: Push failed in some way
"""
repo =... | Push default branch and project template branch to remote
With default config (i.e. remote and branch names), equivalent to::
$ git push origin master:master project-template:project-template
Raises:
ballet.exc.BalletError: Push failed in some way | entailment |
def build(X_df=None, y_df=None):
"""Build features and target
Args:
X_df (DataFrame): raw variables
y_df (DataFrame): raw target
Returns:
dict with keys X_df, features, mapper_X, X, y_df, encoder_y, y
"""
if X_df is None:
X_df, _ = load_data()
if y_df is None:
... | Build features and target
Args:
X_df (DataFrame): raw variables
y_df (DataFrame): raw target
Returns:
dict with keys X_df, features, mapper_X, X, y_df, encoder_y, y | entailment |
def main(input_dir, output_dir):
"""Engineer features"""
import ballet.util.log
ballet.util.log.enable(logger=logger, level='INFO', echo=False)
ballet.util.log.enable(logger=ballet.util.log.logger, level='INFO',
echo=False)
X_df, y_df = load_data(input_dir=input_dir)
... | Engineer features | entailment |
def load_data(input_dir=None):
"""Load data"""
if input_dir is not None:
tables = conf.get('tables')
entities_table_name = conf.get('data', 'entities_table_name')
entities_config = some(where(tables, name=entities_table_name))
X = load_table_from_config(input_dir, entities_confi... | Load data | entailment |
def _write_header(self, epoch_data: EpochData) -> None:
"""
Write CSV header row with column names.
Column names are inferred from the ``epoch_data`` and ``self.variables`` (if specified).
Variables and streams expected later on are stored in ``self._variables`` and ``self._streams`` re... | Write CSV header row with column names.
Column names are inferred from the ``epoch_data`` and ``self.variables`` (if specified).
Variables and streams expected later on are stored in ``self._variables`` and ``self._streams`` respectively.
:param epoch_data: epoch data to be logged | entailment |
def _write_row(self, epoch_id: int, epoch_data: EpochData) -> None:
"""
Write a single epoch result row to the CSV file.
:param epoch_id: epoch number (will be written at the first column)
:param epoch_data: epoch data
:raise KeyError: if the variable is missing and ``self._on_m... | Write a single epoch result row to the CSV file.
:param epoch_id: epoch number (will be written at the first column)
:param epoch_data: epoch data
:raise KeyError: if the variable is missing and ``self._on_missing_variable`` is set to ``error``
:raise TypeError: if the variable has wron... | entailment |
def after_epoch(self, epoch_id: int, epoch_data: EpochData) -> None:
"""
Write a new row to the CSV file with the given epoch data.
In the case of first invocation, create the CSV header.
:param epoch_id: number of the epoch
:param epoch_data: epoch data to be logged
""... | Write a new row to the CSV file with the given epoch data.
In the case of first invocation, create the CSV header.
:param epoch_id: number of the epoch
:param epoch_data: epoch data to be logged | entailment |
def get_random_name(sep: str='-'):
"""
Generate random docker-like name with the given separator.
:param sep: adjective-name separator string
:return: random docker-like name
"""
r = random.SystemRandom()
return '{}{}{}'.format(r.choice(_left), sep, r.choice(_right)) | Generate random docker-like name with the given separator.
:param sep: adjective-name separator string
:return: random docker-like name | entailment |
def _check_train_time(self) -> None:
"""
Stop the training if the training time exceeded ``self._minutes``.
:raise TrainingTerminated: if the training time exceeded ``self._minutes``
"""
if self._minutes is not None and (datetime.now() - self._training_start).total_seconds()/60 ... | Stop the training if the training time exceeded ``self._minutes``.
:raise TrainingTerminated: if the training time exceeded ``self._minutes`` | entailment |
def after_batch(self, stream_name: str, batch_data: Batch) -> None:
"""
If ``stream_name`` equals to :py:attr:`cxflow.constants.TRAIN_STREAM`,
increase the iterations counter and possibly stop the training; additionally, call :py:meth:`_check_train_time`.
:param stream_name: stream name... | If ``stream_name`` equals to :py:attr:`cxflow.constants.TRAIN_STREAM`,
increase the iterations counter and possibly stop the training; additionally, call :py:meth:`_check_train_time`.
:param stream_name: stream name
:param batch_data: ignored
:raise TrainingTerminated: if the number of ... | entailment |
def after_epoch(self, epoch_id: int, epoch_data: EpochData) -> None:
"""
Stop the training if the ``epoch_id`` reaches ``self._epochs``; additionally, call :py:meth:`_check_train_time`.
:param epoch_id: epoch id
:param epoch_data: ignored
:raise TrainingTerminated: if the ``epoc... | Stop the training if the ``epoch_id`` reaches ``self._epochs``; additionally, call :py:meth:`_check_train_time`.
:param epoch_id: epoch id
:param epoch_data: ignored
:raise TrainingTerminated: if the ``epoch_id`` reaches ``self._epochs`` | entailment |
def sanitize_url(url: str) -> str:
"""
Sanitize the given url so that it can be used as a valid filename.
:param url: url to create filename from
:raise ValueError: when the given url can not be sanitized
:return: created filename
"""
for part in reversed(url.split('/')):
filename ... | Sanitize the given url so that it can be used as a valid filename.
:param url: url to create filename from
:raise ValueError: when the given url can not be sanitized
:return: created filename | entailment |
def maybe_download_and_extract(data_root: str, url: str) -> None:
"""
Maybe download the specified file to ``data_root`` and try to unpack it with ``shutil.unpack_archive``.
:param data_root: data root to download the files to
:param url: url to download from
"""
# make sure data_root exis... | Maybe download the specified file to ``data_root`` and try to unpack it with ``shutil.unpack_archive``.
:param data_root: data root to download the files to
:param url: url to download from | entailment |
def _raise_check_aggregation(aggregation: str):
"""
Check whether the given aggregation is present in NumPy or it is one of EXTRA_AGGREGATIONS.
:param aggregation: the aggregation name
:raise ValueError: if the specified aggregation is not supported or found in NumPy
"""
... | Check whether the given aggregation is present in NumPy or it is one of EXTRA_AGGREGATIONS.
:param aggregation: the aggregation name
:raise ValueError: if the specified aggregation is not supported or found in NumPy | entailment |
def _compute_aggregation(aggregation: str, data: Iterable[Any]):
"""
Compute the specified aggregation on the given data.
:param aggregation: the name of an arbitrary NumPy function (e.g., mean, max, median, nanmean, ...)
or one of :py:attr:`EXTRA_AGGREGATIONS`.
... | Compute the specified aggregation on the given data.
:param aggregation: the name of an arbitrary NumPy function (e.g., mean, max, median, nanmean, ...)
or one of :py:attr:`EXTRA_AGGREGATIONS`.
:param data: data to be aggregated
:raise ValueError: if the specified ag... | entailment |
def _save_stats(self, epoch_data: EpochData) -> None:
"""
Extend ``epoch_data`` by stream:variable:aggreagation data.
:param epoch_data: data source from which the statistics are computed
"""
for stream_name in epoch_data.keys():
for variable, aggregations in self._... | Extend ``epoch_data`` by stream:variable:aggreagation data.
:param epoch_data: data source from which the statistics are computed | entailment |
def after_epoch(self, epoch_data: EpochData, **kwargs) -> None:
"""
Compute the specified aggregations and save them to the given epoch data.
:param epoch_data: epoch data to be processed
"""
self._save_stats(epoch_data)
super().after_epoch(epoch_data=epoch_data, **kwarg... | Compute the specified aggregations and save them to the given epoch data.
:param epoch_data: epoch data to be processed | entailment |
def save(self) -> None:
"""
Save the training trace to :py:attr:`CXF_TRACE_FILE` file under the specified directory.
:raise ValueError: if no output directory was specified
"""
if self._output_dir is None:
raise ValueError('Can not save TrainingTrace without output d... | Save the training trace to :py:attr:`CXF_TRACE_FILE` file under the specified directory.
:raise ValueError: if no output directory was specified | entailment |
def from_file(filepath: str):
"""
Load training trace from the given ``filepath``.
:param filepath: training trace file path
:return: training trace
"""
trace = TrainingTrace()
trace._trace = load_config(filepath)
return trace | Load training trace from the given ``filepath``.
:param filepath: training trace file path
:return: training trace | entailment |
def after_epoch(self, epoch_id: int, epoch_data: EpochData):
"""
Check termination conditions.
:param epoch_id: number of the processed epoch
:param epoch_data: epoch data to be checked
:raise KeyError: if the stream of variable was not found in ``epoch_data``
:raise Typ... | Check termination conditions.
:param epoch_id: number of the processed epoch
:param epoch_data: epoch data to be checked
:raise KeyError: if the stream of variable was not found in ``epoch_data``
:raise TypeError: if the monitored variable is not a scalar or scalar ``mean`` aggregation
... | entailment |
def train(config_path: str, cl_arguments: Iterable[str], output_root: str) -> None:
"""
Load config and start the training.
:param config_path: path to configuration file
:param cl_arguments: additional command line arguments which will update the configuration
:param output_root: output root in wh... | Load config and start the training.
:param config_path: path to configuration file
:param cl_arguments: additional command line arguments which will update the configuration
:param output_root: output root in which the training directory will be created | entailment |
def evaluate(model_path: str, stream_name: str, config_path: Optional[str], cl_arguments: Iterable[str],
output_root: str) -> None:
"""
Evaluate the given model on the specified data stream.
Configuration is updated by the respective predict.stream_name section, in particular:
- hooks ... | Evaluate the given model on the specified data stream.
Configuration is updated by the respective predict.stream_name section, in particular:
- hooks section is entirely replaced
- model and dataset sections are updated
:param model_path: path to the model to be evaluated
:param stream_nam... | entailment |
def predict(config_path: str, restore_from: Optional[str], cl_arguments: Iterable[str], output_root: str) -> None:
"""
Run prediction from the specified config path.
If the config contains a ``predict`` section:
- override hooks with ``predict.hooks`` if present
- update dataset, model and ... | Run prediction from the specified config path.
If the config contains a ``predict`` section:
- override hooks with ``predict.hooks`` if present
- update dataset, model and main loop sections if the respective sections are present
:param config_path: path to the config file or the directory in ... | entailment |
def _create_epoch_data(self, streams: Optional[Iterable[str]]=None) -> EpochData:
"""Create empty epoch data double dict."""
if streams is None:
streams = [self._train_stream_name] + self._extra_streams
return OrderedDict([(stream_name, OrderedDict()) for stream_name in streams]) | Create empty epoch data double dict. | entailment |
def _check_sources(self, batch: Dict[str, object]) -> None:
"""
Check for unused and missing sources.
:param batch: batch to be checked
:raise ValueError: if a source is missing or unused and ``self._on_unused_sources`` is set to ``error``
"""
unused_sources = [source fo... | Check for unused and missing sources.
:param batch: batch to be checked
:raise ValueError: if a source is missing or unused and ``self._on_unused_sources`` is set to ``error`` | entailment |
def _run_epoch(self, stream: StreamWrapper, train: bool) -> None:
"""
Iterate through the given stream and evaluate/train the model with the received batches.
Calls :py:meth:`cxflow.hooks.AbstractHook.after_batch` events.
:param stream: stream to iterate
:param train: if set to... | Iterate through the given stream and evaluate/train the model with the received batches.
Calls :py:meth:`cxflow.hooks.AbstractHook.after_batch` events.
:param stream: stream to iterate
:param train: if set to ``True``, the model will be trained
:raise ValueError: in case of empty batch... | entailment |
def train_by_stream(self, stream: StreamWrapper) -> None:
"""
Train the model with the given stream.
:param stream: stream to train with
"""
self._run_epoch(stream=stream, train=True) | Train the model with the given stream.
:param stream: stream to train with | entailment |
def evaluate_stream(self, stream: StreamWrapper) -> None:
"""
Evaluate the given stream.
:param stream: stream to be evaluated
:param stream_name: stream name
"""
self._run_epoch(stream=stream, train=False) | Evaluate the given stream.
:param stream: stream to be evaluated
:param stream_name: stream name | entailment |
def get_stream(self, stream_name: str) -> StreamWrapper:
"""
Get a :py:class:`StreamWrapper` with the given name.
:param stream_name: stream name
:return: dataset function name providing the respective stream
:raise AttributeError: if the dataset does not provide the function cr... | Get a :py:class:`StreamWrapper` with the given name.
:param stream_name: stream name
:return: dataset function name providing the respective stream
:raise AttributeError: if the dataset does not provide the function creating the stream | entailment |
def _run_zeroth_epoch(self, streams: Iterable[str]) -> None:
"""
Run zeroth epoch on the specified streams.
Calls
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch`
:param streams: stream names to be evaluated
"""
for stream_name in streams:
with... | Run zeroth epoch on the specified streams.
Calls
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch`
:param streams: stream names to be evaluated | entailment |
def _try_run(self, run_func: Callable[[], None]) -> None:
"""
Try running the given function (training/prediction).
Calls
- :py:meth:`cxflow.hooks.AbstractHook.before_training`
- :py:meth:`cxflow.hooks.AbstractHook.after_training`
:param run_func: function to be... | Try running the given function (training/prediction).
Calls
- :py:meth:`cxflow.hooks.AbstractHook.before_training`
- :py:meth:`cxflow.hooks.AbstractHook.after_training`
:param run_func: function to be run | entailment |
def run_training(self, trace: Optional[TrainingTrace]=None) -> None:
"""
Run the main loop in the training mode.
Calls
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch`
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch_profile`
"""
for stream_name in [se... | Run the main loop in the training mode.
Calls
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch`
- :py:meth:`cxflow.hooks.AbstractHook.after_epoch_profile` | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.