Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def subset(self, used_indices, params=None): if params is None: params = self.params ret = Dataset(None, reference=self, feature_name=self.feature_name, categorical_feature=self.categorical_feature, params=params, ...
[ "Get subset of current Dataset.\n\n Parameters\n ----------\n used_indices : list of int\n Indices used to create the subset.\n params : dict or None, optional (default=None)\n These parameters will be passed to Dataset constructor.\n\n Returns\n -----...
Please provide a description of the function:def save_binary(self, filename): _safe_call(_LIB.LGBM_DatasetSaveBinary( self.construct().handle, c_str(filename))) return self
[ "Save Dataset to a binary file.\n\n Parameters\n ----------\n filename : string\n Name of the output file.\n\n Returns\n -------\n self : Dataset\n Returns self.\n " ]
Please provide a description of the function:def set_field(self, field_name, data): if self.handle is None: raise Exception("Cannot set %s before construct dataset" % field_name) if data is None: # set to None _safe_call(_LIB.LGBM_DatasetSetField( ...
[ "Set property into the Dataset.\n\n Parameters\n ----------\n field_name : string\n The field name of the information.\n data : list, numpy 1-D array, pandas Series or None\n The array of data to be set.\n\n Returns\n -------\n self : Dataset\n ...
Please provide a description of the function:def get_field(self, field_name): if self.handle is None: raise Exception("Cannot get %s before construct Dataset" % field_name) tmp_out_len = ctypes.c_int() out_type = ctypes.c_int() ret = ctypes.POINTER(ctypes.c_void_p)()...
[ "Get property from the Dataset.\n\n Parameters\n ----------\n field_name : string\n The field name of the information.\n\n Returns\n -------\n info : numpy array\n A numpy array with information from the Dataset.\n " ]
Please provide a description of the function:def set_categorical_feature(self, categorical_feature): if self.categorical_feature == categorical_feature: return self if self.data is not None: if self.categorical_feature is None: self.categorical_feature = ...
[ "Set categorical features.\n\n Parameters\n ----------\n categorical_feature : list of int or strings\n Names or indices of categorical features.\n\n Returns\n -------\n self : Dataset\n Dataset with set categorical features.\n " ]
Please provide a description of the function:def _set_predictor(self, predictor): if predictor is self._predictor: return self if self.data is not None: self._predictor = predictor return self._free_handle() else: raise LightGBMError("Cann...
[ "Set predictor for continued training.\n\n It is not recommended for user to call this function.\n Please use init_model argument in engine.train() or engine.cv() instead.\n " ]
Please provide a description of the function:def set_reference(self, reference): self.set_categorical_feature(reference.categorical_feature) \ .set_feature_name(reference.feature_name) \ ._set_predictor(reference._predictor) # we're done if self and reference share a com...
[ "Set reference Dataset.\n\n Parameters\n ----------\n reference : Dataset\n Reference that is used as a template to construct the current Dataset.\n\n Returns\n -------\n self : Dataset\n Dataset with set reference.\n " ]
Please provide a description of the function:def set_feature_name(self, feature_name): if feature_name != 'auto': self.feature_name = feature_name if self.handle is not None and feature_name is not None and feature_name != 'auto': if len(feature_name) != self.num_feature...
[ "Set feature name.\n\n Parameters\n ----------\n feature_name : list of strings\n Feature names.\n\n Returns\n -------\n self : Dataset\n Dataset with set feature name.\n " ]
Please provide a description of the function:def set_label(self, label): self.label = label if self.handle is not None: label = list_to_1d_numpy(_label_from_pandas(label), name='label') self.set_field('label', label) return self
[ "Set label of Dataset.\n\n Parameters\n ----------\n label : list, numpy 1-D array, pandas Series / one-column DataFrame or None\n The label information to be set into Dataset.\n\n Returns\n -------\n self : Dataset\n Dataset with set label.\n "...
Please provide a description of the function:def set_weight(self, weight): if weight is not None and np.all(weight == 1): weight = None self.weight = weight if self.handle is not None and weight is not None: weight = list_to_1d_numpy(weight, name='weight') ...
[ "Set weight of each instance.\n\n Parameters\n ----------\n weight : list, numpy 1-D array, pandas Series or None\n Weight to be set for each data point.\n\n Returns\n -------\n self : Dataset\n Dataset with set weight.\n " ]
Please provide a description of the function:def set_init_score(self, init_score): self.init_score = init_score if self.handle is not None and init_score is not None: init_score = list_to_1d_numpy(init_score, np.float64, name='init_score') self.set_field('init_score', in...
[ "Set init score of Booster to start from.\n\n Parameters\n ----------\n init_score : list, numpy 1-D array, pandas Series or None\n Init score for Booster.\n\n Returns\n -------\n self : Dataset\n Dataset with set init score.\n " ]
Please provide a description of the function:def set_group(self, group): self.group = group if self.handle is not None and group is not None: group = list_to_1d_numpy(group, np.int32, name='group') self.set_field('group', group) return self
[ "Set group size of Dataset (used for ranking).\n\n Parameters\n ----------\n group : list, numpy 1-D array, pandas Series or None\n Group size of each group.\n\n Returns\n -------\n self : Dataset\n Dataset with set group.\n " ]
Please provide a description of the function:def get_label(self): if self.label is None: self.label = self.get_field('label') return self.label
[ "Get the label of the Dataset.\n\n Returns\n -------\n label : numpy array or None\n The label information from the Dataset.\n " ]
Please provide a description of the function:def get_weight(self): if self.weight is None: self.weight = self.get_field('weight') return self.weight
[ "Get the weight of the Dataset.\n\n Returns\n -------\n weight : numpy array or None\n Weight for each data point from the Dataset.\n " ]
Please provide a description of the function:def get_feature_penalty(self): if self.feature_penalty is None: self.feature_penalty = self.get_field('feature_penalty') return self.feature_penalty
[ "Get the feature penalty of the Dataset.\n\n Returns\n -------\n feature_penalty : numpy array or None\n Feature penalty for each feature in the Dataset.\n " ]
Please provide a description of the function:def get_monotone_constraints(self): if self.monotone_constraints is None: self.monotone_constraints = self.get_field('monotone_constraints') return self.monotone_constraints
[ "Get the monotone constraints of the Dataset.\n\n Returns\n -------\n monotone_constraints : numpy array or None\n Monotone constraints: -1, 0 or 1, for each feature in the Dataset.\n " ]
Please provide a description of the function:def get_init_score(self): if self.init_score is None: self.init_score = self.get_field('init_score') return self.init_score
[ "Get the initial score of the Dataset.\n\n Returns\n -------\n init_score : numpy array or None\n Init score of Booster.\n " ]
Please provide a description of the function: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 not None and self.need_slice: if isinstance(self.data, np.ndarray) or sc...
[ "Get the raw data of the Dataset.\n\n Returns\n -------\n data : string, numpy array, pandas DataFrame, H2O DataTable's Frame, scipy.sparse, list of numpy arrays or None\n Raw data used in the Dataset construction.\n " ]
Please provide a description of the function: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 boundaries data, need to convert to group size self.group = np.d...
[ "Get the group of the Dataset.\n\n Returns\n -------\n group : numpy array or None\n Group size of each group.\n " ]
Please provide a description of the function:def num_data(self): if self.handle is not None: ret = ctypes.c_int() _safe_call(_LIB.LGBM_DatasetGetNumData(self.handle, ctypes.byref(ret))) return ret.value else:...
[ "Get the number of rows in the Dataset.\n\n Returns\n -------\n number_of_rows : int\n The number of rows in the Dataset.\n " ]
Please provide a description of the function:def num_feature(self): if self.handle is not None: ret = ctypes.c_int() _safe_call(_LIB.LGBM_DatasetGetNumFeature(self.handle, ctypes.byref(ret))) return ret.value ...
[ "Get the number of columns (features) in the Dataset.\n\n Returns\n -------\n number_of_columns : int\n The number of columns (features) in the Dataset.\n " ]
Please provide a description of the function:def get_ref_chain(self, ref_limit=100): head = self ref_chain = set() while len(ref_chain) < ref_limit: if isinstance(head, Dataset): ref_chain.add(head) if (head.reference is not None) and (head.re...
[ "Get a chain of Dataset objects.\n\n Starts with r, then goes to r.reference (if exists),\n then to r.reference.reference, etc.\n until we hit ``ref_limit`` or a reference loop.\n\n Parameters\n ----------\n ref_limit : int, optional (default=100)\n The limit num...
Please provide a description of the function: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') _safe_call(_LIB.LGBM_DatasetAddFeaturesFrom(self.handle, ot...
[ "Add features from other Dataset to the current Dataset.\n\n Both Datasets must be constructed before calling this method.\n\n Parameters\n ----------\n other : Dataset\n The Dataset to take features from.\n\n Returns\n -------\n self : Dataset\n ...
Please provide a description of the function:def dump_text(self, filename): _safe_call(_LIB.LGBM_DatasetDumpText( self.construct().handle, c_str(filename))) return self
[ "Save Dataset to a text file.\n\n This format cannot be loaded back in by LightGBM, but is useful for debugging purposes.\n\n Parameters\n ----------\n filename : string\n Name of the output file.\n\n Returns\n -------\n self : Dataset\n Returns...
Please provide a description of the function: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.\n\n Returns\n -------\n self : Booster\n Booster without Datasets.\n " ]
Please provide a description of the function:def set_network(self, machines, local_listen_port=12400, listen_time_out=120, num_machines=1): _safe_call(_LIB.LGBM_NetworkInit(c_str(machines), ctypes.c_int(local_listen_port), ...
[ "Set the network configuration.\n\n Parameters\n ----------\n machines : list, set or string\n Names of machines.\n local_listen_port : int, optional (default=12400)\n TCP listen port for local machines.\n listen_time_out : int, optional (default=120)\n ...
Please provide a description of the function:def add_valid(self, data, name): if not isinstance(data, Dataset): raise TypeError('Validation data should be Dataset instance, met {}' .format(type(data).__name__)) if data._predictor is not self.__init_predic...
[ "Add validation data.\n\n Parameters\n ----------\n data : Dataset\n Validation data.\n name : string\n Name of validation data.\n\n Returns\n -------\n self : Booster\n Booster with set validation data.\n " ]
Please provide a description of the function:def reset_parameter(self, params): if any(metric_alias in params for metric_alias in ('metric', 'metrics', 'metric_types')): self.__need_reload_eval_info = True params_str = param_dict_to_str(params) if params_str: _sa...
[ "Reset parameters of Booster.\n\n Parameters\n ----------\n params : dict\n New parameters for Booster.\n\n Returns\n -------\n self : Booster\n Booster with new parameters.\n " ]
Please provide a description of the function: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(train_set, Dataset): raise TypeError('Training data should be Dataset ...
[ "Update Booster for one iteration.\n\n Parameters\n ----------\n train_set : Dataset or None, optional (default=None)\n Training data.\n If None, last training data is used.\n fobj : callable or None, optional (default=None)\n Customized objective functio...
Please provide a description of the function:def __boost(self, grad, hess): grad = list_to_1d_numpy(grad, name='gradient') hess = list_to_1d_numpy(hess, name='hessian') assert grad.flags.c_contiguous assert hess.flags.c_contiguous if len(grad) != len(hess): r...
[ "Boost Booster for one iteration with customized gradient statistics.\n\n Note\n ----\n For multi-class task, the score is group by class_id first, then group by row_id.\n If you want to get i-th row score in j-th class, the access way is score[j * num_data + i]\n and you should g...
Please provide a description of the function:def rollback_one_iter(self): _safe_call(_LIB.LGBM_BoosterRollbackOneIter( self.handle)) self.__is_predicted_cur_iter = [False for _ in range_(self.__num_dataset)] return self
[ "Rollback one iteration.\n\n Returns\n -------\n self : Booster\n Booster with rolled back one iteration.\n " ]
Please provide a description of the function:def current_iteration(self): out_cur_iter = ctypes.c_int(0) _safe_call(_LIB.LGBM_BoosterGetCurrentIteration( self.handle, ctypes.byref(out_cur_iter))) return out_cur_iter.value
[ "Get the index of the current iteration.\n\n Returns\n -------\n cur_iter : int\n The index of the current iteration.\n " ]
Please provide a description of the function:def num_model_per_iteration(self): model_per_iter = ctypes.c_int(0) _safe_call(_LIB.LGBM_BoosterNumModelPerIteration( self.handle, ctypes.byref(model_per_iter))) return model_per_iter.value
[ "Get number of models per iteration.\n\n Returns\n -------\n model_per_iter : int\n The number of models per iteration.\n " ]
Please provide a description of the function:def num_trees(self): num_trees = ctypes.c_int(0) _safe_call(_LIB.LGBM_BoosterNumberOfTotalModel( self.handle, ctypes.byref(num_trees))) return num_trees.value
[ "Get number of weak sub-models.\n\n Returns\n -------\n num_trees : int\n The number of weak sub-models.\n " ]
Please provide a description of the function:def eval(self, data, name, feval=None): if not isinstance(data, Dataset): raise TypeError("Can only eval for Dataset instance") data_idx = -1 if data is self.train_set: data_idx = 0 else: for i in r...
[ "Evaluate for data.\n\n Parameters\n ----------\n data : Dataset\n Data for the evaluating.\n name : string\n Name of the data.\n feval : callable or None, optional (default=None)\n Customized evaluation function.\n Should accept two par...
Please provide a description of the function:def eval_valid(self, feval=None): return [item for i in range_(1, self.__num_dataset) for item in self.__inner_eval(self.name_valid_sets[i - 1], i, feval)]
[ "Evaluate for validation data.\n\n Parameters\n ----------\n feval : callable or None, optional (default=None)\n Customized evaluation function.\n Should accept two parameters: preds, train_data,\n and return (eval_name, eval_result, is_higher_better) or list of...
Please provide a description of the function:def save_model(self, filename, num_iteration=None, start_iteration=0): if num_iteration is None: num_iteration = self.best_iteration _safe_call(_LIB.LGBM_BoosterSaveModel( self.handle, ctypes.c_int(start_iteration)...
[ "Save Booster to file.\n\n Parameters\n ----------\n filename : string\n Filename to save Booster.\n num_iteration : int or None, optional (default=None)\n Index of the iteration that should be saved.\n If None, if the best iteration exists, it is saved; ...
Please provide a description of the function:def shuffle_models(self, start_iteration=0, end_iteration=-1): _safe_call(_LIB.LGBM_BoosterShuffleModels( self.handle, ctypes.c_int(start_iteration), ctypes.c_int(end_iteration))) return self
[ "Shuffle models.\n\n Parameters\n ----------\n start_iteration : int, optional (default=0)\n The first iteration that will be shuffled.\n end_iteration : int, optional (default=-1)\n The last iteration that will be shuffled.\n If <= 0, means the last avai...
Please provide a description of the function:def model_from_string(self, model_str, verbose=True): if self.handle is not None: _safe_call(_LIB.LGBM_BoosterFree(self.handle)) self._free_buffer() self.handle = ctypes.c_void_p() out_num_iterations = ctypes.c_int(0) ...
[ "Load Booster from a string.\n\n Parameters\n ----------\n model_str : string\n Model will be loaded from this string.\n verbose : bool, optional (default=True)\n Whether to print messages while loading model.\n\n Returns\n -------\n self : Boos...
Please provide a description of the function: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_len = ctypes.c_int64(0) string_buffer = ctypes.create_string_buff...
[ "Save Booster to string.\n\n Parameters\n ----------\n num_iteration : int or None, optional (default=None)\n Index of the iteration that should be saved.\n If None, if the best iteration exists, it is saved; otherwise, all iterations are saved.\n If <= 0, all i...
Please provide a description of the function: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 = ctypes.c_int64(0) string_buffer = ctypes.create_string_buffer(bu...
[ "Dump Booster to JSON format.\n\n Parameters\n ----------\n num_iteration : int or None, optional (default=None)\n Index of the iteration that should be dumped.\n If None, if the best iteration exists, it is dumped; otherwise, all iterations are dumped.\n If <= ...
Please provide a description of the function:def predict(self, data, num_iteration=None, raw_score=False, pred_leaf=False, pred_contrib=False, data_has_header=False, is_reshape=True, **kwargs): predictor = self._to_predictor(copy.deepcopy(kwargs)) if num_iteratio...
[ "Make a prediction.\n\n Parameters\n ----------\n data : string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.sparse\n Data source for prediction.\n If string, it represents the path to txt file.\n num_iteration : int or None, optional (default=None...
Please provide a description of the function: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.') predictor = self._to_predictor(copy.deepcopy(kwargs)) leaf_preds = predic...
[ "Refit the existing Booster by new data.\n\n Parameters\n ----------\n data : string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.sparse\n Data source for refit.\n If string, it represents the path to txt file.\n label : list, numpy 1-D array or pa...
Please provide a description of the function:def get_leaf_output(self, tree_id, leaf_id): ret = ctypes.c_double(0) _safe_call(_LIB.LGBM_BoosterGetLeafValue( self.handle, ctypes.c_int(tree_id), ctypes.c_int(leaf_id), ctypes.byref(ret))) ret...
[ "Get the output of a leaf.\n\n Parameters\n ----------\n tree_id : int\n The index of the tree.\n leaf_id : int\n The index of the leaf in the tree.\n\n Returns\n -------\n result : float\n The output of the leaf.\n " ]
Please provide a description of the function:def _to_predictor(self, pred_parameter=None): predictor = _InnerPredictor(booster_handle=self.handle, pred_parameter=pred_parameter) predictor.pandas_categorical = self.pandas_categorical return predictor
[ "Convert to predictor." ]
Please provide a description of the function:def num_feature(self): out_num_feature = ctypes.c_int(0) _safe_call(_LIB.LGBM_BoosterGetNumFeature( self.handle, ctypes.byref(out_num_feature))) return out_num_feature.value
[ "Get number of features.\n\n Returns\n -------\n num_feature : int\n The number of features.\n " ]
Please provide a description of the function: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(255) for i in range_(num_feature)] ptr_string_buffers = (ctypes.c_char...
[ "Get names of features.\n\n Returns\n -------\n result : list\n List with names of features.\n " ]
Please provide a description of the function:def feature_importance(self, importance_type='split', iteration=None): if iteration is None: iteration = self.best_iteration if importance_type == "split": importance_type_int = 0 elif importance_type == "gain": ...
[ "Get feature importances.\n\n Parameters\n ----------\n importance_type : string, optional (default=\"split\")\n How the importance is calculated.\n If \"split\", result contains numbers of times the feature is used in a model.\n If \"gain\", result contains tot...
Please provide a description of the function:def get_split_value_histogram(self, feature, bins=None, xgboost_style=False): def add(root): if 'split_index' in root: # non-leaf if feature_names is not None and isinstance(feature, string_type): ...
[ "Get split value histogram for the specified feature.\n\n Parameters\n ----------\n feature : int or string\n The feature name or index the histogram is calculated for.\n If int, interpreted as index.\n If string, interpreted as name.\n\n Note\n ...
Please provide a description of the function: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.__get_eval_info() ret = [] if self.__num_inner_eval > 0...
[ "Evaluate training or validation data." ]
Please provide a description of the function: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[data_idx] is None: if data_idx == 0: ...
[ "Predict for training and validation dataset." ]
Please provide a description of the function: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(_LIB.LGBM_BoosterGetEvalCounts( ...
[ "Get inner evaluation count and names." ]
Please provide a description of the function:def set_attr(self, **kwargs): for key, value in kwargs.items(): if value is not None: if not isinstance(value, string_type): raise ValueError("Only string values are accepted") self.__attr[key] ...
[ "Set attributes to the Booster.\n\n Parameters\n ----------\n **kwargs\n The attributes to set.\n Setting a value to None deletes an attribute.\n\n Returns\n -------\n self : Booster\n Booster with set attributes.\n " ]
Please provide a description of the function: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(os.path.abspath(os.path.expanduser(__file__))) dll_path = [curr_path, ...
[ "Find the path to LightGBM library files.\n\n Returns\n -------\n lib_path: list of strings\n List of all found library paths to LightGBM.\n " ]
Please provide a description of the function:def json_default_with_numpy(obj): if isinstance(obj, (np.integer, np.floating, np.bool_)): return obj.item() elif isinstance(obj, np.ndarray): return obj.tolist() else: return obj
[ "Convert numpy classes to JSON serializable objects." ]
Please provide a description of the function:def _format_eval_result(value, show_stdv=True): 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]) ...
[ "Format metric string." ]
Please provide a description of the function:def print_evaluation(period=1, show_stdv=True): def _callback(env): if period > 0 and env.evaluation_result_list and (env.iteration + 1) % period == 0: result = '\t'.join([_format_eval_result(x, show_stdv) for x in env.evaluation_result_list]) ...
[ "Create a callback that prints the evaluation results.\n\n Parameters\n ----------\n period : int, optional (default=1)\n The period to print the evaluation results.\n show_stdv : bool, optional (default=True)\n Whether to show stdv (if provided).\n\n Returns\n -------\n callback ...
Please provide a description of the function:def record_evaluation(eval_result): if not isinstance(eval_result, dict): raise TypeError('Eval_result should be a dictionary') eval_result.clear() def _init(env): for data_name, _, _, _ in env.evaluation_result_list: eval_result...
[ "Create a callback that records the evaluation history into ``eval_result``.\n\n Parameters\n ----------\n eval_result : dict\n A dictionary to store the evaluation results.\n\n Returns\n -------\n callback : function\n The callback that records the evaluation history into the passed ...
Please provide a description of the function:def reset_parameter(**kwargs): def _callback(env): new_parameters = {} for key, value in kwargs.items(): if key in ['num_class', 'num_classes', 'boosting', 'boost', 'boosting_type', 'metric', ...
[ "Create a callback that resets the parameter after the first iteration.\n\n Note\n ----\n The initial parameter will still take in-effect on first iteration.\n\n Parameters\n ----------\n **kwargs : value should be list or function\n List of parameters for each boosting round\n or a ...
Please provide a description of the function:def early_stopping(stopping_rounds, first_metric_only=False, verbose=True): best_score = [] best_iter = [] best_score_list = [] cmp_op = [] enabled = [True] def _init(env): enabled[0] = not any((boost_alias in env.params ...
[ "Create a callback that activates early stopping.\n\n Note\n ----\n Activates early stopping.\n The model will train until the validation score stops improving.\n Validation score needs to improve at least every ``early_stopping_rounds`` round(s)\n to continue training.\n Requires at least one ...
Please provide a description of the function:def train(params, train_set, num_boost_round=100, valid_sets=None, valid_names=None, fobj=None, feval=None, init_model=None, feature_name='auto', categorical_feature='auto', early_stopping_rounds=None, evals_result=None, verb...
[ "Perform the training with given parameters.\n\n Parameters\n ----------\n params : dict\n Parameters for training.\n train_set : Dataset\n Data to be trained on.\n num_boost_round : int, optional (default=100)\n Number of boosting iterations.\n valid_sets : list of Datasets o...
Please provide a description of the function:def _make_n_folds(full_data, folds, nfold, params, seed, fpreproc=None, stratified=True, shuffle=True, eval_train_metric=False): full_data = full_data.construct() num_data = full_data.num_data() if folds is not None: if not hasattr(...
[ "Make a n-fold list of Booster from random indices." ]
Please provide a description of the function:def _agg_cv_result(raw_results, eval_train_metric=False): cvmap = collections.defaultdict(list) metric_type = {} for one_result in raw_results: for one_line in one_result: if eval_train_metric: key = "{} {}".format(one_lin...
[ "Aggregate cross-validation results." ]
Please provide a description of the function:def cv(params, train_set, num_boost_round=100, folds=None, nfold=5, stratified=True, shuffle=True, metrics=None, fobj=None, feval=None, init_model=None, feature_name='auto', categorical_feature='auto', early_stopping_rounds=None, fpreproc=None, ...
[ "Perform the cross-validation with given paramaters.\n\n Parameters\n ----------\n params : dict\n Parameters for Booster.\n train_set : Dataset\n Data to be trained on.\n num_boost_round : int, optional (default=100)\n Number of boosting iterations.\n folds : generator or ite...
Please provide a description of the function: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." ]
Please provide a description of the function:def experiment(objective, label_type, data): np.random.seed(0) nrounds = 5 lgb_data = data['lgb_with_' + label_type + '_labels'] params = { 'objective': objective, 'feature_fraction': 1, 'bagging_fraction': 1, 'verbose': -...
[ "Measure performance of an objective.\n\n Parameters\n ----------\n objective : string 'binary' or 'xentropy'\n Objective function.\n label_type : string 'binary' or 'probability'\n Type of the label.\n data : dict\n Data for training.\n\n Returns\n -------\n result : di...
Please provide a description of the function: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 elements.' % obj_name)
[ "Check object is not tuple or does not have 2 elements." ]
Please provide a description of the function: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, ...
[ "Plot model's feature importances.\n\n Parameters\n ----------\n booster : Booster or LGBMModel\n Booster or LGBMModel instance which feature importance should be plotted.\n ax : matplotlib.axes.Axes or None, optional (default=None)\n Target axes instance.\n If None, new figure and ...
Please provide a description of the function: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): if MATPLOTLIB_INSTA...
[ "Plot one metric during training.\n\n Parameters\n ----------\n booster : dict or LGBMModel\n Dictionary returned from ``lightgbm.train()`` or LGBMModel instance.\n metric : string or None, optional (default=None)\n The metric name to plot.\n Only one metric supported because differ...
Please provide a description of the function:def _to_graphviz(tree_info, show_info, feature_names, precision=None, **kwargs): if GRAPHVIZ_INSTALLED: from graphviz import Digraph else: raise ImportError('You must install graphviz to plot tree.') def add(root, parent=None, decision=None)...
[ "Convert specified tree to graphviz instance.\n\n See:\n - https://graphviz.readthedocs.io/en/stable/api.html#digraph\n ", "Recursively add node or edge." ]
Please provide a description of the function: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, ...
[ "Create a digraph representation of specified tree.\n\n Note\n ----\n For more information please visit\n https://graphviz.readthedocs.io/en/stable/api.html#digraph.\n\n Parameters\n ----------\n booster : Booster or LGBMModel\n Booster or LGBMModel instance to be converted.\n tree_in...
Please provide a description of the function:def plot_tree(booster, ax=None, tree_index=0, figsize=None, old_graph_attr=None, old_node_attr=None, old_edge_attr=None, show_info=None, precision=None, **kwargs): if MATPLOTLIB_INSTALLED: import matplotlib.pyplot as plt i...
[ "Plot specified tree.\n\n Note\n ----\n It is preferable to use ``create_tree_digraph()`` because of its lossless quality\n and returned objects can be also rendered and displayed directly inside a Jupyter notebook.\n\n Parameters\n ----------\n booster : Booster or LGBMModel\n Booster o...
Please provide a description of the function:def cpp_flag(compiler): standards = ['-std=c++14', '-std=c++11', '-std=c++0x'] for standard in standards: if has_flag(compiler, [standard]): return standard raise RuntimeError( 'Unsupported compiler -- at least C++0x support ' ...
[ "Return the -std=c++[0x/11/14] compiler flag.\n The c++14 is preferred over c++0x/11 (when it is available).\n " ]
Please provide a description of the function:def find_nearest_neighbor(query, vectors, ban_set, cossims=None): if cossims is None: cossims = np.matmul(vectors, query, out=cossims) else: np.matmul(vectors, query, out=cossims) rank = len(cossims) - 1 result_i = np.argpartition(cossims...
[ "\n query is a 1d numpy array corresponding to the vector to which you want to\n find the closest vector\n vectors is a 2d numpy array corresponding to the vectors you want to consider\n ban_set is a set of indicies within vectors you want to ignore for nearest match\n cossims is a 1d numpy array of ...
Please provide a description of the function: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...
[ "\n Train a supervised model and return a model object.\n\n input must be a filepath. The input text does not need to be tokenized\n as per the tokenize function, but it must be preprocessed and encoded\n as UTF-8. You might want to consult standard preprocessing scripts such\n as tokenizer.perl ment...
Please provide a description of the function:def get_word_vector(self, word): dim = self.get_dimension() b = fasttext.Vector(dim) self.f.getWordVector(b, word) return np.array(b)
[ "Get the vector representation of word." ]
Please provide a description of the function:def get_sentence_vector(self, text): if text.find('\n') != -1: raise ValueError( "predict processes one line at a time (remove \'\\n\')" ) text += "\n" dim = self.get_dimension() b = fasttext.Ve...
[ "\n Given a string, get a single vector represenation. This function\n assumes to be given a single line of text. We split words on\n whitespace (space, newline, tab, vertical tab) and the control\n characters carriage return, formfeed and the null character.\n " ]
Please provide a description of the function:def get_subwords(self, word, on_unicode_error='strict'): pair = self.f.getSubwords(word, on_unicode_error) return pair[0], np.array(pair[1])
[ "\n Given a word, get the subwords and their indicies.\n " ]
Please provide a description of the function:def get_input_vector(self, ind): dim = self.get_dimension() b = fasttext.Vector(dim) self.f.getInputVector(b, ind) return np.array(b)
[ "\n Given an index, get the corresponding vector of the Input Matrix.\n " ]
Please provide a description of the function:def predict(self, text, k=1, threshold=0.0, on_unicode_error='strict'): def check(entry): if entry.find('\n') != -1: raise ValueError( "predict processes one line at a time (remove \'\\n\')" ) ...
[ "\n Given a string, get a list of labels and a list of\n corresponding probabilities. k controls the number\n of returned labels. A choice of 5, will return the 5\n most probable labels. By default this returns only\n the most likely label and probability. threshold filters\n ...
Please provide a description of the function:def get_input_matrix(self): if self.f.isQuant(): raise ValueError("Can't get quantized Matrix") return np.array(self.f.getInputMatrix())
[ "\n Get a copy of the full input matrix of a Model. This only\n works if the model is not quantized.\n " ]
Please provide a description of the function:def get_output_matrix(self): if self.f.isQuant(): raise ValueError("Can't get quantized Matrix") return np.array(self.f.getOutputMatrix())
[ "\n Get a copy of the full output matrix of a Model. This only\n works if the model is not quantized.\n " ]
Please provide a description of the function:def get_words(self, include_freq=False, on_unicode_error='strict'): pair = self.f.getVocab(on_unicode_error) if include_freq: return (pair[0], np.array(pair[1])) else: return pair[0]
[ "\n Get the entire list of words of the dictionary optionally\n including the frequency of the individual words. This\n does not include any subwords. For that please consult\n the function get_subwords.\n " ]
Please provide a description of the function:def get_labels(self, include_freq=False, on_unicode_error='strict'): a = self.f.getArgs() if a.model == model_name.supervised: pair = self.f.getLabels(on_unicode_error) if include_freq: return (pair[0], np.arra...
[ "\n Get the entire list of labels of the dictionary optionally\n including the frequency of the individual labels. Unsupervised\n models use words as labels, which is why get_labels\n will call and return get_words for this type of\n model.\n " ]
Please provide a description of the function:def get_line(self, text, on_unicode_error='strict'): def check(entry): if entry.find('\n') != -1: raise ValueError( "get_line processes one line at a time (remove \'\\n\')" ) entry ...
[ "\n Split a line of text into words and labels. Labels must start with\n the prefix used to create the model (__label__ by default).\n " ]
Please provide a description of the function:def quantize( self, input=None, qout=False, cutoff=0, retrain=False, epoch=None, lr=None, thread=None, verbose=None, dsub=2, qnorm=False ): a = self.f.getArgs() ...
[ "\n Quantize the model reducing the size of the model and\n it's memory footprint.\n " ]
Please provide a description of the function:def forward(self, # pylint: disable=arguments-differ inputs: PackedSequence, initial_state: Optional[Tuple[torch.Tensor, torch.Tensor]] = None ) -> Tuple[PackedSequence, Tuple[torch.Tensor, torch.Tensor]]: if n...
[ "\n Parameters\n ----------\n inputs : ``PackedSequence``, required.\n A batch first ``PackedSequence`` to run the stacked LSTM over.\n initial_state : Tuple[torch.Tensor, torch.Tensor], optional, (default = None)\n A tuple (state, memory) representing the initial h...
Please provide a description of the function:def from_params(cls, params: Iterable[Tuple[str, Params]] = ()) -> Optional['RegularizerApplicator']: if not params: return None instantiated_regularizers = [] for parameter_regex, regularizer_params in params: if isi...
[ "\n Converts a List of pairs (regex, params) into an RegularizerApplicator.\n This list should look like\n\n [[\"regex1\", {\"type\": \"l2\", \"alpha\": 0.01}], [\"regex2\", \"l1\"]]\n\n where each parameter receives the penalty corresponding to the first regex\n that matches its ...
Please provide a description of the function:def list_available(cls) -> List[str]: keys = list(Registrable._registry[cls].keys()) default = cls.default_implementation if default is None: return keys elif default not in keys: message = "Default implementa...
[ "List default first if it exists" ]
Please provide a description of the function:def sanitize(x: Any) -> Any: # pylint: disable=invalid-name,too-many-return-statements if isinstance(x, (str, float, int, bool)): # x is already serializable return x elif isinstance(x, torch.Tensor): # tensor needs to be converted to a ...
[ "\n Sanitize turns PyTorch and Numpy types into basic Python types so they\n can be serialized into JSON.\n " ]
Please provide a description of the function:def group_by_count(iterable: List[Any], count: int, default_value: Any) -> List[List[Any]]: return [list(l) for l in zip_longest(*[iter(iterable)] * count, fillvalue=default_value)]
[ "\n Takes a list and groups it into sublists of size ``count``, using ``default_value`` to pad the\n list at the end if the list is not divisable by ``count``.\n\n For example:\n >>> group_by_count([1, 2, 3, 4, 5, 6, 7], 3, 0)\n [[1, 2, 3], [4, 5, 6], [7, 0, 0]]\n\n This is a short method, but it'...
Please provide a description of the function:def lazy_groups_of(iterator: Iterator[A], group_size: int) -> Iterator[List[A]]: return iter(lambda: list(islice(iterator, 0, group_size)), [])
[ "\n Takes an iterator and batches the individual instances into lists of the\n specified size. The last list may be smaller if there are instances left over.\n " ]
Please provide a description of the function:def pad_sequence_to_length(sequence: List, desired_length: int, default_value: Callable[[], Any] = lambda: 0, padding_on_right: bool = True) -> List: # Truncates the sequence to the des...
[ "\n Take a list of objects and pads it to the desired length, returning the padded list. The\n original list is not modified.\n\n Parameters\n ----------\n sequence : List\n A list of objects to be padded.\n\n desired_length : int\n Maximum length of each sequence. Longer sequences ...
Please provide a description of the function:def add_noise_to_dict_values(dictionary: Dict[A, float], noise_param: float) -> Dict[A, float]: new_dict = {} for key, value in dictionary.items(): noise_value = value * noise_param noise = random.uniform(-noise_value, noise_value) new_di...
[ "\n Returns a new dictionary with noise added to every key in ``dictionary``. The noise is\n uniformly distributed within ``noise_param`` percent of the value for every value in the\n dictionary.\n " ]
Please provide a description of the function:def namespace_match(pattern: str, namespace: str): if pattern[0] == '*' and namespace.endswith(pattern[1:]): return True elif pattern == namespace: return True return False
[ "\n Matches a namespace pattern against a namespace string. For example, ``*tags`` matches\n ``passage_tags`` and ``question_tags`` and ``tokens`` matches ``tokens`` but not\n ``stemmed_tokens``.\n " ]
Please provide a description of the function:def prepare_environment(params: Params): seed = params.pop_int("random_seed", 13370) numpy_seed = params.pop_int("numpy_seed", 1337) torch_seed = params.pop_int("pytorch_seed", 133) if seed is not None: random.seed(seed) if numpy_seed is not...
[ "\n Sets random seeds for reproducible experiments. This may not work as expected\n if you use this from within a python project in which you have already imported Pytorch.\n If you use the scripts/run_model.py entry point to training models with this library,\n your experiments should be reasonably rep...
Please provide a description of the function: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.isatty(): file_friendly_logging = True Tqdm.set_slower_...
[ "\n This function configures 3 global logging attributes - streaming stdout and stderr\n to a file as well as the terminal, setting the formatting for the python logging\n library and setting the interval frequency for the Tqdm progress bar.\n\n Note that this function does not set the logging level, wh...
Please provide a description of the function:def cleanup_global_logging(stdout_handler: logging.FileHandler) -> None: stdout_handler.close() logging.getLogger().removeHandler(stdout_handler) if isinstance(sys.stdout, TeeLogger): sys.stdout = sys.stdout.cleanup() if isinstance(sys.stderr, T...
[ "\n This function closes any open file handles and logs set up by `prepare_global_logging`.\n\n Parameters\n ----------\n stdout_handler : ``logging.FileHandler``, required.\n The file handler returned from `prepare_global_logging`, attached to the global logger.\n " ]
Please provide a description of the function:def get_spacy_model(spacy_model_name: str, pos_tags: bool, parse: bool, ner: bool) -> SpacyModelType: options = (spacy_model_name, pos_tags, parse, ner) if options not in LOADED_SPACY_MODELS: disable = ['vectors', 'textcat'] if not pos_tags: ...
[ "\n In order to avoid loading spacy models a whole bunch of times, we'll save references to them,\n keyed by the options we used to create the spacy model, so any particular configuration only\n gets loaded once.\n " ]
Please provide a description of the function: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`. And if it's already there, addin...
[ "\n Import all submodules under the given package.\n Primarily useful so that people using AllenNLP as a library\n can specify their own custom packages and have their custom\n classes get loaded and registered.\n " ]