id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
22,900
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.get_data
def get_data(self): """Get the raw data of the Dataset. Returns ------- data : string, numpy array, pandas DataFrame, H2O DataTable's Frame, scipy.sparse, list of numpy arrays or None Raw data used in the Dataset construction. """ if self.handle is None: ...
python
def get_data(self): """Get the raw data of the Dataset. Returns ------- data : string, numpy array, pandas DataFrame, H2O DataTable's Frame, scipy.sparse, list of numpy arrays or None Raw data used in the Dataset construction. """ if self.handle is None: ...
[ "def", "get_data", "(", "self", ")", ":", "if", "self", ".", "handle", "is", "None", ":", "raise", "Exception", "(", "\"Cannot get data before construct Dataset\"", ")", "if", "self", ".", "data", "is", "not", "None", "and", "self", ".", "used_indices", "is"...
Get the raw data of the Dataset. Returns ------- data : string, numpy array, pandas DataFrame, H2O DataTable's Frame, scipy.sparse, list of numpy arrays or None Raw data used in the Dataset construction.
[ "Get", "the", "raw", "data", "of", "the", "Dataset", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1437-L1458
22,901
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.get_group
def get_group(self): """Get the group of the Dataset. Returns ------- group : numpy array or None Group size of each group. """ if self.group is None: self.group = self.get_field('group') if self.group is not None: # gr...
python
def get_group(self): """Get the group of the Dataset. Returns ------- group : numpy array or None Group size of each group. """ if self.group is None: self.group = self.get_field('group') if self.group is not None: # gr...
[ "def", "get_group", "(", "self", ")", ":", "if", "self", ".", "group", "is", "None", ":", "self", ".", "group", "=", "self", ".", "get_field", "(", "'group'", ")", "if", "self", ".", "group", "is", "not", "None", ":", "# group data from LightGBM is bound...
Get the group of the Dataset. Returns ------- group : numpy array or None Group size of each group.
[ "Get", "the", "group", "of", "the", "Dataset", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1460-L1473
22,902
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.num_data
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...
python
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...
[ "def", "num_data", "(", "self", ")", ":", "if", "self", ".", "handle", "is", "not", "None", ":", "ret", "=", "ctypes", ".", "c_int", "(", ")", "_safe_call", "(", "_LIB", ".", "LGBM_DatasetGetNumData", "(", "self", ".", "handle", ",", "ctypes", ".", "...
Get the number of rows in the Dataset. Returns ------- number_of_rows : int The number of rows in the Dataset.
[ "Get", "the", "number", "of", "rows", "in", "the", "Dataset", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1475-L1489
22,903
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.get_ref_chain
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...
python
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...
[ "def", "get_ref_chain", "(", "self", ",", "ref_limit", "=", "100", ")", ":", "head", "=", "self", "ref_chain", "=", "set", "(", ")", "while", "len", "(", "ref_chain", ")", "<", "ref_limit", ":", "if", "isinstance", "(", "head", ",", "Dataset", ")", "...
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...
[ "Get", "a", "chain", "of", "Dataset", "objects", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1507-L1535
22,904
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.add_features_from
def add_features_from(self, other): """Add features from other Dataset to the current Dataset. Both Datasets must be constructed before calling this method. Parameters ---------- other : Dataset The Dataset to take features from. Returns ------- ...
python
def add_features_from(self, other): """Add features from other Dataset to the current Dataset. Both Datasets must be constructed before calling this method. Parameters ---------- other : Dataset The Dataset to take features from. Returns ------- ...
[ "def", "add_features_from", "(", "self", ",", "other", ")", ":", "if", "self", ".", "handle", "is", "None", "or", "other", ".", "handle", "is", "None", ":", "raise", "ValueError", "(", "'Both source and target Datasets must be constructed before adding features'", "...
Add features from other Dataset to the current Dataset. Both Datasets must be constructed before calling this method. Parameters ---------- other : Dataset The Dataset to take features from. Returns ------- self : Dataset Dataset with th...
[ "Add", "features", "from", "other", "Dataset", "to", "the", "current", "Dataset", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1537-L1555
22,905
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.dump_text
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...
python
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...
[ "def", "dump_text", "(", "self", ",", "filename", ")", ":", "_safe_call", "(", "_LIB", ".", "LGBM_DatasetDumpText", "(", "self", ".", "construct", "(", ")", ".", "handle", ",", "c_str", "(", "filename", ")", ")", ")", "return", "self" ]
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.
[ "Save", "Dataset", "to", "a", "text", "file", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1557-L1575
22,906
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.free_dataset
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
python
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
[ "def", "free_dataset", "(", "self", ")", ":", "self", ".", "__dict__", ".", "pop", "(", "'train_set'", ",", "None", ")", "self", ".", "__dict__", ".", "pop", "(", "'valid_sets'", ",", "None", ")", "self", ".", "__num_dataset", "=", "0", "return", "self...
Free Booster's Datasets. Returns ------- self : Booster Booster without Datasets.
[ "Free", "Booster", "s", "Datasets", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1719-L1730
22,907
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.set_network
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...
python
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...
[ "def", "set_network", "(", "self", ",", "machines", ",", "local_listen_port", "=", "12400", ",", "listen_time_out", "=", "120", ",", "num_machines", "=", "1", ")", ":", "_safe_call", "(", "_LIB", ".", "LGBM_NetworkInit", "(", "c_str", "(", "machines", ")", ...
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...
[ "Set", "the", "network", "configuration", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1737-L1762
22,908
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.add_valid
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. ...
python
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. ...
[ "def", "add_valid", "(", "self", ",", "data", ",", "name", ")", ":", "if", "not", "isinstance", "(", "data", ",", "Dataset", ")", ":", "raise", "TypeError", "(", "'Validation data should be Dataset instance, met {}'", ".", "format", "(", "type", "(", "data", ...
Add validation data. Parameters ---------- data : Dataset Validation data. name : string Name of validation data. Returns ------- self : Booster Booster with set validation data.
[ "Add", "validation", "data", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1792-L1821
22,909
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.reset_parameter
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...
python
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...
[ "def", "reset_parameter", "(", "self", ",", "params", ")", ":", "if", "any", "(", "metric_alias", "in", "params", "for", "metric_alias", "in", "(", "'metric'", ",", "'metrics'", ",", "'metric_types'", ")", ")", ":", "self", ".", "__need_reload_eval_info", "=...
Reset parameters of Booster. Parameters ---------- params : dict New parameters for Booster. Returns ------- self : Booster Booster with new parameters.
[ "Reset", "parameters", "of", "Booster", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1823-L1844
22,910
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.update
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...
python
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...
[ "def", "update", "(", "self", ",", "train_set", "=", "None", ",", "fobj", "=", "None", ")", ":", "# need reset training data", "if", "train_set", "is", "not", "None", "and", "train_set", "is", "not", "self", ".", "train_set", ":", "if", "not", "isinstance"...
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. ...
[ "Update", "Booster", "for", "one", "iteration", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1846-L1892
22,911
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.__boost
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...
python
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...
[ "def", "__boost", "(", "self", ",", "grad", ",", "hess", ")", ":", "grad", "=", "list_to_1d_numpy", "(", "grad", ",", "name", "=", "'gradient'", ")", "hess", "=", "list_to_1d_numpy", "(", "hess", ",", "name", "=", "'hessian'", ")", "assert", "grad", "....
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...
[ "Boost", "Booster", "for", "one", "iteration", "with", "customized", "gradient", "statistics", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1894-L1929
22,912
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.rollback_one_iter
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...
python
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...
[ "def", "rollback_one_iter", "(", "self", ")", ":", "_safe_call", "(", "_LIB", ".", "LGBM_BoosterRollbackOneIter", "(", "self", ".", "handle", ")", ")", "self", ".", "__is_predicted_cur_iter", "=", "[", "False", "for", "_", "in", "range_", "(", "self", ".", ...
Rollback one iteration. Returns ------- self : Booster Booster with rolled back one iteration.
[ "Rollback", "one", "iteration", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1931-L1942
22,913
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.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, ...
python
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, ...
[ "def", "current_iteration", "(", "self", ")", ":", "out_cur_iter", "=", "ctypes", ".", "c_int", "(", "0", ")", "_safe_call", "(", "_LIB", ".", "LGBM_BoosterGetCurrentIteration", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "out_cur_iter", ")...
Get the index of the current iteration. Returns ------- cur_iter : int The index of the current iteration.
[ "Get", "the", "index", "of", "the", "current", "iteration", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1944-L1956
22,914
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.num_model_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....
python
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....
[ "def", "num_model_per_iteration", "(", "self", ")", ":", "model_per_iter", "=", "ctypes", ".", "c_int", "(", "0", ")", "_safe_call", "(", "_LIB", ".", "LGBM_BoosterNumModelPerIteration", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "model_per_...
Get number of models per iteration. Returns ------- model_per_iter : int The number of models per iteration.
[ "Get", "number", "of", "models", "per", "iteration", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1958-L1970
22,915
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.num_trees
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...
python
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...
[ "def", "num_trees", "(", "self", ")", ":", "num_trees", "=", "ctypes", ".", "c_int", "(", "0", ")", "_safe_call", "(", "_LIB", ".", "LGBM_BoosterNumberOfTotalModel", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "num_trees", ")", ")", ")"...
Get number of weak sub-models. Returns ------- num_trees : int The number of weak sub-models.
[ "Get", "number", "of", "weak", "sub", "-", "models", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1972-L1984
22,916
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.eval
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...
python
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...
[ "def", "eval", "(", "self", ",", "data", ",", "name", ",", "feval", "=", "None", ")", ":", "if", "not", "isinstance", "(", "data", ",", "Dataset", ")", ":", "raise", "TypeError", "(", "\"Can only eval for Dataset instance\"", ")", "data_idx", "=", "-", "...
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,...
[ "Evaluate", "for", "data", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1986-L2022
22,917
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.eval_valid
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...
python
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...
[ "def", "eval_valid", "(", "self", ",", "feval", "=", "None", ")", ":", "return", "[", "item", "for", "i", "in", "range_", "(", "1", ",", "self", ".", "__num_dataset", ")", "for", "item", "in", "self", ".", "__inner_eval", "(", "self", ".", "name_vali...
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...
[ "Evaluate", "for", "validation", "data", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L2043-L2061
22,918
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.save_model
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...
python
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...
[ "def", "save_model", "(", "self", ",", "filename", ",", "num_iteration", "=", "None", ",", "start_iteration", "=", "0", ")", ":", "if", "num_iteration", "is", "None", ":", "num_iteration", "=", "self", ".", "best_iteration", "_safe_call", "(", "_LIB", ".", ...
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...
[ "Save", "Booster", "to", "file", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L2063-L2090
22,919
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.shuffle_models
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...
python
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...
[ "def", "shuffle_models", "(", "self", ",", "start_iteration", "=", "0", ",", "end_iteration", "=", "-", "1", ")", ":", "_safe_call", "(", "_LIB", ".", "LGBM_BoosterShuffleModels", "(", "self", ".", "handle", ",", "ctypes", ".", "c_int", "(", "start_iteration...
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...
[ "Shuffle", "models", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L2092-L2112
22,920
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.model_from_string
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. ...
python
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. ...
[ "def", "model_from_string", "(", "self", ",", "model_str", ",", "verbose", "=", "True", ")", ":", "if", "self", ".", "handle", "is", "not", "None", ":", "_safe_call", "(", "_LIB", ".", "LGBM_BoosterFree", "(", "self", ".", "handle", ")", ")", "self", "...
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 ...
[ "Load", "Booster", "from", "a", "string", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L2114-L2146
22,921
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.model_to_string
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...
python
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...
[ "def", "model_to_string", "(", "self", ",", "num_iteration", "=", "None", ",", "start_iteration", "=", "0", ")", ":", "if", "num_iteration", "is", "None", ":", "num_iteration", "=", "self", ".", "best_iteration", "buffer_len", "=", "1", "<<", "20", "tmp_out_...
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...
[ "Save", "Booster", "to", "string", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L2148-L2192
22,922
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.dump_model
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...
python
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...
[ "def", "dump_model", "(", "self", ",", "num_iteration", "=", "None", ",", "start_iteration", "=", "0", ")", ":", "if", "num_iteration", "is", "None", ":", "num_iteration", "=", "self", ".", "best_iteration", "buffer_len", "=", "1", "<<", "20", "tmp_out_len",...
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...
[ "Dump", "Booster", "to", "JSON", "format", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L2194-L2239
22,923
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.predict
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 ...
python
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 ...
[ "def", "predict", "(", "self", ",", "data", ",", "num_iteration", "=", "None", ",", "raw_score", "=", "False", ",", "pred_leaf", "=", "False", ",", "pred_contrib", "=", "False", ",", "data_has_header", "=", "False", ",", "is_reshape", "=", "True", ",", "...
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) ...
[ "Make", "a", "prediction", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L2241-L2288
22,924
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.refit
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...
python
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...
[ "def", "refit", "(", "self", ",", "data", ",", "label", ",", "decay_rate", "=", "0.9", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "__set_objective_to_none", ":", "raise", "LightGBMError", "(", "'Cannot refit due to null objective function.'", ")", "...
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 ...
[ "Refit", "the", "existing", "Booster", "by", "new", "data", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L2290-L2332
22,925
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.get_leaf_output
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...
python
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...
[ "def", "get_leaf_output", "(", "self", ",", "tree_id", ",", "leaf_id", ")", ":", "ret", "=", "ctypes", ".", "c_double", "(", "0", ")", "_safe_call", "(", "_LIB", ".", "LGBM_BoosterGetLeafValue", "(", "self", ".", "handle", ",", "ctypes", ".", "c_int", "(...
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.
[ "Get", "the", "output", "of", "a", "leaf", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L2334-L2355
22,926
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster._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
python
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
[ "def", "_to_predictor", "(", "self", ",", "pred_parameter", "=", "None", ")", ":", "predictor", "=", "_InnerPredictor", "(", "booster_handle", "=", "self", ".", "handle", ",", "pred_parameter", "=", "pred_parameter", ")", "predictor", ".", "pandas_categorical", ...
Convert to predictor.
[ "Convert", "to", "predictor", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L2357-L2361
22,927
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.num_feature
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...
python
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...
[ "def", "num_feature", "(", "self", ")", ":", "out_num_feature", "=", "ctypes", ".", "c_int", "(", "0", ")", "_safe_call", "(", "_LIB", ".", "LGBM_BoosterGetNumFeature", "(", "self", ".", "handle", ",", "ctypes", ".", "byref", "(", "out_num_feature", ")", "...
Get number of features. Returns ------- num_feature : int The number of features.
[ "Get", "number", "of", "features", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L2363-L2375
22,928
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.feature_name
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...
python
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...
[ "def", "feature_name", "(", "self", ")", ":", "num_feature", "=", "self", ".", "num_feature", "(", ")", "# Get name of features", "tmp_out_len", "=", "ctypes", ".", "c_int", "(", "0", ")", "string_buffers", "=", "[", "ctypes", ".", "create_string_buffer", "(",...
Get names of features. Returns ------- result : list List with names of features.
[ "Get", "names", "of", "features", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L2377-L2396
22,929
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.get_split_value_histogram
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...
python
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...
[ "def", "get_split_value_histogram", "(", "self", ",", "feature", ",", "bins", "=", "None", ",", "xgboost_style", "=", "False", ")", ":", "def", "add", "(", "root", ")", ":", "\"\"\"Recursively add thresholds.\"\"\"", "if", "'split_index'", "in", "root", ":", "...
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 ---- ...
[ "Get", "split", "value", "histogram", "for", "the", "specified", "feature", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L2436-L2503
22,930
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.__inner_eval
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: ...
python
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: ...
[ "def", "__inner_eval", "(", "self", ",", "data_name", ",", "data_idx", ",", "feval", "=", "None", ")", ":", "if", "data_idx", ">=", "self", ".", "__num_dataset", ":", "raise", "ValueError", "(", "\"Data_idx should be smaller than number of dataset\"", ")", "self",...
Evaluate training or validation data.
[ "Evaluate", "training", "or", "validation", "data", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L2505-L2536
22,931
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.__inner_predict
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: ...
python
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: ...
[ "def", "__inner_predict", "(", "self", ",", "data_idx", ")", ":", "if", "data_idx", ">=", "self", ".", "__num_dataset", ":", "raise", "ValueError", "(", "\"Data_idx should be smaller than number of dataset\"", ")", "if", "self", ".", "__inner_predict_buffer", "[", "...
Predict for training and validation dataset.
[ "Predict", "for", "training", "and", "validation", "dataset", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L2538-L2560
22,932
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.__get_eval_info
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( ...
python
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( ...
[ "def", "__get_eval_info", "(", "self", ")", ":", "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", "(", "...
Get inner evaluation count and names.
[ "Get", "inner", "evaluation", "count", "and", "names", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L2562-L2586
22,933
Microsoft/LightGBM
python-package/lightgbm/basic.py
Booster.set_attr
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. ...
python
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. ...
[ "def", "set_attr", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "value", "is", "not", "None", ":", "if", "not", "isinstance", "(", "value", ",", "string_type", ")", ...
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.
[ "Set", "attributes", "to", "the", "Booster", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L2604-L2625
22,934
Microsoft/LightGBM
python-package/lightgbm/libpath.py
find_lib_path
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...
python
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...
[ "def", "find_lib_path", "(", ")", ":", "if", "os", ".", "environ", ".", "get", "(", "'LIGHTGBM_BUILD_DOC'", ",", "False", ")", ":", "# we don't need lib_lightgbm while building docs", "return", "[", "]", "curr_path", "=", "os", ".", "path", ".", "dirname", "("...
Find the path to LightGBM library files. Returns ------- lib_path: list of strings List of all found library paths to LightGBM.
[ "Find", "the", "path", "to", "LightGBM", "library", "files", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/libpath.py#L8-L38
22,935
Microsoft/LightGBM
python-package/lightgbm/compat.py
json_default_with_numpy
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
python
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
[ "def", "json_default_with_numpy", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "np", ".", "integer", ",", "np", ".", "floating", ",", "np", ".", "bool_", ")", ")", ":", "return", "obj", ".", "item", "(", ")", "elif", "isinstance", ...
Convert numpy classes to JSON serializable objects.
[ "Convert", "numpy", "classes", "to", "JSON", "serializable", "objects", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/compat.py#L52-L59
22,936
Microsoft/LightGBM
python-package/lightgbm/callback.py
_format_eval_result
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: ...
python
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: ...
[ "def", "_format_eval_result", "(", "value", ",", "show_stdv", "=", "True", ")", ":", "if", "len", "(", "value", ")", "==", "4", ":", "return", "'%s\\'s %s: %g'", "%", "(", "value", "[", "0", "]", ",", "value", "[", "1", "]", ",", "value", "[", "2",...
Format metric string.
[ "Format", "metric", "string", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/callback.py#L42-L52
22,937
Microsoft/LightGBM
python-package/lightgbm/callback.py
print_evaluation
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)....
python
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)....
[ "def", "print_evaluation", "(", "period", "=", "1", ",", "show_stdv", "=", "True", ")", ":", "def", "_callback", "(", "env", ")", ":", "if", "period", ">", "0", "and", "env", ".", "evaluation_result_list", "and", "(", "env", ".", "iteration", "+", "1",...
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 ...
[ "Create", "a", "callback", "that", "prints", "the", "evaluation", "results", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/callback.py#L55-L75
22,938
Microsoft/LightGBM
python-package/lightgbm/callback.py
record_evaluation
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...
python
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...
[ "def", "record_evaluation", "(", "eval_result", ")", ":", "if", "not", "isinstance", "(", "eval_result", ",", "dict", ")", ":", "raise", "TypeError", "(", "'Eval_result should be a dictionary'", ")", "eval_result", ".", "clear", "(", ")", "def", "_init", "(", ...
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.
[ "Create", "a", "callback", "that", "records", "the", "evaluation", "history", "into", "eval_result", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/callback.py#L78-L105
22,939
Microsoft/LightGBM
python-package/lightgbm/callback.py
reset_parameter
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...
python
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...
[ "def", "reset_parameter", "(", "*", "*", "kwargs", ")", ":", "def", "_callback", "(", "env", ")", ":", "new_parameters", "=", "{", "}", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "if", "key", "in", "[", "'num_class'", ...
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...
[ "Create", "a", "callback", "that", "resets", "the", "parameter", "after", "the", "first", "iteration", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/callback.py#L108-L150
22,940
Microsoft/LightGBM
python-package/lightgbm/callback.py
early_stopping
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_...
python
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_...
[ "def", "early_stopping", "(", "stopping_rounds", ",", "first_metric_only", "=", "False", ",", "verbose", "=", "True", ")", ":", "best_score", "=", "[", "]", "best_iter", "=", "[", "]", "best_score_list", "=", "[", "]", "cmp_op", "=", "[", "]", "enabled", ...
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...
[ "Create", "a", "callback", "that", "activates", "early", "stopping", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/callback.py#L153-L236
22,941
Microsoft/LightGBM
examples/python-guide/logistic_regression.py
log_loss
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
python
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
[ "def", "log_loss", "(", "preds", ",", "labels", ")", ":", "log_likelihood", "=", "np", ".", "sum", "(", "labels", "*", "np", ".", "log", "(", "preds", ")", ")", "/", "len", "(", "preds", ")", "return", "-", "log_likelihood" ]
Logarithmic loss with non-necessarily-binary labels.
[ "Logarithmic", "loss", "with", "non", "-", "necessarily", "-", "binary", "labels", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/examples/python-guide/logistic_regression.py#L49-L52
22,942
Microsoft/LightGBM
examples/python-guide/logistic_regression.py
experiment
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...
python
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...
[ "def", "experiment", "(", "objective", ",", "label_type", ",", "data", ")", ":", "np", ".", "random", ".", "seed", "(", "0", ")", "nrounds", "=", "5", "lgb_data", "=", "data", "[", "'lgb_with_'", "+", "label_type", "+", "'_labels'", "]", "params", "=",...
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...
[ "Measure", "performance", "of", "an", "objective", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/examples/python-guide/logistic_regression.py#L55-L90
22,943
Microsoft/LightGBM
python-package/lightgbm/plotting.py
_check_not_tuple_of_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)
python
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)
[ "def", "_check_not_tuple_of_2_elements", "(", "obj", ",", "obj_name", "=", "'obj'", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "tuple", ")", "or", "len", "(", "obj", ")", "!=", "2", ":", "raise", "TypeError", "(", "'%s must be a tuple of 2 element...
Check object is not tuple or does not have 2 elements.
[ "Check", "object", "is", "not", "tuple", "or", "does", "not", "have", "2", "elements", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/plotting.py#L18-L21
22,944
Microsoft/LightGBM
python-package/lightgbm/plotting.py
plot_importance
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, ...
python
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, ...
[ "def", "plot_importance", "(", "booster", ",", "ax", "=", "None", ",", "height", "=", "0.2", ",", "xlim", "=", "None", ",", "ylim", "=", "None", ",", "title", "=", "'Feature importance'", ",", "xlabel", "=", "'Feature importance'", ",", "ylabel", "=", "'...
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 ...
[ "Plot", "model", "s", "feature", "importances", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/plotting.py#L30-L141
22,945
Microsoft/LightGBM
python-package/lightgbm/plotting.py
plot_metric
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 ---------- ...
python
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 ---------- ...
[ "def", "plot_metric", "(", "booster", ",", "metric", "=", "None", ",", "dataset_names", "=", "None", ",", "ax", "=", "None", ",", "xlim", "=", "None", ",", "ylim", "=", "None", ",", "title", "=", "'Metric during training'", ",", "xlabel", "=", "'Iteratio...
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...
[ "Plot", "one", "metric", "during", "training", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/plotting.py#L144-L265
22,946
Microsoft/LightGBM
python-package/lightgbm/plotting.py
_to_graphviz
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...
python
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...
[ "def", "_to_graphviz", "(", "tree_info", ",", "show_info", ",", "feature_names", ",", "precision", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "GRAPHVIZ_INSTALLED", ":", "from", "graphviz", "import", "Digraph", "else", ":", "raise", "ImportError", ...
Convert specified tree to graphviz instance. See: - https://graphviz.readthedocs.io/en/stable/api.html#digraph
[ "Convert", "specified", "tree", "to", "graphviz", "instance", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/plotting.py#L268-L315
22,947
Microsoft/LightGBM
python-package/lightgbm/plotting.py
create_tree_digraph
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...
python
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...
[ "def", "create_tree_digraph", "(", "booster", ",", "tree_index", "=", "0", ",", "show_info", "=", "None", ",", "precision", "=", "None", ",", "old_name", "=", "None", ",", "old_comment", "=", "None", ",", "old_filename", "=", "None", ",", "old_directory", ...
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...
[ "Create", "a", "digraph", "representation", "of", "specified", "tree", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/plotting.py#L318-L388
22,948
facebookresearch/fastText
python/fastText/FastText.py
train_supervised
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...
python
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...
[ "def", "train_supervised", "(", "input", ",", "lr", "=", "0.1", ",", "dim", "=", "100", ",", "ws", "=", "5", ",", "epoch", "=", "5", ",", "minCount", "=", "1", ",", "minCountLabel", "=", "0", ",", "minn", "=", "0", ",", "maxn", "=", "0", ",", ...
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...
[ "Train", "a", "supervised", "model", "and", "return", "a", "model", "object", "." ]
6dd2e11b5fe82854c4529d2a58d699b2cb182b1b
https://github.com/facebookresearch/fastText/blob/6dd2e11b5fe82854c4529d2a58d699b2cb182b1b/python/fastText/FastText.py#L323-L360
22,949
facebookresearch/fastText
python/fastText/FastText.py
_FastText.get_word_vector
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)
python
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)
[ "def", "get_word_vector", "(", "self", ",", "word", ")", ":", "dim", "=", "self", ".", "get_dimension", "(", ")", "b", "=", "fasttext", ".", "Vector", "(", "dim", ")", "self", ".", "f", ".", "getWordVector", "(", "b", ",", "word", ")", "return", "n...
Get the vector representation of word.
[ "Get", "the", "vector", "representation", "of", "word", "." ]
6dd2e11b5fe82854c4529d2a58d699b2cb182b1b
https://github.com/facebookresearch/fastText/blob/6dd2e11b5fe82854c4529d2a58d699b2cb182b1b/python/fastText/FastText.py#L47-L52
22,950
facebookresearch/fastText
python/fastText/FastText.py
_FastText.get_subwords
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])
python
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])
[ "def", "get_subwords", "(", "self", ",", "word", ",", "on_unicode_error", "=", "'strict'", ")", ":", "pair", "=", "self", ".", "f", ".", "getSubwords", "(", "word", ",", "on_unicode_error", ")", "return", "pair", "[", "0", "]", ",", "np", ".", "array",...
Given a word, get the subwords and their indicies.
[ "Given", "a", "word", "get", "the", "subwords", "and", "their", "indicies", "." ]
6dd2e11b5fe82854c4529d2a58d699b2cb182b1b
https://github.com/facebookresearch/fastText/blob/6dd2e11b5fe82854c4529d2a58d699b2cb182b1b/python/fastText/FastText.py#L84-L89
22,951
facebookresearch/fastText
python/fastText/FastText.py
_FastText.get_input_vector
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)
python
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)
[ "def", "get_input_vector", "(", "self", ",", "ind", ")", ":", "dim", "=", "self", ".", "get_dimension", "(", ")", "b", "=", "fasttext", ".", "Vector", "(", "dim", ")", "self", ".", "f", ".", "getInputVector", "(", "b", ",", "ind", ")", "return", "n...
Given an index, get the corresponding vector of the Input Matrix.
[ "Given", "an", "index", "get", "the", "corresponding", "vector", "of", "the", "Input", "Matrix", "." ]
6dd2e11b5fe82854c4529d2a58d699b2cb182b1b
https://github.com/facebookresearch/fastText/blob/6dd2e11b5fe82854c4529d2a58d699b2cb182b1b/python/fastText/FastText.py#L91-L98
22,952
facebookresearch/fastText
python/fastText/FastText.py
_FastText.predict
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...
python
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...
[ "def", "predict", "(", "self", ",", "text", ",", "k", "=", "1", ",", "threshold", "=", "0.0", ",", "on_unicode_error", "=", "'strict'", ")", ":", "def", "check", "(", "entry", ")", ":", "if", "entry", ".", "find", "(", "'\\n'", ")", "!=", "-", "1...
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...
[ "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"...
6dd2e11b5fe82854c4529d2a58d699b2cb182b1b
https://github.com/facebookresearch/fastText/blob/6dd2e11b5fe82854c4529d2a58d699b2cb182b1b/python/fastText/FastText.py#L100-L143
22,953
facebookresearch/fastText
python/fastText/FastText.py
_FastText.get_input_matrix
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())
python
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())
[ "def", "get_input_matrix", "(", "self", ")", ":", "if", "self", ".", "f", ".", "isQuant", "(", ")", ":", "raise", "ValueError", "(", "\"Can't get quantized Matrix\"", ")", "return", "np", ".", "array", "(", "self", ".", "f", ".", "getInputMatrix", "(", "...
Get a copy of the full input matrix of a Model. This only works if the model is not quantized.
[ "Get", "a", "copy", "of", "the", "full", "input", "matrix", "of", "a", "Model", ".", "This", "only", "works", "if", "the", "model", "is", "not", "quantized", "." ]
6dd2e11b5fe82854c4529d2a58d699b2cb182b1b
https://github.com/facebookresearch/fastText/blob/6dd2e11b5fe82854c4529d2a58d699b2cb182b1b/python/fastText/FastText.py#L145-L152
22,954
facebookresearch/fastText
python/fastText/FastText.py
_FastText.get_output_matrix
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())
python
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())
[ "def", "get_output_matrix", "(", "self", ")", ":", "if", "self", ".", "f", ".", "isQuant", "(", ")", ":", "raise", "ValueError", "(", "\"Can't get quantized Matrix\"", ")", "return", "np", ".", "array", "(", "self", ".", "f", ".", "getOutputMatrix", "(", ...
Get a copy of the full output matrix of a Model. This only works if the model is not quantized.
[ "Get", "a", "copy", "of", "the", "full", "output", "matrix", "of", "a", "Model", ".", "This", "only", "works", "if", "the", "model", "is", "not", "quantized", "." ]
6dd2e11b5fe82854c4529d2a58d699b2cb182b1b
https://github.com/facebookresearch/fastText/blob/6dd2e11b5fe82854c4529d2a58d699b2cb182b1b/python/fastText/FastText.py#L154-L161
22,955
facebookresearch/fastText
python/fastText/FastText.py
_FastText.get_words
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. """ ...
python
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. """ ...
[ "def", "get_words", "(", "self", ",", "include_freq", "=", "False", ",", "on_unicode_error", "=", "'strict'", ")", ":", "pair", "=", "self", ".", "f", ".", "getVocab", "(", "on_unicode_error", ")", "if", "include_freq", ":", "return", "(", "pair", "[", "...
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", "words", "of", "the", "dictionary", "optionally", "including", "the", "frequency", "of", "the", "individual", "words", ".", "This", "does", "not", "include", "any", "subwords", ".", "For", "that", "please", "consult", "t...
6dd2e11b5fe82854c4529d2a58d699b2cb182b1b
https://github.com/facebookresearch/fastText/blob/6dd2e11b5fe82854c4529d2a58d699b2cb182b1b/python/fastText/FastText.py#L163-L174
22,956
facebookresearch/fastText
python/fastText/FastText.py
_FastText.get_labels
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...
python
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...
[ "def", "get_labels", "(", "self", ",", "include_freq", "=", "False", ",", "on_unicode_error", "=", "'strict'", ")", ":", "a", "=", "self", ".", "f", ".", "getArgs", "(", ")", "if", "a", ".", "model", "==", "model_name", ".", "supervised", ":", "pair", ...
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.
[ "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", "w...
6dd2e11b5fe82854c4529d2a58d699b2cb182b1b
https://github.com/facebookresearch/fastText/blob/6dd2e11b5fe82854c4529d2a58d699b2cb182b1b/python/fastText/FastText.py#L176-L192
22,957
facebookresearch/fastText
python/fastText/FastText.py
_FastText.quantize
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...
python
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...
[ "def", "quantize", "(", "self", ",", "input", "=", "None", ",", "qout", "=", "False", ",", "cutoff", "=", "0", ",", "retrain", "=", "False", ",", "epoch", "=", "None", ",", "lr", "=", "None", ",", "thread", "=", "None", ",", "verbose", "=", "None...
Quantize the model reducing the size of the model and it's memory footprint.
[ "Quantize", "the", "model", "reducing", "the", "size", "of", "the", "model", "and", "it", "s", "memory", "footprint", "." ]
6dd2e11b5fe82854c4529d2a58d699b2cb182b1b
https://github.com/facebookresearch/fastText/blob/6dd2e11b5fe82854c4529d2a58d699b2cb182b1b/python/fastText/FastText.py#L234-L267
22,958
allenai/allennlp
allennlp/common/registrable.py
Registrable.list_available
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 ...
python
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 ...
[ "def", "list_available", "(", "cls", ")", "->", "List", "[", "str", "]", ":", "keys", "=", "list", "(", "Registrable", ".", "_registry", "[", "cls", "]", ".", "keys", "(", ")", ")", "default", "=", "cls", ".", "default_implementation", "if", "default",...
List default first if it exists
[ "List", "default", "first", "if", "it", "exists" ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/registrable.py#L62-L73
22,959
allenai/allennlp
allennlp/common/util.py
sanitize
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...
python
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...
[ "def", "sanitize", "(", "x", ":", "Any", ")", "->", "Any", ":", "# pylint: disable=invalid-name,too-many-return-statements", "if", "isinstance", "(", "x", ",", "(", "str", ",", "float", ",", "int", ",", "bool", ")", ")", ":", "# x is already serializable", "re...
Sanitize turns PyTorch and Numpy types into basic Python types so they can be serialized into JSON.
[ "Sanitize", "turns", "PyTorch", "and", "Numpy", "types", "into", "basic", "Python", "types", "so", "they", "can", "be", "serialized", "into", "JSON", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L48-L81
22,960
allenai/allennlp
allennlp/common/util.py
group_by_count
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...
python
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...
[ "def", "group_by_count", "(", "iterable", ":", "List", "[", "Any", "]", ",", "count", ":", "int", ",", "default_value", ":", "Any", ")", "->", "List", "[", "List", "[", "Any", "]", "]", ":", "return", "[", "list", "(", "l", ")", "for", "l", "in",...
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 ...
[ "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", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L83-L95
22,961
allenai/allennlp
allennlp/common/util.py
lazy_groups_of
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)), ...
python
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)), ...
[ "def", "lazy_groups_of", "(", "iterator", ":", "Iterator", "[", "A", "]", ",", "group_size", ":", "int", ")", "->", "Iterator", "[", "List", "[", "A", "]", "]", ":", "return", "iter", "(", "lambda", ":", "list", "(", "islice", "(", "iterator", ",", ...
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.
[ "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", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L99-L104
22,962
allenai/allennlp
allennlp/common/util.py
pad_sequence_to_length
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...
python
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...
[ "def", "pad_sequence_to_length", "(", "sequence", ":", "List", ",", "desired_length", ":", "int", ",", "default_value", ":", "Callable", "[", "[", "]", ",", "Any", "]", "=", "lambda", ":", "0", ",", "padding_on_right", ":", "bool", "=", "True", ")", "->"...
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...
[ "Take", "a", "list", "of", "objects", "and", "pads", "it", "to", "the", "desired", "length", "returning", "the", "padded", "list", ".", "The", "original", "list", "is", "not", "modified", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L106-L147
22,963
allenai/allennlp
allennlp/common/util.py
add_noise_to_dict_values
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...
python
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...
[ "def", "add_noise_to_dict_values", "(", "dictionary", ":", "Dict", "[", "A", ",", "float", "]", ",", "noise_param", ":", "float", ")", "->", "Dict", "[", "A", ",", "float", "]", ":", "new_dict", "=", "{", "}", "for", "key", ",", "value", "in", "dicti...
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.
[ "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", "d...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L150-L161
22,964
allenai/allennlp
allennlp/common/util.py
prepare_global_logging
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...
python
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...
[ "def", "prepare_global_logging", "(", "serialization_dir", ":", "str", ",", "file_friendly_logging", ":", "bool", ")", "->", "logging", ".", "FileHandler", ":", "# If we don't have a terminal as stdout,", "# force tqdm to be nicer.", "if", "not", "sys", ".", "stdout", "...
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 `...
[ "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"...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L208-L250
22,965
allenai/allennlp
allennlp/common/util.py
cleanup_global_logging
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...
python
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...
[ "def", "cleanup_global_logging", "(", "stdout_handler", ":", "logging", ".", "FileHandler", ")", "->", "None", ":", "stdout_handler", ".", "close", "(", ")", "logging", ".", "getLogger", "(", ")", ".", "removeHandler", "(", "stdout_handler", ")", "if", "isinst...
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.
[ "This", "function", "closes", "any", "open", "file", "handles", "and", "logs", "set", "up", "by", "prepare_global_logging", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L252-L267
22,966
allenai/allennlp
allennlp/common/util.py
get_spacy_model
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...
python
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...
[ "def", "get_spacy_model", "(", "spacy_model_name", ":", "str", ",", "pos_tags", ":", "bool", ",", "parse", ":", "bool", ",", "ner", ":", "bool", ")", "->", "SpacyModelType", ":", "options", "=", "(", "spacy_model_name", ",", "pos_tags", ",", "parse", ",", ...
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.
[ "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", "partic...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L272-L306
22,967
allenai/allennlp
allennlp/common/util.py
import_submodules
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() ...
python
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() ...
[ "def", "import_submodules", "(", "package_name", ":", "str", ")", "->", "None", ":", "importlib", ".", "invalidate_caches", "(", ")", "# For some reason, python doesn't always add this by default to your path, but you pretty much", "# always want it when using `--include-package`. A...
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.
[ "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...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L308-L334
22,968
allenai/allennlp
allennlp/common/util.py
ensure_list
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)
python
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)
[ "def", "ensure_list", "(", "iterable", ":", "Iterable", "[", "A", "]", ")", "->", "List", "[", "A", "]", ":", "if", "isinstance", "(", "iterable", ",", "list", ")", ":", "return", "iterable", "else", ":", "return", "list", "(", "iterable", ")" ]
An Iterable may be a list or a generator. This ensures we get a list without making an unnecessary copy.
[ "An", "Iterable", "may", "be", "a", "list", "or", "a", "generator", ".", "This", "ensures", "we", "get", "a", "list", "without", "making", "an", "unnecessary", "copy", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/common/util.py#L391-L399
22,969
allenai/allennlp
allennlp/state_machines/states/checklist_statelet.py
ChecklistStatelet.update
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...
python
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...
[ "def", "update", "(", "self", ",", "action", ":", "torch", ".", "Tensor", ")", "->", "'ChecklistStatelet'", ":", "checklist_addition", "=", "(", "self", ".", "terminal_actions", "==", "action", ")", ".", "float", "(", ")", "new_checklist", "=", "self", "."...
Takes an action index, updates checklist and returns an updated state.
[ "Takes", "an", "action", "index", "updates", "checklist", "and", "returns", "an", "updated", "state", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/states/checklist_statelet.py#L57-L68
22,970
allenai/allennlp
allennlp/semparse/worlds/wikitables_world.py
WikiTablesWorld._remove_action_from_type
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...
python
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...
[ "def", "_remove_action_from_type", "(", "valid_actions", ":", "Dict", "[", "str", ",", "List", "[", "str", "]", "]", ",", "type_", ":", "str", ",", "filter_function", ":", "Callable", "[", "[", "str", "]", ",", "bool", "]", ")", "->", "None", ":", "a...
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.
[ "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", "."...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/wikitables_world.py#L124-L134
22,971
allenai/allennlp
allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py
WikiTablesSemanticParser._get_neighbor_indices
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...
python
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...
[ "def", "_get_neighbor_indices", "(", "worlds", ":", "List", "[", "WikiTablesWorld", "]", ",", "num_entities", ":", "int", ",", "tensor", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "LongTensor", ":", "num_neighbors", "=", "0", "for", "world", "in...
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...
[ "This", "method", "returns", "the", "indices", "of", "each", "entity", "s", "neighbors", ".", "A", "tensor", "is", "accepted", "as", "a", "parameter", "for", "copying", "purposes", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py#L299-L341
22,972
allenai/allennlp
allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py
WikiTablesSemanticParser._get_linking_probabilities
def _get_linking_probabilities(self, worlds: List[WikiTablesWorld], linking_scores: torch.FloatTensor, question_mask: torch.LongTensor, entity_type_dict: Dict[int, int]) -> torch.F...
python
def _get_linking_probabilities(self, worlds: List[WikiTablesWorld], linking_scores: torch.FloatTensor, question_mask: torch.LongTensor, entity_type_dict: Dict[int, int]) -> torch.F...
[ "def", "_get_linking_probabilities", "(", "self", ",", "worlds", ":", "List", "[", "WikiTablesWorld", "]", ",", "linking_scores", ":", "torch", ".", "FloatTensor", ",", "question_mask", ":", "torch", ".", "LongTensor", ",", "entity_type_dict", ":", "Dict", "[", ...
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...
[ "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",...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py#L392-L472
22,973
allenai/allennlp
allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py
WikiTablesSemanticParser._create_grammar_state
def _create_grammar_state(self, world: WikiTablesWorld, possible_actions: List[ProductionRule], linking_scores: torch.Tensor, entity_types: torch.Tensor) -> LambdaGrammarStatelet: """ ...
python
def _create_grammar_state(self, world: WikiTablesWorld, possible_actions: List[ProductionRule], linking_scores: torch.Tensor, entity_types: torch.Tensor) -> LambdaGrammarStatelet: """ ...
[ "def", "_create_grammar_state", "(", "self", ",", "world", ":", "WikiTablesWorld", ",", "possible_actions", ":", "List", "[", "ProductionRule", "]", ",", "linking_scores", ":", "torch", ".", "Tensor", ",", "entity_types", ":", "torch", ".", "Tensor", ")", "->"...
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...
[ "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", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/semantic_parsing/wikitables/wikitables_semantic_parser.py#L513-L620
22,974
allenai/allennlp
allennlp/state_machines/transition_functions/linking_coverage_transition_function.py
LinkingCoverageTransitionFunction._get_linked_logits_addition
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 ...
python
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 ...
[ "def", "_get_linked_logits_addition", "(", "checklist_state", ":", "ChecklistStatelet", ",", "action_ids", ":", "List", "[", "int", "]", ",", "action_logits", ":", "torch", ".", "Tensor", ")", "->", "torch", ".", "Tensor", ":", "# Our basic approach here will be to ...
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.
[ "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", "to...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/state_machines/transition_functions/linking_coverage_transition_function.py#L161-L196
22,975
allenai/allennlp
allennlp/semparse/action_space_walker.py
ActionSpaceWalker._walk
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...
python
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...
[ "def", "_walk", "(", "self", ")", "->", "None", ":", "# Buffer of NTs to expand, previous actions", "incomplete_paths", "=", "[", "(", "[", "str", "(", "type_", ")", "]", ",", "[", "f\"{START_SYMBOL} -> {type_}\"", "]", ")", "for", "type_", "in", "self", ".", ...
Walk over action space to collect completed paths of at most ``self._max_path_length`` steps.
[ "Walk", "over", "action", "space", "to", "collect", "completed", "paths", "of", "at", "most", "self", ".", "_max_path_length", "steps", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/action_space_walker.py#L35-L101
22,976
allenai/allennlp
allennlp/data/dataset.py
Batch._check_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()} ...
python
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()} ...
[ "def", "_check_types", "(", "self", ")", "->", "None", ":", "all_instance_fields_and_types", ":", "List", "[", "Dict", "[", "str", ",", "str", "]", "]", "=", "[", "{", "k", ":", "v", ".", "__class__", ".", "__name__", "for", "k", ",", "v", "in", "x...
Check that all the instances have the same types.
[ "Check", "that", "all", "the", "instances", "have", "the", "same", "types", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset.py#L35-L44
22,977
allenai/allennlp
allennlp/data/dataset.py
Batch.as_tensor_dict
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...
python
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...
[ "def", "as_tensor_dict", "(", "self", ",", "padding_lengths", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "int", "]", "]", "=", "None", ",", "verbose", ":", "bool", "=", "False", ")", "->", "Dict", "[", "str", ",", "Union", "[", "torch",...
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...
[ "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", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/dataset.py#L71-L148
22,978
allenai/allennlp
allennlp/semparse/worlds/atis_world.py
get_strings_from_utterance
def get_strings_from_utterance(tokenized_utterance: List[Token]) -> Dict[str, List[int]]: """ Based on the current utterance, return a dictionary where the keys are the strings in the database that map to lists of the token indices that they are linked to. """ string_linking_scores: Dict[str, List[i...
python
def get_strings_from_utterance(tokenized_utterance: List[Token]) -> Dict[str, List[int]]: """ Based on the current utterance, return a dictionary where the keys are the strings in the database that map to lists of the token indices that they are linked to. """ string_linking_scores: Dict[str, List[i...
[ "def", "get_strings_from_utterance", "(", "tokenized_utterance", ":", "List", "[", "Token", "]", ")", "->", "Dict", "[", "str", ",", "List", "[", "int", "]", "]", ":", "string_linking_scores", ":", "Dict", "[", "str", ",", "List", "[", "int", "]", "]", ...
Based on the current utterance, return a dictionary where the keys are the strings in the database that map to lists of the token indices that they are linked to.
[ "Based", "on", "the", "current", "utterance", "return", "a", "dictionary", "where", "the", "keys", "are", "the", "strings", "in", "the", "database", "that", "map", "to", "lists", "of", "the", "token", "indices", "that", "they", "are", "linked", "to", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L15-L42
22,979
allenai/allennlp
allennlp/semparse/worlds/atis_world.py
AtisWorld._update_grammar
def _update_grammar(self): """ We create a new ``Grammar`` object from the one in ``AtisSqlTableContext``, that also has the new entities that are extracted from the utterance. Stitching together the expressions to form the grammar is a little tedious here, but it is worth it because we ...
python
def _update_grammar(self): """ We create a new ``Grammar`` object from the one in ``AtisSqlTableContext``, that also has the new entities that are extracted from the utterance. Stitching together the expressions to form the grammar is a little tedious here, but it is worth it because we ...
[ "def", "_update_grammar", "(", "self", ")", ":", "# This will give us a shallow copy. We have to be careful here because the ``Grammar`` object", "# contains ``Expression`` objects that have tuples containing the members of that expression.", "# We have to create new sub-expression objects so that o...
We create a new ``Grammar`` object from the one in ``AtisSqlTableContext``, that also has the new entities that are extracted from the utterance. Stitching together the expressions to form the grammar is a little tedious here, but it is worth it because we don't have to create a new grammar from...
[ "We", "create", "a", "new", "Grammar", "object", "from", "the", "one", "in", "AtisSqlTableContext", "that", "also", "has", "the", "new", "entities", "that", "are", "extracted", "from", "the", "utterance", ".", "Stitching", "together", "the", "expressions", "to...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L83-L183
22,980
allenai/allennlp
allennlp/semparse/worlds/atis_world.py
AtisWorld._update_expression_reference
def _update_expression_reference(self, # pylint: disable=no-self-use grammar: Grammar, parent_expression_nonterminal: str, child_expression_nonterminal: str) -> None: """ When we add a new expr...
python
def _update_expression_reference(self, # pylint: disable=no-self-use grammar: Grammar, parent_expression_nonterminal: str, child_expression_nonterminal: str) -> None: """ When we add a new expr...
[ "def", "_update_expression_reference", "(", "self", ",", "# pylint: disable=no-self-use", "grammar", ":", "Grammar", ",", "parent_expression_nonterminal", ":", "str", ",", "child_expression_nonterminal", ":", "str", ")", "->", "None", ":", "grammar", "[", "parent_expres...
When we add a new expression, there may be other expressions that refer to it, and we need to update those to point to the new expression.
[ "When", "we", "add", "a", "new", "expression", "there", "may", "be", "other", "expressions", "that", "refer", "to", "it", "and", "we", "need", "to", "update", "those", "to", "point", "to", "the", "new", "expression", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L198-L209
22,981
allenai/allennlp
allennlp/semparse/worlds/atis_world.py
AtisWorld._get_sequence_with_spacing
def _get_sequence_with_spacing(self, # pylint: disable=no-self-use new_grammar, expressions: List[Expression], name: str = '') -> Sequence: """ This is a helper method for generating sequences, since...
python
def _get_sequence_with_spacing(self, # pylint: disable=no-self-use new_grammar, expressions: List[Expression], name: str = '') -> Sequence: """ This is a helper method for generating sequences, since...
[ "def", "_get_sequence_with_spacing", "(", "self", ",", "# pylint: disable=no-self-use", "new_grammar", ",", "expressions", ":", "List", "[", "Expression", "]", ",", "name", ":", "str", "=", "''", ")", "->", "Sequence", ":", "expressions", "=", "[", "subexpressio...
This is a helper method for generating sequences, since we often want a list of expressions with whitespaces between them.
[ "This", "is", "a", "helper", "method", "for", "generating", "sequences", "since", "we", "often", "want", "a", "list", "of", "expressions", "with", "whitespaces", "between", "them", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L211-L222
22,982
allenai/allennlp
allennlp/semparse/worlds/atis_world.py
AtisWorld._get_linked_entities
def _get_linked_entities(self) -> Dict[str, Dict[str, Tuple[str, str, List[int]]]]: """ This method gets entities from the current utterance finds which tokens they are linked to. The entities are divided into two main groups, ``numbers`` and ``strings``. We rely on these entities later ...
python
def _get_linked_entities(self) -> Dict[str, Dict[str, Tuple[str, str, List[int]]]]: """ This method gets entities from the current utterance finds which tokens they are linked to. The entities are divided into two main groups, ``numbers`` and ``strings``. We rely on these entities later ...
[ "def", "_get_linked_entities", "(", "self", ")", "->", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Tuple", "[", "str", ",", "str", ",", "List", "[", "int", "]", "]", "]", "]", ":", "current_tokenized_utterance", "=", "[", "]", "if", "not", "...
This method gets entities from the current utterance finds which tokens they are linked to. The entities are divided into two main groups, ``numbers`` and ``strings``. We rely on these entities later for updating the valid actions and the grammar.
[ "This", "method", "gets", "entities", "from", "the", "current", "utterance", "finds", "which", "tokens", "they", "are", "linked", "to", ".", "The", "entities", "are", "divided", "into", "two", "main", "groups", "numbers", "and", "strings", ".", "We", "rely",...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/worlds/atis_world.py#L305-L381
22,983
allenai/allennlp
allennlp/service/config_explorer.py
make_app
def make_app(include_packages: Sequence[str] = ()) -> Flask: """ Creates a Flask app that serves up a simple configuration wizard. """ # Load modules for package_name in include_packages: import_submodules(package_name) app = Flask(__name__) # pylint: disable=invalid-name @app.err...
python
def make_app(include_packages: Sequence[str] = ()) -> Flask: """ Creates a Flask app that serves up a simple configuration wizard. """ # Load modules for package_name in include_packages: import_submodules(package_name) app = Flask(__name__) # pylint: disable=invalid-name @app.err...
[ "def", "make_app", "(", "include_packages", ":", "Sequence", "[", "str", "]", "=", "(", ")", ")", "->", "Flask", ":", "# Load modules", "for", "package_name", "in", "include_packages", ":", "import_submodules", "(", "package_name", ")", "app", "=", "Flask", ...
Creates a Flask app that serves up a simple configuration wizard.
[ "Creates", "a", "Flask", "app", "that", "serves", "up", "a", "simple", "configuration", "wizard", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/service/config_explorer.py#L31-L105
22,984
allenai/allennlp
allennlp/training/metrics/fbeta_measure.py
_prf_divide
def _prf_divide(numerator, denominator): """Performs division and handles divide-by-zero. On zero-division, sets the corresponding result elements to zero. """ result = numerator / denominator mask = denominator == 0.0 if not mask.any(): return result # remove nan result[mask] ...
python
def _prf_divide(numerator, denominator): """Performs division and handles divide-by-zero. On zero-division, sets the corresponding result elements to zero. """ result = numerator / denominator mask = denominator == 0.0 if not mask.any(): return result # remove nan result[mask] ...
[ "def", "_prf_divide", "(", "numerator", ",", "denominator", ")", ":", "result", "=", "numerator", "/", "denominator", "mask", "=", "denominator", "==", "0.0", "if", "not", "mask", ".", "any", "(", ")", ":", "return", "result", "# remove nan", "result", "["...
Performs division and handles divide-by-zero. On zero-division, sets the corresponding result elements to zero.
[ "Performs", "division", "and", "handles", "divide", "-", "by", "-", "zero", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/training/metrics/fbeta_measure.py#L231-L243
22,985
allenai/allennlp
tutorials/tagger/basic_pytorch.py
load_data
def load_data(file_path: str) -> Tuple[List[str], List[str]]: """ One sentence per line, formatted like The###DET dog###NN ate###V the###DET apple###NN Returns a list of pairs (tokenized_sentence, tags) """ data = [] with open(file_path) as f: for line in f: pairs ...
python
def load_data(file_path: str) -> Tuple[List[str], List[str]]: """ One sentence per line, formatted like The###DET dog###NN ate###V the###DET apple###NN Returns a list of pairs (tokenized_sentence, tags) """ data = [] with open(file_path) as f: for line in f: pairs ...
[ "def", "load_data", "(", "file_path", ":", "str", ")", "->", "Tuple", "[", "List", "[", "str", "]", ",", "List", "[", "str", "]", "]", ":", "data", "=", "[", "]", "with", "open", "(", "file_path", ")", "as", "f", ":", "for", "line", "in", "f", ...
One sentence per line, formatted like The###DET dog###NN ate###V the###DET apple###NN Returns a list of pairs (tokenized_sentence, tags)
[ "One", "sentence", "per", "line", "formatted", "like" ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/tutorials/tagger/basic_pytorch.py#L23-L39
22,986
allenai/allennlp
allennlp/data/vocabulary.py
Vocabulary.save_to_files
def save_to_files(self, directory: str) -> None: """ Persist this Vocabulary to files so it can be reloaded later. Each namespace corresponds to one file. Parameters ---------- directory : ``str`` The directory where we save the serialized vocabulary. ...
python
def save_to_files(self, directory: str) -> None: """ Persist this Vocabulary to files so it can be reloaded later. Each namespace corresponds to one file. Parameters ---------- directory : ``str`` The directory where we save the serialized vocabulary. ...
[ "def", "save_to_files", "(", "self", ",", "directory", ":", "str", ")", "->", "None", ":", "os", ".", "makedirs", "(", "directory", ",", "exist_ok", "=", "True", ")", "if", "os", ".", "listdir", "(", "directory", ")", ":", "logging", ".", "warning", ...
Persist this Vocabulary to files so it can be reloaded later. Each namespace corresponds to one file. Parameters ---------- directory : ``str`` The directory where we save the serialized vocabulary.
[ "Persist", "this", "Vocabulary", "to", "files", "so", "it", "can", "be", "reloaded", "later", ".", "Each", "namespace", "corresponds", "to", "one", "file", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L270-L294
22,987
allenai/allennlp
allennlp/data/vocabulary.py
Vocabulary.from_files
def from_files(cls, directory: str) -> 'Vocabulary': """ Loads a ``Vocabulary`` that was serialized using ``save_to_files``. Parameters ---------- directory : ``str`` The directory containing the serialized vocabulary. """ logger.info("Loading token d...
python
def from_files(cls, directory: str) -> 'Vocabulary': """ Loads a ``Vocabulary`` that was serialized using ``save_to_files``. Parameters ---------- directory : ``str`` The directory containing the serialized vocabulary. """ logger.info("Loading token d...
[ "def", "from_files", "(", "cls", ",", "directory", ":", "str", ")", "->", "'Vocabulary'", ":", "logger", ".", "info", "(", "\"Loading token dictionary from %s.\"", ",", "directory", ")", "with", "codecs", ".", "open", "(", "os", ".", "path", ".", "join", "...
Loads a ``Vocabulary`` that was serialized using ``save_to_files``. Parameters ---------- directory : ``str`` The directory containing the serialized vocabulary.
[ "Loads", "a", "Vocabulary", "that", "was", "serialized", "using", "save_to_files", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L297-L326
22,988
allenai/allennlp
allennlp/data/vocabulary.py
Vocabulary.set_from_file
def set_from_file(self, filename: str, is_padded: bool = True, oov_token: str = DEFAULT_OOV_TOKEN, namespace: str = "tokens"): """ If you already have a vocabulary file for a trained model somewhere, and you really w...
python
def set_from_file(self, filename: str, is_padded: bool = True, oov_token: str = DEFAULT_OOV_TOKEN, namespace: str = "tokens"): """ If you already have a vocabulary file for a trained model somewhere, and you really w...
[ "def", "set_from_file", "(", "self", ",", "filename", ":", "str", ",", "is_padded", ":", "bool", "=", "True", ",", "oov_token", ":", "str", "=", "DEFAULT_OOV_TOKEN", ",", "namespace", ":", "str", "=", "\"tokens\"", ")", ":", "if", "is_padded", ":", "self...
If you already have a vocabulary file for a trained model somewhere, and you really want to use that vocabulary file instead of just setting the vocabulary from a dataset, for whatever reason, you can do that with this method. You must specify the namespace to use, and we assume that you want t...
[ "If", "you", "already", "have", "a", "vocabulary", "file", "for", "a", "trained", "model", "somewhere", "and", "you", "really", "want", "to", "use", "that", "vocabulary", "file", "instead", "of", "just", "setting", "the", "vocabulary", "from", "a", "dataset"...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L328-L378
22,989
allenai/allennlp
allennlp/data/vocabulary.py
Vocabulary.extend_from_instances
def extend_from_instances(self, params: Params, instances: Iterable['adi.Instance'] = ()) -> None: """ Extends an already generated vocabulary using a collection of instances. """ min_count = params.pop("min_count", None) ...
python
def extend_from_instances(self, params: Params, instances: Iterable['adi.Instance'] = ()) -> None: """ Extends an already generated vocabulary using a collection of instances. """ min_count = params.pop("min_count", None) ...
[ "def", "extend_from_instances", "(", "self", ",", "params", ":", "Params", ",", "instances", ":", "Iterable", "[", "'adi.Instance'", "]", "=", "(", ")", ")", "->", "None", ":", "min_count", "=", "params", ".", "pop", "(", "\"min_count\"", ",", "None", ")...
Extends an already generated vocabulary using a collection of instances.
[ "Extends", "an", "already", "generated", "vocabulary", "using", "a", "collection", "of", "instances", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L569-L595
22,990
allenai/allennlp
allennlp/data/vocabulary.py
Vocabulary.is_padded
def is_padded(self, namespace: str) -> bool: """ Returns whether or not there are padding and OOV tokens added to the given namespace. """ return self._index_to_token[namespace][0] == self._padding_token
python
def is_padded(self, namespace: str) -> bool: """ Returns whether or not there are padding and OOV tokens added to the given namespace. """ return self._index_to_token[namespace][0] == self._padding_token
[ "def", "is_padded", "(", "self", ",", "namespace", ":", "str", ")", "->", "bool", ":", "return", "self", ".", "_index_to_token", "[", "namespace", "]", "[", "0", "]", "==", "self", ".", "_padding_token" ]
Returns whether or not there are padding and OOV tokens added to the given namespace.
[ "Returns", "whether", "or", "not", "there", "are", "padding", "and", "OOV", "tokens", "added", "to", "the", "given", "namespace", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L597-L601
22,991
allenai/allennlp
allennlp/data/vocabulary.py
Vocabulary.add_token_to_namespace
def add_token_to_namespace(self, token: str, namespace: str = 'tokens') -> int: """ Adds ``token`` to the index, if it is not already present. Either way, we return the index of the token. """ if not isinstance(token, str): raise ValueError("Vocabulary tokens must be...
python
def add_token_to_namespace(self, token: str, namespace: str = 'tokens') -> int: """ Adds ``token`` to the index, if it is not already present. Either way, we return the index of the token. """ if not isinstance(token, str): raise ValueError("Vocabulary tokens must be...
[ "def", "add_token_to_namespace", "(", "self", ",", "token", ":", "str", ",", "namespace", ":", "str", "=", "'tokens'", ")", "->", "int", ":", "if", "not", "isinstance", "(", "token", ",", "str", ")", ":", "raise", "ValueError", "(", "\"Vocabulary tokens mu...
Adds ``token`` to the index, if it is not already present. Either way, we return the index of the token.
[ "Adds", "token", "to", "the", "index", "if", "it", "is", "not", "already", "present", ".", "Either", "way", "we", "return", "the", "index", "of", "the", "token", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/data/vocabulary.py#L603-L617
22,992
allenai/allennlp
allennlp/models/model.py
Model.get_regularization_penalty
def get_regularization_penalty(self) -> Union[float, torch.Tensor]: """ Computes the regularization penalty for the model. Returns 0 if the model was not configured to use regularization. """ if self._regularizer is None: return 0.0 else: return se...
python
def get_regularization_penalty(self) -> Union[float, torch.Tensor]: """ Computes the regularization penalty for the model. Returns 0 if the model was not configured to use regularization. """ if self._regularizer is None: return 0.0 else: return se...
[ "def", "get_regularization_penalty", "(", "self", ")", "->", "Union", "[", "float", ",", "torch", ".", "Tensor", "]", ":", "if", "self", ".", "_regularizer", "is", "None", ":", "return", "0.0", "else", ":", "return", "self", ".", "_regularizer", "(", "se...
Computes the regularization penalty for the model. Returns 0 if the model was not configured to use regularization.
[ "Computes", "the", "regularization", "penalty", "for", "the", "model", ".", "Returns", "0", "if", "the", "model", "was", "not", "configured", "to", "use", "regularization", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L58-L66
22,993
allenai/allennlp
allennlp/models/model.py
Model._get_prediction_device
def _get_prediction_device(self) -> int: """ This method checks the device of the model parameters to determine the cuda_device this model should be run on for predictions. If there are no parameters, it returns -1. Returns ------- The cuda device this model should run ...
python
def _get_prediction_device(self) -> int: """ This method checks the device of the model parameters to determine the cuda_device this model should be run on for predictions. If there are no parameters, it returns -1. Returns ------- The cuda device this model should run ...
[ "def", "_get_prediction_device", "(", "self", ")", "->", "int", ":", "devices", "=", "{", "util", ".", "get_device_of", "(", "param", ")", "for", "param", "in", "self", ".", "parameters", "(", ")", "}", "if", "len", "(", "devices", ")", ">", "1", ":"...
This method checks the device of the model parameters to determine the cuda_device this model should be run on for predictions. If there are no parameters, it returns -1. Returns ------- The cuda device this model should run on for predictions.
[ "This", "method", "checks", "the", "device", "of", "the", "model", "parameters", "to", "determine", "the", "cuda_device", "this", "model", "should", "be", "run", "on", "for", "predictions", ".", "If", "there", "are", "no", "parameters", "it", "returns", "-",...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L206-L223
22,994
allenai/allennlp
allennlp/models/model.py
Model._maybe_warn_for_unseparable_batches
def _maybe_warn_for_unseparable_batches(self, output_key: str): """ This method warns once if a user implements a model which returns a dictionary with values which we are unable to split back up into elements of the batch. This is controlled by a class attribute ``_warn_for_unseperable_...
python
def _maybe_warn_for_unseparable_batches(self, output_key: str): """ This method warns once if a user implements a model which returns a dictionary with values which we are unable to split back up into elements of the batch. This is controlled by a class attribute ``_warn_for_unseperable_...
[ "def", "_maybe_warn_for_unseparable_batches", "(", "self", ",", "output_key", ":", "str", ")", ":", "if", "output_key", "not", "in", "self", ".", "_warn_for_unseparable_batches", ":", "logger", ".", "warning", "(", "f\"Encountered the {output_key} key in the model's retur...
This method warns once if a user implements a model which returns a dictionary with values which we are unable to split back up into elements of the batch. This is controlled by a class attribute ``_warn_for_unseperable_batches`` because it would be extremely verbose otherwise.
[ "This", "method", "warns", "once", "if", "a", "user", "implements", "a", "model", "which", "returns", "a", "dictionary", "with", "values", "which", "we", "are", "unable", "to", "split", "back", "up", "into", "elements", "of", "the", "batch", ".", "This", ...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/models/model.py#L225-L237
22,995
allenai/allennlp
allennlp/semparse/domain_languages/wikitables_language.py
WikiTablesLanguage.evaluate_logical_form
def evaluate_logical_form(self, logical_form: str, target_list: List[str]) -> bool: """ Takes a logical form, and the list of target values as strings from the original lisp string, and returns True iff the logical form executes to the target list, using the official WikiTableQuestions e...
python
def evaluate_logical_form(self, logical_form: str, target_list: List[str]) -> bool: """ Takes a logical form, and the list of target values as strings from the original lisp string, and returns True iff the logical form executes to the target list, using the official WikiTableQuestions e...
[ "def", "evaluate_logical_form", "(", "self", ",", "logical_form", ":", "str", ",", "target_list", ":", "List", "[", "str", "]", ")", "->", "bool", ":", "normalized_target_list", "=", "[", "TableQuestionContext", ".", "normalize_string", "(", "value", ")", "for...
Takes a logical form, and the list of target values as strings from the original lisp string, and returns True iff the logical form executes to the target list, using the official WikiTableQuestions evaluation script.
[ "Takes", "a", "logical", "form", "and", "the", "list", "of", "target", "values", "as", "strings", "from", "the", "original", "lisp", "string", "and", "returns", "True", "iff", "the", "logical", "form", "executes", "to", "the", "target", "list", "using", "t...
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L323-L342
22,996
allenai/allennlp
allennlp/semparse/domain_languages/wikitables_language.py
WikiTablesLanguage.select_string
def select_string(self, rows: List[Row], column: StringColumn) -> List[str]: """ Select function takes a list of rows and a column name and returns a list of strings as in cells. """ return [str(row.values[column.name]) for row in rows if row.values[column.name] is not None]
python
def select_string(self, rows: List[Row], column: StringColumn) -> List[str]: """ Select function takes a list of rows and a column name and returns a list of strings as in cells. """ return [str(row.values[column.name]) for row in rows if row.values[column.name] is not None]
[ "def", "select_string", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ",", "column", ":", "StringColumn", ")", "->", "List", "[", "str", "]", ":", "return", "[", "str", "(", "row", ".", "values", "[", "column", ".", "name", "]", ")", "f...
Select function takes a list of rows and a column name and returns a list of strings as in cells.
[ "Select", "function", "takes", "a", "list", "of", "rows", "and", "a", "column", "name", "and", "returns", "a", "list", "of", "strings", "as", "in", "cells", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L354-L359
22,997
allenai/allennlp
allennlp/semparse/domain_languages/wikitables_language.py
WikiTablesLanguage.select_date
def select_date(self, rows: List[Row], column: DateColumn) -> Date: """ Select function takes a row as a list and a column name and returns the date in that column. """ dates: List[Date] = [] for row in rows: cell_value = row.values[column.name] if isinsta...
python
def select_date(self, rows: List[Row], column: DateColumn) -> Date: """ Select function takes a row as a list and a column name and returns the date in that column. """ dates: List[Date] = [] for row in rows: cell_value = row.values[column.name] if isinsta...
[ "def", "select_date", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ",", "column", ":", "DateColumn", ")", "->", "Date", ":", "dates", ":", "List", "[", "Date", "]", "=", "[", "]", "for", "row", "in", "rows", ":", "cell_value", "=", "ro...
Select function takes a row as a list and a column name and returns the date in that column.
[ "Select", "function", "takes", "a", "row", "as", "a", "list", "and", "a", "column", "name", "and", "returns", "the", "date", "in", "that", "column", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L376-L386
22,998
allenai/allennlp
allennlp/semparse/domain_languages/wikitables_language.py
WikiTablesLanguage.same_as
def same_as(self, rows: List[Row], column: Column) -> List[Row]: """ Takes a row and a column and returns a list of rows from the full set of rows that contain the same value under the given column as the given row. """ cell_value = rows[0].values[column.name] return_list...
python
def same_as(self, rows: List[Row], column: Column) -> List[Row]: """ Takes a row and a column and returns a list of rows from the full set of rows that contain the same value under the given column as the given row. """ cell_value = rows[0].values[column.name] return_list...
[ "def", "same_as", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ",", "column", ":", "Column", ")", "->", "List", "[", "Row", "]", ":", "cell_value", "=", "rows", "[", "0", "]", ".", "values", "[", "column", ".", "name", "]", "return_lis...
Takes a row and a column and returns a list of rows from the full set of rows that contain the same value under the given column as the given row.
[ "Takes", "a", "row", "and", "a", "column", "and", "returns", "a", "list", "of", "rows", "from", "the", "full", "set", "of", "rows", "that", "contain", "the", "same", "value", "under", "the", "given", "column", "as", "the", "given", "row", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L389-L399
22,999
allenai/allennlp
allennlp/semparse/domain_languages/wikitables_language.py
WikiTablesLanguage.date
def date(self, year: Number, month: Number, day: Number) -> Date: """ Takes three numbers and returns a ``Date`` object whose year, month, and day are the three numbers in that order. """ return Date(year, month, day)
python
def date(self, year: Number, month: Number, day: Number) -> Date: """ Takes three numbers and returns a ``Date`` object whose year, month, and day are the three numbers in that order. """ return Date(year, month, day)
[ "def", "date", "(", "self", ",", "year", ":", "Number", ",", "month", ":", "Number", ",", "day", ":", "Number", ")", "->", "Date", ":", "return", "Date", "(", "year", ",", "month", ",", "day", ")" ]
Takes three numbers and returns a ``Date`` object whose year, month, and day are the three numbers in that order.
[ "Takes", "three", "numbers", "and", "returns", "a", "Date", "object", "whose", "year", "month", "and", "day", "are", "the", "three", "numbers", "in", "that", "order", "." ]
648a36f77db7e45784c047176074f98534c76636
https://github.com/allenai/allennlp/blob/648a36f77db7e45784c047176074f98534c76636/allennlp/semparse/domain_languages/wikitables_language.py#L402-L407