INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Get the number of rows in the Dataset.
Returns
-------
number_of_rows : int
The number of rows in the Dataset. | def num_data(self):
"""Get the number of rows in the Dataset.
Returns
-------
number_of_rows : int
The number of rows in the Dataset.
"""
if self.handle is not None:
ret = ctypes.c_int()
_safe_call(_LIB.LGBM_DatasetGetNumData(self.hand... |
Get the number of columns (features) in the Dataset.
Returns
-------
number_of_columns : int
The number of columns (features) in the Dataset. | def num_feature(self):
"""Get the number of columns (features) in the Dataset.
Returns
-------
number_of_columns : int
The number of columns (features) in the Dataset.
"""
if self.handle is not None:
ret = ctypes.c_int()
_safe_call(_LI... |
Get a chain of Dataset objects.
Starts with r, then goes to r.reference (if exists),
then to r.reference.reference, etc.
until we hit ``ref_limit`` or a reference loop.
Parameters
----------
ref_limit : int, optional (default=100)
The limit number of referen... | def get_ref_chain(self, ref_limit=100):
"""Get a chain of Dataset objects.
Starts with r, then goes to r.reference (if exists),
then to r.reference.reference, etc.
until we hit ``ref_limit`` or a reference loop.
Parameters
----------
ref_limit : int, optional (d... |
Save Dataset to a text file.
This format cannot be loaded back in by LightGBM, but is useful for debugging purposes.
Parameters
----------
filename : string
Name of the output file.
Returns
-------
self : Dataset
Returns self. | def dump_text(self, filename):
"""Save Dataset to a text file.
This format cannot be loaded back in by LightGBM, but is useful for debugging purposes.
Parameters
----------
filename : string
Name of the output file.
Returns
-------
self : Da... |
Free Booster's Datasets.
Returns
-------
self : Booster
Booster without Datasets. | def free_dataset(self):
"""Free Booster's Datasets.
Returns
-------
self : Booster
Booster without Datasets.
"""
self.__dict__.pop('train_set', None)
self.__dict__.pop('valid_sets', None)
self.__num_dataset = 0
return self |
Set the network configuration.
Parameters
----------
machines : list, set or string
Names of machines.
local_listen_port : int, optional (default=12400)
TCP listen port for local machines.
listen_time_out : int, optional (default=120)
Socket t... | def set_network(self, machines, local_listen_port=12400,
listen_time_out=120, num_machines=1):
"""Set the network configuration.
Parameters
----------
machines : list, set or string
Names of machines.
local_listen_port : int, optional (default=124... |
Add validation data.
Parameters
----------
data : Dataset
Validation data.
name : string
Name of validation data.
Returns
-------
self : Booster
Booster with set validation data. | def add_valid(self, data, name):
"""Add validation data.
Parameters
----------
data : Dataset
Validation data.
name : string
Name of validation data.
Returns
-------
self : Booster
Booster with set validation data.
... |
Reset parameters of Booster.
Parameters
----------
params : dict
New parameters for Booster.
Returns
-------
self : Booster
Booster with new parameters. | def reset_parameter(self, params):
"""Reset parameters of Booster.
Parameters
----------
params : dict
New parameters for Booster.
Returns
-------
self : Booster
Booster with new parameters.
"""
if any(metric_alias in para... |
Update Booster for one iteration.
Parameters
----------
train_set : Dataset or None, optional (default=None)
Training data.
If None, last training data is used.
fobj : callable or None, optional (default=None)
Customized objective function.
... | def update(self, train_set=None, fobj=None):
"""Update Booster for one iteration.
Parameters
----------
train_set : Dataset or None, optional (default=None)
Training data.
If None, last training data is used.
fobj : callable or None, optional (default=Non... |
Boost Booster for one iteration with customized gradient statistics.
Note
----
For multi-class task, the score is group by class_id first, then group by row_id.
If you want to get i-th row score in j-th class, the access way is score[j * num_data + i]
and you should group grad a... | def __boost(self, grad, hess):
"""Boost Booster for one iteration with customized gradient statistics.
Note
----
For multi-class task, the score is group by class_id first, then group by row_id.
If you want to get i-th row score in j-th class, the access way is score[j * num_dat... |
Rollback one iteration.
Returns
-------
self : Booster
Booster with rolled back one iteration. | def rollback_one_iter(self):
"""Rollback one iteration.
Returns
-------
self : Booster
Booster with rolled back one iteration.
"""
_safe_call(_LIB.LGBM_BoosterRollbackOneIter(
self.handle))
self.__is_predicted_cur_iter = [False for _ in ra... |
Get the index of the current iteration.
Returns
-------
cur_iter : int
The index of the current iteration. | def current_iteration(self):
"""Get the index of the current iteration.
Returns
-------
cur_iter : int
The index of the current iteration.
"""
out_cur_iter = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterGetCurrentIteration(
self.handle,
... |
Get number of models per iteration.
Returns
-------
model_per_iter : int
The number of models per iteration. | def num_model_per_iteration(self):
"""Get number of models per iteration.
Returns
-------
model_per_iter : int
The number of models per iteration.
"""
model_per_iter = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterNumModelPerIteration(
self.... |
Get number of weak sub-models.
Returns
-------
num_trees : int
The number of weak sub-models. | def num_trees(self):
"""Get number of weak sub-models.
Returns
-------
num_trees : int
The number of weak sub-models.
"""
num_trees = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterNumberOfTotalModel(
self.handle,
ctypes.byref(num... |
Evaluate for data.
Parameters
----------
data : Dataset
Data for the evaluating.
name : string
Name of the data.
feval : callable or None, optional (default=None)
Customized evaluation function.
Should accept two parameters: preds,... | def eval(self, data, name, feval=None):
"""Evaluate for data.
Parameters
----------
data : Dataset
Data for the evaluating.
name : string
Name of the data.
feval : callable or None, optional (default=None)
Customized evaluation functio... |
Evaluate for validation data.
Parameters
----------
feval : callable or None, optional (default=None)
Customized evaluation function.
Should accept two parameters: preds, train_data,
and return (eval_name, eval_result, is_higher_better) or list of such tuples... | def eval_valid(self, feval=None):
"""Evaluate for validation data.
Parameters
----------
feval : callable or None, optional (default=None)
Customized evaluation function.
Should accept two parameters: preds, train_data,
and return (eval_name, eval_res... |
Save Booster to file.
Parameters
----------
filename : string
Filename to save Booster.
num_iteration : int or None, optional (default=None)
Index of the iteration that should be saved.
If None, if the best iteration exists, it is saved; otherwise, al... | def save_model(self, filename, num_iteration=None, start_iteration=0):
"""Save Booster to file.
Parameters
----------
filename : string
Filename to save Booster.
num_iteration : int or None, optional (default=None)
Index of the iteration that should be sa... |
Shuffle models.
Parameters
----------
start_iteration : int, optional (default=0)
The first iteration that will be shuffled.
end_iteration : int, optional (default=-1)
The last iteration that will be shuffled.
If <= 0, means the last available iterati... | def shuffle_models(self, start_iteration=0, end_iteration=-1):
"""Shuffle models.
Parameters
----------
start_iteration : int, optional (default=0)
The first iteration that will be shuffled.
end_iteration : int, optional (default=-1)
The last iteration th... |
Load Booster from a string.
Parameters
----------
model_str : string
Model will be loaded from this string.
verbose : bool, optional (default=True)
Whether to print messages while loading model.
Returns
-------
self : Booster
... | def model_from_string(self, model_str, verbose=True):
"""Load Booster from a string.
Parameters
----------
model_str : string
Model will be loaded from this string.
verbose : bool, optional (default=True)
Whether to print messages while loading model.
... |
Save Booster to string.
Parameters
----------
num_iteration : int or None, optional (default=None)
Index of the iteration that should be saved.
If None, if the best iteration exists, it is saved; otherwise, all iterations are saved.
If <= 0, all iterations ar... | def model_to_string(self, num_iteration=None, start_iteration=0):
"""Save Booster to string.
Parameters
----------
num_iteration : int or None, optional (default=None)
Index of the iteration that should be saved.
If None, if the best iteration exists, it is saved... |
Dump Booster to JSON format.
Parameters
----------
num_iteration : int or None, optional (default=None)
Index of the iteration that should be dumped.
If None, if the best iteration exists, it is dumped; otherwise, all iterations are dumped.
If <= 0, all itera... | def dump_model(self, num_iteration=None, start_iteration=0):
"""Dump Booster to JSON format.
Parameters
----------
num_iteration : int or None, optional (default=None)
Index of the iteration that should be dumped.
If None, if the best iteration exists, it is dump... |
Make a prediction.
Parameters
----------
data : string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.sparse
Data source for prediction.
If string, it represents the path to txt file.
num_iteration : int or None, optional (default=None)
... | def predict(self, data, num_iteration=None,
raw_score=False, pred_leaf=False, pred_contrib=False,
data_has_header=False, is_reshape=True, **kwargs):
"""Make a prediction.
Parameters
----------
data : string, numpy array, pandas DataFrame, H2O DataTable's ... |
Refit the existing Booster by new data.
Parameters
----------
data : string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.sparse
Data source for refit.
If string, it represents the path to txt file.
label : list, numpy 1-D array or pandas Series ... | def refit(self, data, label, decay_rate=0.9, **kwargs):
"""Refit the existing Booster by new data.
Parameters
----------
data : string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.sparse
Data source for refit.
If string, it represents the path t... |
Get the output of a leaf.
Parameters
----------
tree_id : int
The index of the tree.
leaf_id : int
The index of the leaf in the tree.
Returns
-------
result : float
The output of the leaf. | def get_leaf_output(self, tree_id, leaf_id):
"""Get the output of a leaf.
Parameters
----------
tree_id : int
The index of the tree.
leaf_id : int
The index of the leaf in the tree.
Returns
-------
result : float
The o... |
Convert to predictor. | def _to_predictor(self, pred_parameter=None):
"""Convert to predictor."""
predictor = _InnerPredictor(booster_handle=self.handle, pred_parameter=pred_parameter)
predictor.pandas_categorical = self.pandas_categorical
return predictor |
Get number of features.
Returns
-------
num_feature : int
The number of features. | def num_feature(self):
"""Get number of features.
Returns
-------
num_feature : int
The number of features.
"""
out_num_feature = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterGetNumFeature(
self.handle,
ctypes.byref(out_num_feat... |
Get names of features.
Returns
-------
result : list
List with names of features. | def feature_name(self):
"""Get names of features.
Returns
-------
result : list
List with names of features.
"""
num_feature = self.num_feature()
# Get name of features
tmp_out_len = ctypes.c_int(0)
string_buffers = [ctypes.create_stri... |
Get feature importances.
Parameters
----------
importance_type : string, optional (default="split")
How the importance is calculated.
If "split", result contains numbers of times the feature is used in a model.
If "gain", result contains total gains of splits... | def feature_importance(self, importance_type='split', iteration=None):
"""Get feature importances.
Parameters
----------
importance_type : string, optional (default="split")
How the importance is calculated.
If "split", result contains numbers of times the featur... |
Get split value histogram for the specified feature.
Parameters
----------
feature : int or string
The feature name or index the histogram is calculated for.
If int, interpreted as index.
If string, interpreted as name.
Note
----
... | def get_split_value_histogram(self, feature, bins=None, xgboost_style=False):
"""Get split value histogram for the specified feature.
Parameters
----------
feature : int or string
The feature name or index the histogram is calculated for.
If int, interpreted as i... |
Evaluate training or validation data. | def __inner_eval(self, data_name, data_idx, feval=None):
"""Evaluate training or validation data."""
if data_idx >= self.__num_dataset:
raise ValueError("Data_idx should be smaller than number of dataset")
self.__get_eval_info()
ret = []
if self.__num_inner_eval > 0:
... |
Predict for training and validation dataset. | def __inner_predict(self, data_idx):
"""Predict for training and validation dataset."""
if data_idx >= self.__num_dataset:
raise ValueError("Data_idx should be smaller than number of dataset")
if self.__inner_predict_buffer[data_idx] is None:
if data_idx == 0:
... |
Get inner evaluation count and names. | def __get_eval_info(self):
"""Get inner evaluation count and names."""
if self.__need_reload_eval_info:
self.__need_reload_eval_info = False
out_num_eval = ctypes.c_int(0)
# Get num of inner evals
_safe_call(_LIB.LGBM_BoosterGetEvalCounts(
... |
Find the path to LightGBM library files.
Returns
-------
lib_path: list of strings
List of all found library paths to LightGBM. | def find_lib_path():
"""Find the path to LightGBM library files.
Returns
-------
lib_path: list of strings
List of all found library paths to LightGBM.
"""
if os.environ.get('LIGHTGBM_BUILD_DOC', False):
# we don't need lib_lightgbm while building docs
return []
curr... |
Set attributes to the Booster.
Parameters
----------
**kwargs
The attributes to set.
Setting a value to None deletes an attribute.
Returns
-------
self : Booster
Booster with set attributes. | def set_attr(self, **kwargs):
"""Set attributes to the Booster.
Parameters
----------
**kwargs
The attributes to set.
Setting a value to None deletes an attribute.
Returns
-------
self : Booster
Booster with set attributes.
... |
Convert numpy classes to JSON serializable objects. | def json_default_with_numpy(obj):
"""Convert numpy classes to JSON serializable objects."""
if isinstance(obj, (np.integer, np.floating, np.bool_)):
return obj.item()
elif isinstance(obj, np.ndarray):
return obj.tolist()
else:
return obj |
Create a callback that prints the evaluation results.
Parameters
----------
period : int, optional (default=1)
The period to print the evaluation results.
show_stdv : bool, optional (default=True)
Whether to show stdv (if provided).
Returns
-------
callback : function
... | def print_evaluation(period=1, show_stdv=True):
"""Create a callback that prints the evaluation results.
Parameters
----------
period : int, optional (default=1)
The period to print the evaluation results.
show_stdv : bool, optional (default=True)
Whether to show stdv (if provided).... |
Format metric string. | def _format_eval_result(value, show_stdv=True):
"""Format metric string."""
if len(value) == 4:
return '%s\'s %s: %g' % (value[0], value[1], value[2])
elif len(value) == 5:
if show_stdv:
return '%s\'s %s: %g + %g' % (value[0], value[1], value[2], value[4])
else:
... |
Create a callback that records the evaluation history into ``eval_result``.
Parameters
----------
eval_result : dict
A dictionary to store the evaluation results.
Returns
-------
callback : function
The callback that records the evaluation history into the passed dictionary. | def record_evaluation(eval_result):
"""Create a callback that records the evaluation history into ``eval_result``.
Parameters
----------
eval_result : dict
A dictionary to store the evaluation results.
Returns
-------
callback : function
The callback that records the evaluat... |
Create a callback that resets the parameter after the first iteration.
Note
----
The initial parameter will still take in-effect on first iteration.
Parameters
----------
**kwargs : value should be list or function
List of parameters for each boosting round
or a customized func... | def reset_parameter(**kwargs):
"""Create a callback that resets the parameter after the first iteration.
Note
----
The initial parameter will still take in-effect on first iteration.
Parameters
----------
**kwargs : value should be list or function
List of parameters for each boost... |
Create a callback that activates early stopping.
Note
----
Activates early stopping.
The model will train until the validation score stops improving.
Validation score needs to improve at least every ``early_stopping_rounds`` round(s)
to continue training.
Requires at least one validation da... | def early_stopping(stopping_rounds, first_metric_only=False, verbose=True):
"""Create a callback that activates early stopping.
Note
----
Activates early stopping.
The model will train until the validation score stops improving.
Validation score needs to improve at least every ``early_stopping_... |
Perform the training with given parameters.
Parameters
----------
params : dict
Parameters for training.
train_set : Dataset
Data to be trained on.
num_boost_round : int, optional (default=100)
Number of boosting iterations.
valid_sets : list of Datasets or None, optiona... | def train(params, train_set, num_boost_round=100,
valid_sets=None, valid_names=None,
fobj=None, feval=None, init_model=None,
feature_name='auto', categorical_feature='auto',
early_stopping_rounds=None, evals_result=None,
verbose_eval=True, learning_rates=None,
... |
Make a n-fold list of Booster from random indices. | def _make_n_folds(full_data, folds, nfold, params, seed, fpreproc=None, stratified=True,
shuffle=True, eval_train_metric=False):
"""Make a n-fold list of Booster from random indices."""
full_data = full_data.construct()
num_data = full_data.num_data()
if folds is not None:
if n... |
Aggregate cross-validation results. | def _agg_cv_result(raw_results, eval_train_metric=False):
"""Aggregate cross-validation results."""
cvmap = collections.defaultdict(list)
metric_type = {}
for one_result in raw_results:
for one_line in one_result:
if eval_train_metric:
key = "{} {}".format(one_line[0]... |
Perform the cross-validation with given paramaters.
Parameters
----------
params : dict
Parameters for Booster.
train_set : Dataset
Data to be trained on.
num_boost_round : int, optional (default=100)
Number of boosting iterations.
folds : generator or iterator of (train... | def cv(params, train_set, num_boost_round=100,
folds=None, nfold=5, stratified=True, shuffle=True,
metrics=None, fobj=None, feval=None, init_model=None,
feature_name='auto', categorical_feature='auto',
early_stopping_rounds=None, fpreproc=None,
verbose_eval=None, show_stdv=True, seed=... |
Logarithmic loss with non-necessarily-binary labels. | def log_loss(preds, labels):
"""Logarithmic loss with non-necessarily-binary labels."""
log_likelihood = np.sum(labels * np.log(preds)) / len(preds)
return -log_likelihood |
Measure performance of an objective.
Parameters
----------
objective : string 'binary' or 'xentropy'
Objective function.
label_type : string 'binary' or 'probability'
Type of the label.
data : dict
Data for training.
Returns
-------
result : dict
Experim... | def experiment(objective, label_type, data):
"""Measure performance of an objective.
Parameters
----------
objective : string 'binary' or 'xentropy'
Objective function.
label_type : string 'binary' or 'probability'
Type of the label.
data : dict
Data for training.
R... |
Check object is not tuple or does not have 2 elements. | def _check_not_tuple_of_2_elements(obj, obj_name='obj'):
"""Check object is not tuple or does not have 2 elements."""
if not isinstance(obj, tuple) or len(obj) != 2:
raise TypeError('%s must be a tuple of 2 elements.' % obj_name) |
Plot model's feature importances.
Parameters
----------
booster : Booster or LGBMModel
Booster or LGBMModel instance which feature importance should be plotted.
ax : matplotlib.axes.Axes or None, optional (default=None)
Target axes instance.
If None, new figure and axes will be ... | def plot_importance(booster, ax=None, height=0.2,
xlim=None, ylim=None, title='Feature importance',
xlabel='Feature importance', ylabel='Features',
importance_type='split', max_num_features=None,
ignore_zero=True, figsize=None, grid=True,
... |
Plot one metric during training.
Parameters
----------
booster : dict or LGBMModel
Dictionary returned from ``lightgbm.train()`` or LGBMModel instance.
metric : string or None, optional (default=None)
The metric name to plot.
Only one metric supported because different metrics h... | def plot_metric(booster, metric=None, dataset_names=None,
ax=None, xlim=None, ylim=None,
title='Metric during training',
xlabel='Iterations', ylabel='auto',
figsize=None, grid=True):
"""Plot one metric during training.
Parameters
----------
... |
Convert specified tree to graphviz instance.
See:
- https://graphviz.readthedocs.io/en/stable/api.html#digraph | def _to_graphviz(tree_info, show_info, feature_names, precision=None, **kwargs):
"""Convert specified tree to graphviz instance.
See:
- https://graphviz.readthedocs.io/en/stable/api.html#digraph
"""
if GRAPHVIZ_INSTALLED:
from graphviz import Digraph
else:
raise ImportError('Y... |
Create a digraph representation of specified tree.
Note
----
For more information please visit
https://graphviz.readthedocs.io/en/stable/api.html#digraph.
Parameters
----------
booster : Booster or LGBMModel
Booster or LGBMModel instance to be converted.
tree_index : int, optio... | def create_tree_digraph(booster, tree_index=0, show_info=None, precision=None,
old_name=None, old_comment=None, old_filename=None, old_directory=None,
old_format=None, old_engine=None, old_encoding=None, old_graph_attr=None,
old_node_attr=None, old... |
Plot specified tree.
Note
----
It is preferable to use ``create_tree_digraph()`` because of its lossless quality
and returned objects can be also rendered and displayed directly inside a Jupyter notebook.
Parameters
----------
booster : Booster or LGBMModel
Booster or LGBMModel ins... | def plot_tree(booster, ax=None, tree_index=0, figsize=None,
old_graph_attr=None, old_node_attr=None, old_edge_attr=None,
show_info=None, precision=None, **kwargs):
"""Plot specified tree.
Note
----
It is preferable to use ``create_tree_digraph()`` because of its lossless qua... |
Return the -std=c++[0x/11/14] compiler flag.
The c++14 is preferred over c++0x/11 (when it is available). | def cpp_flag(compiler):
"""Return the -std=c++[0x/11/14] compiler flag.
The c++14 is preferred over c++0x/11 (when it is available).
"""
standards = ['-std=c++14', '-std=c++11', '-std=c++0x']
for standard in standards:
if has_flag(compiler, [standard]):
return standard
raise ... |
query is a 1d numpy array corresponding to the vector to which you want to
find the closest vector
vectors is a 2d numpy array corresponding to the vectors you want to consider
ban_set is a set of indicies within vectors you want to ignore for nearest match
cossims is a 1d numpy array of size len(vector... | def find_nearest_neighbor(query, vectors, ban_set, cossims=None):
"""
query is a 1d numpy array corresponding to the vector to which you want to
find the closest vector
vectors is a 2d numpy array corresponding to the vectors you want to consider
ban_set is a set of indicies within vectors you want ... |
Train a supervised model and return a model object.
input must be a filepath. The input text does not need to be tokenized
as per the tokenize function, but it must be preprocessed and encoded
as UTF-8. You might want to consult standard preprocessing scripts such
as tokenizer.perl mentioned here: http... | def train_supervised(
input,
lr=0.1,
dim=100,
ws=5,
epoch=5,
minCount=1,
minCountLabel=0,
minn=0,
maxn=0,
neg=5,
wordNgrams=1,
loss="softmax",
bucket=2000000,
thread=multiprocessing.cpu_count() - 1,
lrUpdateRate=100,
t=1e-4,
label="__label__",
verb... |
Get the vector representation of word. | def get_word_vector(self, word):
"""Get the vector representation of word."""
dim = self.get_dimension()
b = fasttext.Vector(dim)
self.f.getWordVector(b, word)
return np.array(b) |
Given a string, get a single vector represenation. This function
assumes to be given a single line of text. We split words on
whitespace (space, newline, tab, vertical tab) and the control
characters carriage return, formfeed and the null character. | def get_sentence_vector(self, text):
"""
Given a string, get a single vector represenation. This function
assumes to be given a single line of text. We split words on
whitespace (space, newline, tab, vertical tab) and the control
characters carriage return, formfeed and the null ... |
Given a word, get the subwords and their indicies. | def get_subwords(self, word, on_unicode_error='strict'):
"""
Given a word, get the subwords and their indicies.
"""
pair = self.f.getSubwords(word, on_unicode_error)
return pair[0], np.array(pair[1]) |
Given an index, get the corresponding vector of the Input Matrix. | def get_input_vector(self, ind):
"""
Given an index, get the corresponding vector of the Input Matrix.
"""
dim = self.get_dimension()
b = fasttext.Vector(dim)
self.f.getInputVector(b, ind)
return np.array(b) |
Given a string, get a list of labels and a list of
corresponding probabilities. k controls the number
of returned labels. A choice of 5, will return the 5
most probable labels. By default this returns only
the most likely label and probability. threshold filters
the returned labe... | def predict(self, text, k=1, threshold=0.0, on_unicode_error='strict'):
"""
Given a string, get a list of labels and a list of
corresponding probabilities. k controls the number
of returned labels. A choice of 5, will return the 5
most probable labels. By default this returns onl... |
Get a copy of the full input matrix of a Model. This only
works if the model is not quantized. | def get_input_matrix(self):
"""
Get a copy of the full input matrix of a Model. This only
works if the model is not quantized.
"""
if self.f.isQuant():
raise ValueError("Can't get quantized Matrix")
return np.array(self.f.getInputMatrix()) |
Get a copy of the full output matrix of a Model. This only
works if the model is not quantized. | def get_output_matrix(self):
"""
Get a copy of the full output matrix of a Model. This only
works if the model is not quantized.
"""
if self.f.isQuant():
raise ValueError("Can't get quantized Matrix")
return np.array(self.f.getOutputMatrix()) |
Get the entire list of words of the dictionary optionally
including the frequency of the individual words. This
does not include any subwords. For that please consult
the function get_subwords. | def get_words(self, include_freq=False, on_unicode_error='strict'):
"""
Get the entire list of words of the dictionary optionally
including the frequency of the individual words. This
does not include any subwords. For that please consult
the function get_subwords.
"""
... |
Get the entire list of labels of the dictionary optionally
including the frequency of the individual labels. Unsupervised
models use words as labels, which is why get_labels
will call and return get_words for this type of
model. | def get_labels(self, include_freq=False, on_unicode_error='strict'):
"""
Get the entire list of labels of the dictionary optionally
including the frequency of the individual labels. Unsupervised
models use words as labels, which is why get_labels
will call and return get_words fo... |
Split a line of text into words and labels. Labels must start with
the prefix used to create the model (__label__ by default). | def get_line(self, text, on_unicode_error='strict'):
"""
Split a line of text into words and labels. Labels must start with
the prefix used to create the model (__label__ by default).
"""
def check(entry):
if entry.find('\n') != -1:
raise ValueError(
... |
Quantize the model reducing the size of the model and
it's memory footprint. | def quantize(
self,
input=None,
qout=False,
cutoff=0,
retrain=False,
epoch=None,
lr=None,
thread=None,
verbose=None,
dsub=2,
qnorm=False
):
"""
Quantize the model reducing the size of the model and
it's m... |
Parameters
----------
inputs : ``PackedSequence``, required.
A batch first ``PackedSequence`` to run the stacked LSTM over.
initial_state : Tuple[torch.Tensor, torch.Tensor], optional, (default = None)
A tuple (state, memory) representing the initial hidden state and memo... | def forward(self, # pylint: disable=arguments-differ
inputs: PackedSequence,
initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None
) -> Tuple[PackedSequence, Tuple[torch.Tensor, torch.Tensor]]:
"""
Parameters
----------
inputs :... |
Converts a List of pairs (regex, params) into an RegularizerApplicator.
This list should look like
[["regex1", {"type": "l2", "alpha": 0.01}], ["regex2", "l1"]]
where each parameter receives the penalty corresponding to the first regex
that matches its name (which may be no regex and h... | def from_params(cls, params: Iterable[Tuple[str, Params]] = ()) -> Optional['RegularizerApplicator']:
"""
Converts a List of pairs (regex, params) into an RegularizerApplicator.
This list should look like
[["regex1", {"type": "l2", "alpha": 0.01}], ["regex2", "l1"]]
where each ... |
Sanitize turns PyTorch and Numpy types into basic Python types so they
can be serialized into JSON. | def sanitize(x: Any) -> Any: # pylint: disable=invalid-name,too-many-return-statements
"""
Sanitize turns PyTorch and Numpy types into basic Python types so they
can be serialized into JSON.
"""
if isinstance(x, (str, float, int, bool)):
# x is already serializable
return x
elif... |
List default first if it exists | def list_available(cls) -> List[str]:
"""List default first if it exists"""
keys = list(Registrable._registry[cls].keys())
default = cls.default_implementation
if default is None:
return keys
elif default not in keys:
message = "Default implementation %s ... |
Takes a list and groups it into sublists of size ``count``, using ``default_value`` to pad the
list at the end if the list is not divisable by ``count``.
For example:
>>> group_by_count([1, 2, 3, 4, 5, 6, 7], 3, 0)
[[1, 2, 3], [4, 5, 6], [7, 0, 0]]
This is a short method, but it's complicated and ... | def group_by_count(iterable: List[Any], count: int, default_value: Any) -> List[List[Any]]:
"""
Takes a list and groups it into sublists of size ``count``, using ``default_value`` to pad the
list at the end if the list is not divisable by ``count``.
For example:
>>> group_by_count([1, 2, 3, 4, 5, 6... |
Takes an iterator and batches the individual instances into lists of the
specified size. The last list may be smaller if there are instances left over. | def lazy_groups_of(iterator: Iterator[A], group_size: int) -> Iterator[List[A]]:
"""
Takes an iterator and batches the individual instances into lists of the
specified size. The last list may be smaller if there are instances left over.
"""
return iter(lambda: list(islice(iterator, 0, group_size)), ... |
Take a list of objects and pads it to the desired length, returning the padded list. The
original list is not modified.
Parameters
----------
sequence : List
A list of objects to be padded.
desired_length : int
Maximum length of each sequence. Longer sequences are truncated to thi... | def pad_sequence_to_length(sequence: List,
desired_length: int,
default_value: Callable[[], Any] = lambda: 0,
padding_on_right: bool = True) -> List:
"""
Take a list of objects and pads it to the desired length, returning the padde... |
Returns a new dictionary with noise added to every key in ``dictionary``. The noise is
uniformly distributed within ``noise_param`` percent of the value for every value in the
dictionary. | def add_noise_to_dict_values(dictionary: Dict[A, float], noise_param: float) -> Dict[A, float]:
"""
Returns a new dictionary with noise added to every key in ``dictionary``. The noise is
uniformly distributed within ``noise_param`` percent of the value for every value in the
dictionary.
"""
new... |
Sets random seeds for reproducible experiments. This may not work as expected
if you use this from within a python project in which you have already imported Pytorch.
If you use the scripts/run_model.py entry point to training models with this library,
your experiments should be reasonably reproducible. If ... | def prepare_environment(params: Params):
"""
Sets random seeds for reproducible experiments. This may not work as expected
if you use this from within a python project in which you have already imported Pytorch.
If you use the scripts/run_model.py entry point to training models with this library,
yo... |
Matches a namespace pattern against a namespace string. For example, ``*tags`` matches
``passage_tags`` and ``question_tags`` and ``tokens`` matches ``tokens`` but not
``stemmed_tokens``. | def namespace_match(pattern: str, namespace: str):
"""
Matches a namespace pattern against a namespace string. For example, ``*tags`` matches
``passage_tags`` and ``question_tags`` and ``tokens`` matches ``tokens`` but not
``stemmed_tokens``.
"""
if pattern[0] == '*' and namespace.endswith(patt... |
This function configures 3 global logging attributes - streaming stdout and stderr
to a file as well as the terminal, setting the formatting for the python logging
library and setting the interval frequency for the Tqdm progress bar.
Note that this function does not set the logging level, which is set in `... | def prepare_global_logging(serialization_dir: str, file_friendly_logging: bool) -> logging.FileHandler:
"""
This function configures 3 global logging attributes - streaming stdout and stderr
to a file as well as the terminal, setting the formatting for the python logging
library and setting the interval... |
This function closes any open file handles and logs set up by `prepare_global_logging`.
Parameters
----------
stdout_handler : ``logging.FileHandler``, required.
The file handler returned from `prepare_global_logging`, attached to the global logger. | def cleanup_global_logging(stdout_handler: logging.FileHandler) -> None:
"""
This function closes any open file handles and logs set up by `prepare_global_logging`.
Parameters
----------
stdout_handler : ``logging.FileHandler``, required.
The file handler returned from `prepare_global_loggi... |
In order to avoid loading spacy models a whole bunch of times, we'll save references to them,
keyed by the options we used to create the spacy model, so any particular configuration only
gets loaded once. | def get_spacy_model(spacy_model_name: str, pos_tags: bool, parse: bool, ner: bool) -> SpacyModelType:
"""
In order to avoid loading spacy models a whole bunch of times, we'll save references to them,
keyed by the options we used to create the spacy model, so any particular configuration only
gets loaded... |
Import all submodules under the given package.
Primarily useful so that people using AllenNLP as a library
can specify their own custom packages and have their custom
classes get loaded and registered. | def import_submodules(package_name: str) -> None:
"""
Import all submodules under the given package.
Primarily useful so that people using AllenNLP as a library
can specify their own custom packages and have their custom
classes get loaded and registered.
"""
importlib.invalidate_caches()
... |
Get peak memory usage for this process, as measured by
max-resident-set size:
https://unix.stackexchange.com/questions/30940/getrusage-system-call-what-is-maximum-resident-set-size
Only works on OSX and Linux, returns 0.0 otherwise. | def peak_memory_mb() -> float:
"""
Get peak memory usage for this process, as measured by
max-resident-set size:
https://unix.stackexchange.com/questions/30940/getrusage-system-call-what-is-maximum-resident-set-size
Only works on OSX and Linux, returns 0.0 otherwise.
"""
if resource is Non... |
Get the current GPU memory usage.
Based on https://discuss.pytorch.org/t/access-gpu-memory-usage-in-pytorch/3192/4
Returns
-------
``Dict[int, int]``
Keys are device ids as integers.
Values are memory usage as integers in MB.
Returns an empty ``dict`` if GPUs are not available. | def gpu_memory_mb() -> Dict[int, int]:
"""
Get the current GPU memory usage.
Based on https://discuss.pytorch.org/t/access-gpu-memory-usage-in-pytorch/3192/4
Returns
-------
``Dict[int, int]``
Keys are device ids as integers.
Values are memory usage as integers in MB.
Re... |
An Iterable may be a list or a generator.
This ensures we get a list without making an unnecessary copy. | def ensure_list(iterable: Iterable[A]) -> List[A]:
"""
An Iterable may be a list or a generator.
This ensures we get a list without making an unnecessary copy.
"""
if isinstance(iterable, list):
return iterable
else:
return list(iterable) |
Takes an action index, updates checklist and returns an updated state. | def update(self, action: torch.Tensor) -> 'ChecklistStatelet':
"""
Takes an action index, updates checklist and returns an updated state.
"""
checklist_addition = (self.terminal_actions == action).float()
new_checklist = self.checklist + checklist_addition
new_checklist_s... |
Finds the production rule matching the filter function in the given type's valid action
list, and removes it. If there is more than one matching function, we crash. | def _remove_action_from_type(valid_actions: Dict[str, List[str]],
type_: str,
filter_function: Callable[[str], bool]) -> None:
"""
Finds the production rule matching the filter function in the given type's valid action
list, and r... |
Parameters
----------
inputs : ``torch.FloatTensor``, required.
A tensor of shape (batch_size, num_timesteps, input_size)
to apply the LSTM over.
batch_lengths : ``List[int]``, required.
A list of length batch_size containing the lengths of the sequences in ba... | def forward(self, # pylint: disable=arguments-differ
inputs: torch.FloatTensor,
batch_lengths: List[int],
initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None):
"""
Parameters
----------
inputs : ``torch.FloatTensor``, require... |
Determine the URL corresponding to Python object
This code is from
https://github.com/numpy/numpy/blob/master/doc/source/conf.py#L290
and https://github.com/Lasagne/Lasagne/pull/262 | def linkcode_resolve(domain, info):
"""
Determine the URL corresponding to Python object
This code is from
https://github.com/numpy/numpy/blob/master/doc/source/conf.py#L290
and https://github.com/Lasagne/Lasagne/pull/262
"""
if domain != 'py':
return None
modname = info['module... |
This method returns the indices of each entity's neighbors. A tensor
is accepted as a parameter for copying purposes.
Parameters
----------
worlds : ``List[WikiTablesWorld]``
num_entities : ``int``
tensor : ``torch.Tensor``
Used for copying the constructed li... | def _get_neighbor_indices(worlds: List[WikiTablesWorld],
num_entities: int,
tensor: torch.Tensor) -> torch.LongTensor:
"""
This method returns the indices of each entity's neighbors. A tensor
is accepted as a parameter for copying purpo... |
Encodes the question and table, computes a linking between the two, and constructs an
initial RnnStatelet and LambdaGrammarStatelet for each batch instance to pass to the
decoder.
We take ``outputs`` as a parameter here and `modify` it, adding things that we want to
visualize in a demo. | def _get_initial_rnn_and_grammar_state(self,
question: Dict[str, torch.LongTensor],
table: Dict[str, torch.LongTensor],
world: List[WikiTablesWorld],
... |
Produces a tensor with shape ``(batch_size, num_entities)`` that encodes each entity's
type. In addition, a map from a flattened entity index to type is returned to combine
entity type operations into one method.
Parameters
----------
worlds : ``List[WikiTablesWorld]``
n... | def _get_type_vector(worlds: List[WikiTablesWorld],
num_entities: int,
tensor: torch.Tensor) -> Tuple[torch.LongTensor, Dict[int, int]]:
"""
Produces a tensor with shape ``(batch_size, num_entities)`` that encodes each entity's
type. In addition,... |
Produces the probability of an entity given a question word and type. The logic below
separates the entities by type since the softmax normalization term sums over entities
of a single type.
Parameters
----------
worlds : ``List[WikiTablesWorld]``
linking_scores : ``torc... | def _get_linking_probabilities(self,
worlds: List[WikiTablesWorld],
linking_scores: torch.FloatTensor,
question_mask: torch.LongTensor,
entity_type_dict: Dict[int, int]) -> torch.F... |
We track three metrics here:
1. dpd_acc, which is the percentage of the time that our best output action sequence is
in the set of action sequences provided by DPD. This is an easy-to-compute lower bound
on denotation accuracy for the set of examples where we actually have DPD outp... | def get_metrics(self, reset: bool = False) -> Dict[str, float]:
"""
We track three metrics here:
1. dpd_acc, which is the percentage of the time that our best output action sequence is
in the set of action sequences provided by DPD. This is an easy-to-compute lower bound
... |
This method creates the LambdaGrammarStatelet object that's used for decoding. Part of
creating that is creating the `valid_actions` dictionary, which contains embedded
representations of all of the valid actions. So, we create that here as well.
The way we represent the valid expansions is a... | def _create_grammar_state(self,
world: WikiTablesWorld,
possible_actions: List[ProductionRule],
linking_scores: torch.Tensor,
entity_types: torch.Tensor) -> LambdaGrammarStatelet:
"""
... |
Does common things for validation time: computing logical form accuracy (which is expensive
and unnecessary during training), adding visualization info to the output dictionary, etc.
This doesn't return anything; instead it `modifies` the given ``outputs`` dictionary, and
calls metrics on ``sel... | def _compute_validation_outputs(self,
actions: List[List[ProductionRule]],
best_final_states: Mapping[int, Sequence[GrammarBasedState]],
world: List[WikiTablesWorld],
example_l... |
This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test
time, to finalize predictions. This is (confusingly) a separate notion from the "decoder"
in "encoder/decoder", where that decoder logic lives in the ``TransitionFunction``.
This method trims the output ... | def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
"""
This method overrides ``Model.decode``, which gets called after ``Model.forward``, at test
time, to finalize predictions. This is (confusingly) a separate notion from the "decoder"
in "encoder/decoder... |
Gets the logits of desired terminal actions yet to be produced by the decoder, and
returns them for the decoder to add to the prior action logits, biasing the model towards
predicting missing linked actions. | def _get_linked_logits_addition(checklist_state: ChecklistStatelet,
action_ids: List[int],
action_logits: torch.Tensor) -> torch.Tensor:
"""
Gets the logits of desired terminal actions yet to be produced by the decoder, and
... |
Given a query (which is typically the decoder hidden state), compute an attention over the
output of the question encoder, and return a weighted sum of the question representations
given this attention. We also return the attention weights themselves.
This is a simple computation, but we have ... | def attend_on_question(self,
query: torch.Tensor,
encoder_outputs: torch.Tensor,
encoder_output_mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Given a query (which is typically the decoder hidden state), comp... |
Walk over action space to collect completed paths of at most ``self._max_path_length`` steps. | def _walk(self) -> None:
"""
Walk over action space to collect completed paths of at most ``self._max_path_length`` steps.
"""
# Buffer of NTs to expand, previous actions
incomplete_paths = [([str(type_)], [f"{START_SYMBOL} -> {type_}"]) for type_ in
s... |
Check that all the instances have the same types. | def _check_types(self) -> None:
"""
Check that all the instances have the same types.
"""
all_instance_fields_and_types: List[Dict[str, str]] = [{k: v.__class__.__name__
for k, v in x.fields.items()}
... |
This method converts this ``Batch`` into a set of pytorch Tensors that can be passed
through a model. In order for the tensors to be valid tensors, all ``Instances`` in this
batch need to be padded to the same lengths wherever padding is necessary, so we do that
first, then we combine all of th... | def as_tensor_dict(self,
padding_lengths: Dict[str, Dict[str, int]] = None,
verbose: bool = False) -> Dict[str, Union[torch.Tensor, Dict[str, torch.Tensor]]]:
# This complex return type is actually predefined elsewhere as a DataArray,
# but we can't use it b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.