Code
stringlengths 103
85.9k
| Summary
sequencelengths 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,
free_raw_data=self.free_raw_data)
ret._predictor = self._predictor
ret.pandas_categorical = self.pandas_categorical
ret.used_indices = used_indices
return ret | [
"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 -------\n subset : Dataset\n Subset of the current Dataset.\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(
self.handle,
c_str(field_name),
None,
ctypes.c_int(0),
ctypes.c_int(FIELD_TYPE_MAPPER[field_name])))
return self
dtype = np.float32
if field_name == 'group':
dtype = np.int32
elif field_name == 'init_score':
dtype = np.float64
data = list_to_1d_numpy(data, dtype, name=field_name)
if data.dtype == np.float32 or data.dtype == np.float64:
ptr_data, type_data, _ = c_float_array(data)
elif data.dtype == np.int32:
ptr_data, type_data, _ = c_int_array(data)
else:
raise TypeError("Excepted np.float32/64 or np.int32, meet type({})".format(data.dtype))
if type_data != FIELD_TYPE_MAPPER[field_name]:
raise TypeError("Input type error for set_field")
_safe_call(_LIB.LGBM_DatasetSetField(
self.handle,
c_str(field_name),
ptr_data,
ctypes.c_int(len(data)),
ctypes.c_int(type_data)))
return self | [
"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 Dataset with set property.\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)()
_safe_call(_LIB.LGBM_DatasetGetField(
self.handle,
c_str(field_name),
ctypes.byref(tmp_out_len),
ctypes.byref(ret),
ctypes.byref(out_type)))
if out_type.value != FIELD_TYPE_MAPPER[field_name]:
raise TypeError("Return type error for get_field")
if tmp_out_len.value == 0:
return None
if out_type.value == C_API_DTYPE_INT32:
return cint32_array_to_numpy(ctypes.cast(ret, ctypes.POINTER(ctypes.c_int32)), tmp_out_len.value)
elif out_type.value == C_API_DTYPE_FLOAT32:
return cfloat32_array_to_numpy(ctypes.cast(ret, ctypes.POINTER(ctypes.c_float)), tmp_out_len.value)
elif out_type.value == C_API_DTYPE_FLOAT64:
return cfloat64_array_to_numpy(ctypes.cast(ret, ctypes.POINTER(ctypes.c_double)), tmp_out_len.value)
elif out_type.value == C_API_DTYPE_INT8:
return cint8_array_to_numpy(ctypes.cast(ret, ctypes.POINTER(ctypes.c_int8)), tmp_out_len.value)
else:
raise TypeError("Unknown type") | [
"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 = categorical_feature
return self._free_handle()
elif categorical_feature == 'auto':
warnings.warn('Using categorical_feature in Dataset.')
return self
else:
warnings.warn('categorical_feature in Dataset is overridden.\n'
'New categorical_feature is {}'.format(sorted(list(categorical_feature))))
self.categorical_feature = categorical_feature
return self._free_handle()
else:
raise LightGBMError("Cannot set categorical feature after freed raw data, "
"set free_raw_data=False when construct Dataset to avoid this.") | [
"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("Cannot set predictor after freed raw data, "
"set free_raw_data=False when construct Dataset to avoid this.") | [
"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 common upstrem reference
if self.get_ref_chain().intersection(reference.get_ref_chain()):
return self
if self.data is not None:
self.reference = reference
return self._free_handle()
else:
raise LightGBMError("Cannot set reference after freed raw data, "
"set free_raw_data=False when construct Dataset to avoid this.") | [
"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():
raise ValueError("Length of feature_name({}) and num_feature({}) don't match"
.format(len(feature_name), self.num_feature()))
c_feature_name = [c_str(name) for name in feature_name]
_safe_call(_LIB.LGBM_DatasetSetFeatureNames(
self.handle,
c_array(ctypes.c_char_p, c_feature_name),
ctypes.c_int(len(feature_name))))
return self | [
"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')
self.set_field('weight', weight)
return self | [
"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', init_score)
return self | [
"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 scipy.sparse.issparse(self.data):
self.data = self.data[self.used_indices, :]
elif isinstance(self.data, DataFrame):
self.data = self.data.iloc[self.used_indices].copy()
elif isinstance(self.data, DataTable):
self.data = self.data[self.used_indices, :]
else:
warnings.warn("Cannot subset {} type of raw data.\n"
"Returning original raw data".format(type(self.data).__name__))
self.need_slice = False
return self.data | [
"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.diff(self.group)
return self.group | [
"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:
raise LightGBMError("Cannot get num_data before construct dataset") | [
"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
else:
raise LightGBMError("Cannot get num_feature before construct dataset") | [
"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.reference not in ref_chain):
head = head.reference
else:
break
else:
break
return ref_chain | [
"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 number of references.\n\n Returns\n -------\n ref_chain : set of Dataset\n Chain of references of the Datasets.\n "
] |
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, other.handle))
return self | [
"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 Dataset with the new features added.\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 self.\n "
] |
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),
ctypes.c_int(listen_time_out),
ctypes.c_int(num_machines)))
self.network = True
return self | [
"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 Socket time-out in minutes.\n num_machines : int, optional (default=1)\n The number of machines for parallel learning application.\n\n Returns\n -------\n self : Booster\n Booster with set network.\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_predictor:
raise LightGBMError("Add validation data failed, "
"you should use same predictor for these data")
_safe_call(_LIB.LGBM_BoosterAddValidData(
self.handle,
data.construct().handle))
self.valid_sets.append(data)
self.name_valid_sets.append(name)
self.__num_dataset += 1
self.__inner_predict_buffer.append(None)
self.__is_predicted_cur_iter.append(False)
return self | [
"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:
_safe_call(_LIB.LGBM_BoosterResetParameter(
self.handle,
c_str(params_str)))
self.params.update(params)
return self | [
"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 instance, met {}'
.format(type(train_set).__name__))
if train_set._predictor is not self.__init_predictor:
raise LightGBMError("Replace training data failed, "
"you should use same predictor for these data")
self.train_set = train_set
_safe_call(_LIB.LGBM_BoosterResetTrainingData(
self.handle,
self.train_set.construct().handle))
self.__inner_predict_buffer[0] = None
is_finished = ctypes.c_int(0)
if fobj is None:
if self.__set_objective_to_none:
raise LightGBMError('Cannot update due to null objective function.')
_safe_call(_LIB.LGBM_BoosterUpdateOneIter(
self.handle,
ctypes.byref(is_finished)))
self.__is_predicted_cur_iter = [False for _ in range_(self.__num_dataset)]
return is_finished.value == 1
else:
if not self.__set_objective_to_none:
self.reset_parameter({"objective": "none"}).__set_objective_to_none = True
grad, hess = fobj(self.__inner_predict(0), self.train_set)
return self.__boost(grad, hess) | [
"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 function.\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 group grad and hess in this way as well.\n\n Returns\n -------\n is_finished : bool\n Whether the update was successfully finished.\n "
] |
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):
raise ValueError("Lengths of gradient({}) and hessian({}) don't match"
.format(len(grad), len(hess)))
is_finished = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterUpdateOneIterCustom(
self.handle,
grad.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
hess.ctypes.data_as(ctypes.POINTER(ctypes.c_float)),
ctypes.byref(is_finished)))
self.__is_predicted_cur_iter = [False for _ in range_(self.__num_dataset)]
return is_finished.value == 1 | [
"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 group grad and hess in this way as well.\n\n Parameters\n ----------\n grad : 1-D numpy array or 1-D list\n The first order derivative (gradient).\n hess : 1-D numpy array or 1-D list\n The second order derivative (Hessian).\n\n Returns\n -------\n is_finished : bool\n Whether the boost was successfully finished.\n "
] |
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 range_(len(self.valid_sets)):
if data is self.valid_sets[i]:
data_idx = i + 1
break
# need to push new valid data
if data_idx == -1:
self.add_valid(data, name)
data_idx = self.__num_dataset - 1
return self.__inner_eval(name, data_idx, feval) | [
"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 parameters: preds, train_data,\n and return (eval_name, eval_result, is_higher_better) or list of such tuples.\n For multi-class task, the preds is group by class_id first, then group by row_id.\n If you want to get i-th row preds in j-th class, the access way is preds[j * num_data + i].\n\n Returns\n -------\n result : list\n List with evaluation results.\n "
] |
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 such tuples.\n For multi-class task, the preds is group by class_id first, then group by row_id.\n If you want to get i-th row preds in j-th class, the access way is preds[j * num_data + i].\n\n Returns\n -------\n result : list\n List with evaluation results.\n "
] |
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),
ctypes.c_int(num_iteration),
c_str(filename)))
_dump_pandas_categorical(self.pandas_categorical, filename)
return self | [
"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; otherwise, all iterations are saved.\n If <= 0, all iterations are saved.\n start_iteration : int, optional (default=0)\n Start index of the iteration that should be saved.\n\n Returns\n -------\n self : Booster\n Returns self.\n "
] |
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 available iteration.\n\n Returns\n -------\n self : Booster\n Booster with shuffled models.\n "
] |
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)
_safe_call(_LIB.LGBM_BoosterLoadModelFromString(
c_str(model_str),
ctypes.byref(out_num_iterations),
ctypes.byref(self.handle)))
out_num_class = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterGetNumClasses(
self.handle,
ctypes.byref(out_num_class)))
if verbose:
print('Finished loading model, total used %d iterations' % int(out_num_iterations.value))
self.__num_class = out_num_class.value
self.pandas_categorical = _load_pandas_categorical(model_str=model_str)
return self | [
"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 : Booster\n Loaded Booster object.\n "
] |
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_buffer(buffer_len)
ptr_string_buffer = ctypes.c_char_p(*[ctypes.addressof(string_buffer)])
_safe_call(_LIB.LGBM_BoosterSaveModelToString(
self.handle,
ctypes.c_int(start_iteration),
ctypes.c_int(num_iteration),
ctypes.c_int64(buffer_len),
ctypes.byref(tmp_out_len),
ptr_string_buffer))
actual_len = tmp_out_len.value
# if buffer length is not long enough, re-allocate a buffer
if actual_len > buffer_len:
string_buffer = ctypes.create_string_buffer(actual_len)
ptr_string_buffer = ctypes.c_char_p(*[ctypes.addressof(string_buffer)])
_safe_call(_LIB.LGBM_BoosterSaveModelToString(
self.handle,
ctypes.c_int(start_iteration),
ctypes.c_int(num_iteration),
ctypes.c_int64(actual_len),
ctypes.byref(tmp_out_len),
ptr_string_buffer))
ret = string_buffer.value.decode()
ret += _dump_pandas_categorical(self.pandas_categorical)
return ret | [
"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 iterations are saved.\n start_iteration : int, optional (default=0)\n Start index of the iteration that should be saved.\n\n Returns\n -------\n str_repr : string\n String representation of Booster.\n "
] |
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(buffer_len)
ptr_string_buffer = ctypes.c_char_p(*[ctypes.addressof(string_buffer)])
_safe_call(_LIB.LGBM_BoosterDumpModel(
self.handle,
ctypes.c_int(start_iteration),
ctypes.c_int(num_iteration),
ctypes.c_int64(buffer_len),
ctypes.byref(tmp_out_len),
ptr_string_buffer))
actual_len = tmp_out_len.value
# if buffer length is not long enough, reallocate a buffer
if actual_len > buffer_len:
string_buffer = ctypes.create_string_buffer(actual_len)
ptr_string_buffer = ctypes.c_char_p(*[ctypes.addressof(string_buffer)])
_safe_call(_LIB.LGBM_BoosterDumpModel(
self.handle,
ctypes.c_int(start_iteration),
ctypes.c_int(num_iteration),
ctypes.c_int64(actual_len),
ctypes.byref(tmp_out_len),
ptr_string_buffer))
ret = json.loads(string_buffer.value.decode())
ret['pandas_categorical'] = json.loads(json.dumps(self.pandas_categorical,
default=json_default_with_numpy))
return ret | [
"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 <= 0, all iterations are dumped.\n start_iteration : int, optional (default=0)\n Start index of the iteration that should be dumped.\n\n Returns\n -------\n json_repr : dict\n JSON format of Booster.\n "
] |
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_iteration is None:
num_iteration = self.best_iteration
return predictor.predict(data, num_iteration,
raw_score, pred_leaf, pred_contrib,
data_has_header, is_reshape) | [
"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)\n Limit number of iterations in the prediction.\n If None, if the best iteration exists, it is used; otherwise, all iterations are used.\n If <= 0, all iterations are used (no limits).\n raw_score : bool, optional (default=False)\n Whether to predict raw scores.\n pred_leaf : bool, optional (default=False)\n Whether to predict leaf index.\n pred_contrib : bool, optional (default=False)\n Whether to predict feature contributions.\n\n Note\n ----\n If you want to get more explanations for your model's predictions using SHAP values,\n like SHAP interaction values,\n you can install the shap package (https://github.com/slundberg/shap).\n Note that unlike the shap package, with ``pred_contrib`` we return a matrix with an extra\n column, where the last column is the expected value.\n\n data_has_header : bool, optional (default=False)\n Whether the data has header.\n Used only if data is string.\n is_reshape : bool, optional (default=True)\n If True, result is reshaped to [nrow, ncol].\n **kwargs\n Other parameters for the prediction.\n\n Returns\n -------\n result : numpy array\n Prediction result.\n "
] |
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 = predictor.predict(data, -1, pred_leaf=True)
nrow, ncol = leaf_preds.shape
train_set = Dataset(data, label, silent=True)
new_booster = Booster(self.params, train_set, silent=True)
# Copy models
_safe_call(_LIB.LGBM_BoosterMerge(
new_booster.handle,
predictor.handle))
leaf_preds = leaf_preds.reshape(-1)
ptr_data, type_ptr_data, _ = c_int_array(leaf_preds)
_safe_call(_LIB.LGBM_BoosterRefit(
new_booster.handle,
ptr_data,
ctypes.c_int(nrow),
ctypes.c_int(ncol)))
new_booster.network = self.network
new_booster.__attr = self.__attr.copy()
return new_booster | [
"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 pandas Series / one-column DataFrame\n Label for refit.\n decay_rate : float, optional (default=0.9)\n Decay rate of refit,\n will use ``leaf_output = decay_rate * old_leaf_output + (1.0 - decay_rate) * new_leaf_output`` to refit trees.\n **kwargs\n Other parameters for refit.\n These parameters will be passed to ``predict`` method.\n\n Returns\n -------\n result : Booster\n Refitted Booster.\n "
] |
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)))
return ret.value | [
"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_p * num_feature)(*map(ctypes.addressof, string_buffers))
_safe_call(_LIB.LGBM_BoosterGetFeatureNames(
self.handle,
ctypes.byref(tmp_out_len),
ptr_string_buffers))
if num_feature != tmp_out_len.value:
raise ValueError("Length of feature names doesn't equal with num_feature")
return [string_buffers[i].value.decode() for i in range_(num_feature)] | [
"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":
importance_type_int = 1
else:
importance_type_int = -1
result = np.zeros(self.num_feature(), dtype=np.float64)
_safe_call(_LIB.LGBM_BoosterFeatureImportance(
self.handle,
ctypes.c_int(iteration),
ctypes.c_int(importance_type_int),
result.ctypes.data_as(ctypes.POINTER(ctypes.c_double))))
if importance_type_int == 0:
return result.astype(int)
else:
return result | [
"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 total gains of splits which use the feature.\n iteration : int or None, optional (default=None)\n Limit number of iterations in the feature importance calculation.\n If None, if the best iteration exists, it is used; otherwise, all trees are used.\n If <= 0, all trees are used (no limits).\n\n Returns\n -------\n result : numpy array\n Array with feature importances.\n "
] |
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):
split_feature = feature_names[root['split_feature']]
else:
split_feature = root['split_feature']
if split_feature == feature:
if isinstance(root['threshold'], string_type):
raise LightGBMError('Cannot compute split value histogram for the categorical feature')
else:
values.append(root['threshold'])
add(root['left_child'])
add(root['right_child'])
model = self.dump_model()
feature_names = model.get('feature_names')
tree_infos = model['tree_info']
values = []
for tree_info in tree_infos:
add(tree_info['tree_structure'])
if bins is None or isinstance(bins, integer_types) and xgboost_style:
n_unique = len(np.unique(values))
bins = max(min(n_unique, bins) if bins is not None else n_unique, 1)
hist, bin_edges = np.histogram(values, bins=bins)
if xgboost_style:
ret = np.column_stack((bin_edges[1:], hist))
ret = ret[ret[:, 1] > 0]
if PANDAS_INSTALLED:
return DataFrame(ret, columns=['SplitValue', 'Count'])
else:
return ret
else:
return hist, bin_edges | [
"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 ----\n Categorical features are not supported.\n\n bins : int, string or None, optional (default=None)\n The maximum number of bins.\n If None, or int and > number of unique split values and ``xgboost_style=True``,\n the number of bins equals number of unique split values.\n If string, it should be one from the list of the supported values by ``numpy.histogram()`` function.\n xgboost_style : bool, optional (default=False)\n Whether the returned result should be in the same form as it is in XGBoost.\n If False, the returned value is tuple of 2 numpy arrays as it is in ``numpy.histogram()`` function.\n If True, the returned value is matrix, in which the first column is the right edges of non-empty bins\n and the second one is the histogram values.\n\n Returns\n -------\n result_tuple : tuple of 2 numpy arrays\n If ``xgboost_style=False``, the values of the histogram of used splitting values for the specified feature\n and the bin edges.\n result_array_like : numpy array or pandas DataFrame (if pandas is installed)\n If ``xgboost_style=True``, the histogram of used splitting values for the specified feature.\n ",
"Recursively add thresholds."
] |
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:
result = np.zeros(self.__num_inner_eval, dtype=np.float64)
tmp_out_len = ctypes.c_int(0)
_safe_call(_LIB.LGBM_BoosterGetEval(
self.handle,
ctypes.c_int(data_idx),
ctypes.byref(tmp_out_len),
result.ctypes.data_as(ctypes.POINTER(ctypes.c_double))))
if tmp_out_len.value != self.__num_inner_eval:
raise ValueError("Wrong length of eval results")
for i in range_(self.__num_inner_eval):
ret.append((data_name, self.__name_inner_eval[i],
result[i], self.__higher_better_inner_eval[i]))
if feval is not None:
if data_idx == 0:
cur_data = self.train_set
else:
cur_data = self.valid_sets[data_idx - 1]
feval_ret = feval(self.__inner_predict(data_idx), cur_data)
if isinstance(feval_ret, list):
for eval_name, val, is_higher_better in feval_ret:
ret.append((data_name, eval_name, val, is_higher_better))
else:
eval_name, val, is_higher_better = feval_ret
ret.append((data_name, eval_name, val, is_higher_better))
return ret | [
"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:
n_preds = self.train_set.num_data() * self.__num_class
else:
n_preds = self.valid_sets[data_idx - 1].num_data() * self.__num_class
self.__inner_predict_buffer[data_idx] = np.zeros(n_preds, dtype=np.float64)
# avoid to predict many time in one iteration
if not self.__is_predicted_cur_iter[data_idx]:
tmp_out_len = ctypes.c_int64(0)
data_ptr = self.__inner_predict_buffer[data_idx].ctypes.data_as(ctypes.POINTER(ctypes.c_double))
_safe_call(_LIB.LGBM_BoosterGetPredict(
self.handle,
ctypes.c_int(data_idx),
ctypes.byref(tmp_out_len),
data_ptr))
if tmp_out_len.value != len(self.__inner_predict_buffer[data_idx]):
raise ValueError("Wrong length of predict results for data %d" % (data_idx))
self.__is_predicted_cur_iter[data_idx] = True
return self.__inner_predict_buffer[data_idx] | [
"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(
self.handle,
ctypes.byref(out_num_eval)))
self.__num_inner_eval = out_num_eval.value
if self.__num_inner_eval > 0:
# Get name of evals
tmp_out_len = ctypes.c_int(0)
string_buffers = [ctypes.create_string_buffer(255) for i in range_(self.__num_inner_eval)]
ptr_string_buffers = (ctypes.c_char_p * self.__num_inner_eval)(*map(ctypes.addressof, string_buffers))
_safe_call(_LIB.LGBM_BoosterGetEvalNames(
self.handle,
ctypes.byref(tmp_out_len),
ptr_string_buffers))
if self.__num_inner_eval != tmp_out_len.value:
raise ValueError("Length of eval names doesn't equal with num_evals")
self.__name_inner_eval = \
[string_buffers[i].value.decode() for i in range_(self.__num_inner_eval)]
self.__higher_better_inner_eval = \
[name.startswith(('auc', 'ndcg@', 'map@')) for name in self.__name_inner_eval] | [
"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] = value
else:
self.__attr.pop(key, None)
return self | [
"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,
os.path.join(curr_path, '../../'),
os.path.join(curr_path, 'compile'),
os.path.join(curr_path, '../compile'),
os.path.join(curr_path, '../../lib/')]
if system() in ('Windows', 'Microsoft'):
dll_path.append(os.path.join(curr_path, '../compile/Release/'))
dll_path.append(os.path.join(curr_path, '../compile/windows/x64/DLL/'))
dll_path.append(os.path.join(curr_path, '../../Release/'))
dll_path.append(os.path.join(curr_path, '../../windows/x64/DLL/'))
dll_path = [os.path.join(p, 'lib_lightgbm.dll') for p in dll_path]
else:
dll_path = [os.path.join(p, 'lib_lightgbm.so') for p in dll_path]
lib_path = [p for p in dll_path if os.path.exists(p) and os.path.isfile(p)]
if not lib_path:
dll_path = [os.path.realpath(p) for p in dll_path]
raise Exception('Cannot find lightgbm library file in following paths:\n' + '\n'.join(dll_path))
return lib_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])
else:
return '%s\'s %s: %g' % (value[0], value[1], value[2])
else:
raise ValueError("Wrong metric value") | [
"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])
print('[%d]\t%s' % (env.iteration + 1, result))
_callback.order = 10
return _callback | [
"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 : function\n The callback that prints the evaluation results every ``period`` iteration(s).\n "
] |
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.setdefault(data_name, collections.defaultdict(list))
def _callback(env):
if not eval_result:
_init(env)
for data_name, eval_name, result, _ in env.evaluation_result_list:
eval_result[data_name][eval_name].append(result)
_callback.order = 20
return _callback | [
"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 dictionary.\n "
] |
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', 'metrics', 'metric_types']:
raise RuntimeError("cannot reset {} during training".format(repr(key)))
if isinstance(value, list):
if len(value) != env.end_iteration - env.begin_iteration:
raise ValueError("Length of list {} has to equal to 'num_boost_round'."
.format(repr(key)))
new_param = value[env.iteration - env.begin_iteration]
else:
new_param = value(env.iteration - env.begin_iteration)
if new_param != env.params.get(key, None):
new_parameters[key] = new_param
if new_parameters:
env.model.reset_parameter(new_parameters)
env.params.update(new_parameters)
_callback.before_iteration = True
_callback.order = 10
return _callback | [
"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 customized function that calculates the parameter in terms of\n current number of round (e.g. yields learning rate decay).\n If list lst, parameter = lst[current_round].\n If function func, parameter = func(current_round).\n\n Returns\n -------\n callback : function\n The callback that resets the parameter after the first iteration.\n "
] |
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
and env.params[boost_alias] == 'dart') for boost_alias in ('boosting',
'boosting_type',
'boost'))
if not enabled[0]:
warnings.warn('Early stopping is not available in dart mode')
return
if not env.evaluation_result_list:
raise ValueError('For early stopping, '
'at least one dataset and eval metric is required for evaluation')
if verbose:
msg = "Training until validation scores don't improve for {} rounds."
print(msg.format(stopping_rounds))
for eval_ret in env.evaluation_result_list:
best_iter.append(0)
best_score_list.append(None)
if eval_ret[3]:
best_score.append(float('-inf'))
cmp_op.append(gt)
else:
best_score.append(float('inf'))
cmp_op.append(lt)
def _callback(env):
if not cmp_op:
_init(env)
if not enabled[0]:
return
for i in range_(len(env.evaluation_result_list)):
score = env.evaluation_result_list[i][2]
if best_score_list[i] is None or cmp_op[i](score, best_score[i]):
best_score[i] = score
best_iter[i] = env.iteration
best_score_list[i] = env.evaluation_result_list
elif env.iteration - best_iter[i] >= stopping_rounds:
if verbose:
print('Early stopping, best iteration is:\n[%d]\t%s' % (
best_iter[i] + 1, '\t'.join([_format_eval_result(x) for x in best_score_list[i]])))
raise EarlyStopException(best_iter[i], best_score_list[i])
if env.iteration == env.end_iteration - 1:
if verbose:
print('Did not meet early stopping. Best iteration is:\n[%d]\t%s' % (
best_iter[i] + 1, '\t'.join([_format_eval_result(x) for x in best_score_list[i]])))
raise EarlyStopException(best_iter[i], best_score_list[i])
if first_metric_only: # the only first metric is used for early stopping
break
_callback.order = 30
return _callback | [
"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 validation data and one metric.\n If there's more than one, will check all of them. But the training data is ignored anyway.\n To check only the first metric set ``first_metric_only`` to True.\n\n Parameters\n ----------\n stopping_rounds : int\n The possible number of rounds without the trend occurrence.\n first_metric_only : bool, optional (default=False)\n Whether to use only the first metric for early stopping.\n verbose : bool, optional (default=True)\n Whether to print message with early stopping information.\n\n Returns\n -------\n callback : function\n The callback that activates early stopping.\n "
] |
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,
verbose_eval=True, learning_rates=None,
keep_training_booster=False, callbacks=None):
# create predictor first
params = copy.deepcopy(params)
if fobj is not None:
params['objective'] = 'none'
for alias in ["num_iterations", "num_iteration", "n_iter", "num_tree", "num_trees",
"num_round", "num_rounds", "num_boost_round", "n_estimators"]:
if alias in params:
num_boost_round = int(params.pop(alias))
warnings.warn("Found `{}` in params. Will use it instead of argument".format(alias))
break
for alias in ["early_stopping_round", "early_stopping_rounds", "early_stopping"]:
if alias in params and params[alias] is not None:
early_stopping_rounds = int(params.pop(alias))
warnings.warn("Found `{}` in params. Will use it instead of argument".format(alias))
break
if num_boost_round <= 0:
raise ValueError("num_boost_round should be greater than zero.")
if isinstance(init_model, string_type):
predictor = _InnerPredictor(model_file=init_model, pred_parameter=params)
elif isinstance(init_model, Booster):
predictor = init_model._to_predictor(dict(init_model.params, **params))
else:
predictor = None
init_iteration = predictor.num_total_iteration if predictor is not None else 0
# check dataset
if not isinstance(train_set, Dataset):
raise TypeError("Training only accepts Dataset object")
train_set._update_params(params) \
._set_predictor(predictor) \
.set_feature_name(feature_name) \
.set_categorical_feature(categorical_feature)
is_valid_contain_train = False
train_data_name = "training"
reduced_valid_sets = []
name_valid_sets = []
if valid_sets is not None:
if isinstance(valid_sets, Dataset):
valid_sets = [valid_sets]
if isinstance(valid_names, string_type):
valid_names = [valid_names]
for i, valid_data in enumerate(valid_sets):
# reduce cost for prediction training data
if valid_data is train_set:
is_valid_contain_train = True
if valid_names is not None:
train_data_name = valid_names[i]
continue
if not isinstance(valid_data, Dataset):
raise TypeError("Traninig only accepts Dataset object")
reduced_valid_sets.append(valid_data._update_params(params).set_reference(train_set))
if valid_names is not None and len(valid_names) > i:
name_valid_sets.append(valid_names[i])
else:
name_valid_sets.append('valid_' + str(i))
# process callbacks
if callbacks is None:
callbacks = set()
else:
for i, cb in enumerate(callbacks):
cb.__dict__.setdefault('order', i - len(callbacks))
callbacks = set(callbacks)
# Most of legacy advanced options becomes callbacks
if verbose_eval is True:
callbacks.add(callback.print_evaluation())
elif isinstance(verbose_eval, integer_types):
callbacks.add(callback.print_evaluation(verbose_eval))
if early_stopping_rounds is not None:
callbacks.add(callback.early_stopping(early_stopping_rounds, verbose=bool(verbose_eval)))
if learning_rates is not None:
callbacks.add(callback.reset_parameter(learning_rate=learning_rates))
if evals_result is not None:
callbacks.add(callback.record_evaluation(evals_result))
callbacks_before_iter = {cb for cb in callbacks if getattr(cb, 'before_iteration', False)}
callbacks_after_iter = callbacks - callbacks_before_iter
callbacks_before_iter = sorted(callbacks_before_iter, key=attrgetter('order'))
callbacks_after_iter = sorted(callbacks_after_iter, key=attrgetter('order'))
# construct booster
try:
booster = Booster(params=params, train_set=train_set)
if is_valid_contain_train:
booster.set_train_data_name(train_data_name)
for valid_set, name_valid_set in zip_(reduced_valid_sets, name_valid_sets):
booster.add_valid(valid_set, name_valid_set)
finally:
train_set._reverse_update_params()
for valid_set in reduced_valid_sets:
valid_set._reverse_update_params()
booster.best_iteration = 0
# start training
for i in range_(init_iteration, init_iteration + num_boost_round):
for cb in callbacks_before_iter:
cb(callback.CallbackEnv(model=booster,
params=params,
iteration=i,
begin_iteration=init_iteration,
end_iteration=init_iteration + num_boost_round,
evaluation_result_list=None))
booster.update(fobj=fobj)
evaluation_result_list = []
# check evaluation result.
if valid_sets is not None:
if is_valid_contain_train:
evaluation_result_list.extend(booster.eval_train(feval))
evaluation_result_list.extend(booster.eval_valid(feval))
try:
for cb in callbacks_after_iter:
cb(callback.CallbackEnv(model=booster,
params=params,
iteration=i,
begin_iteration=init_iteration,
end_iteration=init_iteration + num_boost_round,
evaluation_result_list=evaluation_result_list))
except callback.EarlyStopException as earlyStopException:
booster.best_iteration = earlyStopException.best_iteration + 1
evaluation_result_list = earlyStopException.best_score
break
booster.best_score = collections.defaultdict(dict)
for dataset_name, eval_name, score, _ in evaluation_result_list:
booster.best_score[dataset_name][eval_name] = score
if not keep_training_booster:
booster.model_from_string(booster.model_to_string(), False).free_dataset()
return booster | [
"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 or None, optional (default=None)\n List of data to be evaluated on during training.\n valid_names : list of strings or None, optional (default=None)\n Names of ``valid_sets``.\n fobj : callable or None, optional (default=None)\n Customized objective function.\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 such tuples.\n For multi-class task, the preds is group by class_id first, then group by row_id.\n If you want to get i-th row preds in j-th class, the access way is preds[j * num_data + i].\n To ignore the default metric corresponding to the used objective,\n set the ``metric`` parameter to the string ``\"None\"`` in ``params``.\n init_model : string, Booster or None, optional (default=None)\n Filename of LightGBM model or Booster instance used for continue training.\n feature_name : list of strings or 'auto', optional (default=\"auto\")\n Feature names.\n If 'auto' and data is pandas DataFrame, data columns names are used.\n categorical_feature : list of strings or int, or 'auto', optional (default=\"auto\")\n Categorical features.\n If list of int, interpreted as indices.\n If list of strings, interpreted as feature names (need to specify ``feature_name`` as well).\n If 'auto' and data is pandas DataFrame, pandas unordered categorical columns are used.\n All values in categorical features should be less than int32 max value (2147483647).\n Large values could be memory consuming. Consider using consecutive integers starting from zero.\n All negative values in categorical features will be treated as missing values.\n early_stopping_rounds : int or None, optional (default=None)\n Activates early stopping. 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 validation data and one metric.\n If there's more than one, will check all of them. But the training data is ignored anyway.\n To check only the first metric you can pass in ``callbacks``\n ``early_stopping`` callback with ``first_metric_only=True``.\n The index of iteration that has the best performance will be saved in the ``best_iteration`` field\n if early stopping logic is enabled by setting ``early_stopping_rounds``.\n evals_result: dict or None, optional (default=None)\n This dictionary used to store all evaluation results of all the items in ``valid_sets``.\n\n Example\n -------\n With a ``valid_sets`` = [valid_set, train_set],\n ``valid_names`` = ['eval', 'train']\n and a ``params`` = {'metric': 'logloss'}\n returns {'train': {'logloss': ['0.48253', '0.35953', ...]},\n 'eval': {'logloss': ['0.480385', '0.357756', ...]}}.\n\n verbose_eval : bool or int, optional (default=True)\n Requires at least one validation data.\n If True, the eval metric on the valid set is printed at each boosting stage.\n If int, the eval metric on the valid set is printed at every ``verbose_eval`` boosting stage.\n The last boosting stage or the boosting stage found by using ``early_stopping_rounds`` is also printed.\n\n Example\n -------\n With ``verbose_eval`` = 4 and at least one item in ``valid_sets``,\n an evaluation metric is printed every 4 (instead of 1) boosting stages.\n\n learning_rates : list, callable or None, optional (default=None)\n List of learning rates for each boosting round\n or a customized function that calculates ``learning_rate``\n in terms of current number of round (e.g. yields learning rate decay).\n keep_training_booster : bool, optional (default=False)\n Whether the returned Booster will be used to keep training.\n If False, the returned value will be converted into _InnerPredictor before returning.\n You can still use _InnerPredictor as ``init_model`` for future continue training.\n callbacks : list of callables or None, optional (default=None)\n List of callback functions that are applied at each iteration.\n See Callbacks in Python API for more information.\n\n Returns\n -------\n booster : Booster\n The trained Booster model.\n "
] |
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(folds, '__iter__') and not hasattr(folds, 'split'):
raise AttributeError("folds should be a generator or iterator of (train_idx, test_idx) tuples "
"or scikit-learn splitter object with split method")
if hasattr(folds, 'split'):
group_info = full_data.get_group()
if group_info is not None:
group_info = group_info.astype(int)
flatted_group = np.repeat(range_(len(group_info)), repeats=group_info)
else:
flatted_group = np.zeros(num_data, dtype=int)
folds = folds.split(X=np.zeros(num_data), y=full_data.get_label(), groups=flatted_group)
else:
if 'objective' in params and params['objective'] == 'lambdarank':
if not SKLEARN_INSTALLED:
raise LightGBMError('Scikit-learn is required for lambdarank cv.')
# lambdarank task, split according to groups
group_info = full_data.get_group().astype(int)
flatted_group = np.repeat(range_(len(group_info)), repeats=group_info)
group_kfold = _LGBMGroupKFold(n_splits=nfold)
folds = group_kfold.split(X=np.zeros(num_data), groups=flatted_group)
elif stratified:
if not SKLEARN_INSTALLED:
raise LightGBMError('Scikit-learn is required for stratified cv.')
skf = _LGBMStratifiedKFold(n_splits=nfold, shuffle=shuffle, random_state=seed)
folds = skf.split(X=np.zeros(num_data), y=full_data.get_label())
else:
if shuffle:
randidx = np.random.RandomState(seed).permutation(num_data)
else:
randidx = np.arange(num_data)
kstep = int(num_data / nfold)
test_id = [randidx[i: i + kstep] for i in range_(0, num_data, kstep)]
train_id = [np.concatenate([test_id[i] for i in range_(nfold) if k != i]) for k in range_(nfold)]
folds = zip_(train_id, test_id)
ret = _CVBooster()
for train_idx, test_idx in folds:
train_set = full_data.subset(train_idx)
valid_set = full_data.subset(test_idx)
# run preprocessing on the data set if needed
if fpreproc is not None:
train_set, valid_set, tparam = fpreproc(train_set, valid_set, params.copy())
else:
tparam = params
cvbooster = Booster(tparam, train_set)
if eval_train_metric:
cvbooster.add_valid(train_set, 'train')
cvbooster.add_valid(valid_set, 'valid')
ret.append(cvbooster)
return ret | [
"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_line[0], one_line[1])
else:
key = one_line[1]
metric_type[key] = one_line[3]
cvmap[key].append(one_line[2])
return [('cv_agg', k, np.mean(v), metric_type[k], np.std(v)) for k, v in cvmap.items()] | [
"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,
verbose_eval=None, show_stdv=True, seed=0,
callbacks=None, eval_train_metric=False):
if not isinstance(train_set, Dataset):
raise TypeError("Traninig only accepts Dataset object")
params = copy.deepcopy(params)
if fobj is not None:
params['objective'] = 'none'
for alias in ["num_iterations", "num_iteration", "n_iter", "num_tree", "num_trees",
"num_round", "num_rounds", "num_boost_round", "n_estimators"]:
if alias in params:
warnings.warn("Found `{}` in params. Will use it instead of argument".format(alias))
num_boost_round = params.pop(alias)
break
for alias in ["early_stopping_round", "early_stopping_rounds", "early_stopping"]:
if alias in params:
warnings.warn("Found `{}` in params. Will use it instead of argument".format(alias))
early_stopping_rounds = params.pop(alias)
break
if num_boost_round <= 0:
raise ValueError("num_boost_round should be greater than zero.")
if isinstance(init_model, string_type):
predictor = _InnerPredictor(model_file=init_model, pred_parameter=params)
elif isinstance(init_model, Booster):
predictor = init_model._to_predictor(dict(init_model.params, **params))
else:
predictor = None
train_set._update_params(params) \
._set_predictor(predictor) \
.set_feature_name(feature_name) \
.set_categorical_feature(categorical_feature)
if metrics is not None:
params['metric'] = metrics
results = collections.defaultdict(list)
cvfolds = _make_n_folds(train_set, folds=folds, nfold=nfold,
params=params, seed=seed, fpreproc=fpreproc,
stratified=stratified, shuffle=shuffle,
eval_train_metric=eval_train_metric)
# setup callbacks
if callbacks is None:
callbacks = set()
else:
for i, cb in enumerate(callbacks):
cb.__dict__.setdefault('order', i - len(callbacks))
callbacks = set(callbacks)
if early_stopping_rounds is not None:
callbacks.add(callback.early_stopping(early_stopping_rounds, verbose=False))
if verbose_eval is True:
callbacks.add(callback.print_evaluation(show_stdv=show_stdv))
elif isinstance(verbose_eval, integer_types):
callbacks.add(callback.print_evaluation(verbose_eval, show_stdv=show_stdv))
callbacks_before_iter = {cb for cb in callbacks if getattr(cb, 'before_iteration', False)}
callbacks_after_iter = callbacks - callbacks_before_iter
callbacks_before_iter = sorted(callbacks_before_iter, key=attrgetter('order'))
callbacks_after_iter = sorted(callbacks_after_iter, key=attrgetter('order'))
for i in range_(num_boost_round):
for cb in callbacks_before_iter:
cb(callback.CallbackEnv(model=cvfolds,
params=params,
iteration=i,
begin_iteration=0,
end_iteration=num_boost_round,
evaluation_result_list=None))
cvfolds.update(fobj=fobj)
res = _agg_cv_result(cvfolds.eval_valid(feval), eval_train_metric)
for _, key, mean, _, std in res:
results[key + '-mean'].append(mean)
results[key + '-stdv'].append(std)
try:
for cb in callbacks_after_iter:
cb(callback.CallbackEnv(model=cvfolds,
params=params,
iteration=i,
begin_iteration=0,
end_iteration=num_boost_round,
evaluation_result_list=res))
except callback.EarlyStopException as earlyStopException:
cvfolds.best_iteration = earlyStopException.best_iteration + 1
for k in results:
results[k] = results[k][:cvfolds.best_iteration]
break
return dict(results) | [
"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 iterator of (train_idx, test_idx) tuples, scikit-learn splitter object or None, optional (default=None)\n If generator or iterator, it should yield the train and test indices for each fold.\n If object, it should be one of the scikit-learn splitter classes\n (https://scikit-learn.org/stable/modules/classes.html#splitter-classes)\n and have ``split`` method.\n This argument has highest priority over other data split arguments.\n nfold : int, optional (default=5)\n Number of folds in CV.\n stratified : bool, optional (default=True)\n Whether to perform stratified sampling.\n shuffle : bool, optional (default=True)\n Whether to shuffle before splitting data.\n metrics : string, list of strings or None, optional (default=None)\n Evaluation metrics to be monitored while CV.\n If not None, the metric in ``params`` will be overridden.\n fobj : callable or None, optional (default=None)\n Custom objective function.\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 such tuples.\n For multi-class task, the preds is group by class_id first, then group by row_id.\n If you want to get i-th row preds in j-th class, the access way is preds[j * num_data + i].\n To ignore the default metric corresponding to the used objective,\n set ``metrics`` to the string ``\"None\"``.\n init_model : string, Booster or None, optional (default=None)\n Filename of LightGBM model or Booster instance used for continue training.\n feature_name : list of strings or 'auto', optional (default=\"auto\")\n Feature names.\n If 'auto' and data is pandas DataFrame, data columns names are used.\n categorical_feature : list of strings or int, or 'auto', optional (default=\"auto\")\n Categorical features.\n If list of int, interpreted as indices.\n If list of strings, interpreted as feature names (need to specify ``feature_name`` as well).\n If 'auto' and data is pandas DataFrame, pandas unordered categorical columns are used.\n All values in categorical features should be less than int32 max value (2147483647).\n Large values could be memory consuming. Consider using consecutive integers starting from zero.\n All negative values in categorical features will be treated as missing values.\n early_stopping_rounds : int or None, optional (default=None)\n Activates early stopping.\n CV score needs to improve at least every ``early_stopping_rounds`` round(s)\n to continue.\n Requires at least one metric. If there's more than one, will check all of them.\n To check only the first metric you can pass in ``callbacks``\n ``early_stopping`` callback with ``first_metric_only=True``.\n Last entry in evaluation history is the one from the best iteration.\n fpreproc : callable or None, optional (default=None)\n Preprocessing function that takes (dtrain, dtest, params)\n and returns transformed versions of those.\n verbose_eval : bool, int, or None, optional (default=None)\n Whether to display the progress.\n If None, progress will be displayed when np.ndarray is returned.\n If True, progress will be displayed at every boosting stage.\n If int, progress will be displayed at every given ``verbose_eval`` boosting stage.\n show_stdv : bool, optional (default=True)\n Whether to display the standard deviation in progress.\n Results are not affected by this parameter, and always contain std.\n seed : int, optional (default=0)\n Seed used to generate the folds (passed to numpy.random.seed).\n callbacks : list of callables or None, optional (default=None)\n List of callback functions that are applied at each iteration.\n See Callbacks in Python API for more information.\n eval_train_metric : bool, optional (default=False)\n Whether to display the train metric in progress.\n The score of the metric is calculated again after each training step, so there is some impact on performance.\n\n Returns\n -------\n eval_hist : dict\n Evaluation history.\n The dictionary has the following format:\n {'metric1-mean': [values], 'metric1-stdv': [values],\n 'metric2-mean': [values], 'metric2-stdv': [values],\n ...}.\n "
] |
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': -1
}
time_zero = time.time()
gbm = lgb.train(params, lgb_data, num_boost_round=nrounds)
y_fitted = gbm.predict(data['X'])
y_true = data[label_type + '_labels']
duration = time.time() - time_zero
return {
'time': duration,
'correlation': np.corrcoef(y_fitted, y_true)[0, 1],
'logloss': log_loss(y_fitted, y_true)
} | [
"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 : dict\n Experiment summary stats.\n "
] |
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,
ignore_zero=True, figsize=None, grid=True,
precision=None, **kwargs):
if MATPLOTLIB_INSTALLED:
import matplotlib.pyplot as plt
else:
raise ImportError('You must install matplotlib to plot importance.')
if isinstance(booster, LGBMModel):
booster = booster.booster_
elif not isinstance(booster, Booster):
raise TypeError('booster must be Booster or LGBMModel.')
importance = booster.feature_importance(importance_type=importance_type)
feature_name = booster.feature_name()
if not len(importance):
raise ValueError("Booster's feature_importance is empty.")
tuples = sorted(zip_(feature_name, importance), key=lambda x: x[1])
if ignore_zero:
tuples = [x for x in tuples if x[1] > 0]
if max_num_features is not None and max_num_features > 0:
tuples = tuples[-max_num_features:]
labels, values = zip_(*tuples)
if ax is None:
if figsize is not None:
_check_not_tuple_of_2_elements(figsize, 'figsize')
_, ax = plt.subplots(1, 1, figsize=figsize)
ylocs = np.arange(len(values))
ax.barh(ylocs, values, align='center', height=height, **kwargs)
for x, y in zip_(values, ylocs):
ax.text(x + 1, y,
_float2str(x, precision) if importance_type == 'gain' else x,
va='center')
ax.set_yticks(ylocs)
ax.set_yticklabels(labels)
if xlim is not None:
_check_not_tuple_of_2_elements(xlim, 'xlim')
else:
xlim = (0, max(values) * 1.1)
ax.set_xlim(xlim)
if ylim is not None:
_check_not_tuple_of_2_elements(ylim, 'ylim')
else:
ylim = (-1, len(values))
ax.set_ylim(ylim)
if title is not None:
ax.set_title(title)
if xlabel is not None:
ax.set_xlabel(xlabel)
if ylabel is not None:
ax.set_ylabel(ylabel)
ax.grid(grid)
return ax | [
"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 axes will be created.\n height : float, optional (default=0.2)\n Bar height, passed to ``ax.barh()``.\n xlim : tuple of 2 elements or None, optional (default=None)\n Tuple passed to ``ax.xlim()``.\n ylim : tuple of 2 elements or None, optional (default=None)\n Tuple passed to ``ax.ylim()``.\n title : string or None, optional (default=\"Feature importance\")\n Axes title.\n If None, title is disabled.\n xlabel : string or None, optional (default=\"Feature importance\")\n X-axis title label.\n If None, title is disabled.\n ylabel : string or None, optional (default=\"Features\")\n Y-axis title label.\n If None, title is disabled.\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 total gains of splits which use the feature.\n max_num_features : int or None, optional (default=None)\n Max number of top features displayed on plot.\n If None or <1, all features will be displayed.\n ignore_zero : bool, optional (default=True)\n Whether to ignore features with zero importance.\n figsize : tuple of 2 elements or None, optional (default=None)\n Figure size.\n grid : bool, optional (default=True)\n Whether to add a grid for axes.\n precision : int or None, optional (default=None)\n Used to restrict the display of floating point values to a certain precision.\n **kwargs\n Other parameters passed to ``ax.barh()``.\n\n Returns\n -------\n ax : matplotlib.axes.Axes\n The plot with model's feature importances.\n "
] |
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_INSTALLED:
import matplotlib.pyplot as plt
else:
raise ImportError('You must install matplotlib to plot metric.')
if isinstance(booster, LGBMModel):
eval_results = deepcopy(booster.evals_result_)
elif isinstance(booster, dict):
eval_results = deepcopy(booster)
else:
raise TypeError('booster must be dict or LGBMModel.')
num_data = len(eval_results)
if not num_data:
raise ValueError('eval results cannot be empty.')
if ax is None:
if figsize is not None:
_check_not_tuple_of_2_elements(figsize, 'figsize')
_, ax = plt.subplots(1, 1, figsize=figsize)
if dataset_names is None:
dataset_names = iter(eval_results.keys())
elif not isinstance(dataset_names, (list, tuple, set)) or not dataset_names:
raise ValueError('dataset_names should be iterable and cannot be empty')
else:
dataset_names = iter(dataset_names)
name = next(dataset_names) # take one as sample
metrics_for_one = eval_results[name]
num_metric = len(metrics_for_one)
if metric is None:
if num_metric > 1:
msg =
warnings.warn(msg, stacklevel=2)
metric, results = metrics_for_one.popitem()
else:
if metric not in metrics_for_one:
raise KeyError('No given metric in eval results.')
results = metrics_for_one[metric]
num_iteration, max_result, min_result = len(results), max(results), min(results)
x_ = range_(num_iteration)
ax.plot(x_, results, label=name)
for name in dataset_names:
metrics_for_one = eval_results[name]
results = metrics_for_one[metric]
max_result, min_result = max(max(results), max_result), min(min(results), min_result)
ax.plot(x_, results, label=name)
ax.legend(loc='best')
if xlim is not None:
_check_not_tuple_of_2_elements(xlim, 'xlim')
else:
xlim = (0, num_iteration)
ax.set_xlim(xlim)
if ylim is not None:
_check_not_tuple_of_2_elements(ylim, 'ylim')
else:
range_result = max_result - min_result
ylim = (min_result - range_result * 0.2, max_result + range_result * 0.2)
ax.set_ylim(ylim)
if ylabel == 'auto':
ylabel = metric
if title is not None:
ax.set_title(title)
if xlabel is not None:
ax.set_xlabel(xlabel)
if ylabel is not None:
ax.set_ylabel(ylabel)
ax.grid(grid)
return ax | [
"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 different metrics have various scales.\n If None, first metric picked from dictionary (according to hashcode).\n dataset_names : list of strings or None, optional (default=None)\n List of the dataset names which are used to calculate metric to plot.\n If None, all datasets are used.\n ax : matplotlib.axes.Axes or None, optional (default=None)\n Target axes instance.\n If None, new figure and axes will be created.\n xlim : tuple of 2 elements or None, optional (default=None)\n Tuple passed to ``ax.xlim()``.\n ylim : tuple of 2 elements or None, optional (default=None)\n Tuple passed to ``ax.ylim()``.\n title : string or None, optional (default=\"Metric during training\")\n Axes title.\n If None, title is disabled.\n xlabel : string or None, optional (default=\"Iterations\")\n X-axis title label.\n If None, title is disabled.\n ylabel : string or None, optional (default=\"auto\")\n Y-axis title label.\n If 'auto', metric name is used.\n If None, title is disabled.\n figsize : tuple of 2 elements or None, optional (default=None)\n Figure size.\n grid : bool, optional (default=True)\n Whether to add a grid for axes.\n\n Returns\n -------\n ax : matplotlib.axes.Axes\n The plot with metric's history over the training.\n ",
"more than one metric available, picking one to plot."
] |
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):
if 'split_index' in root: # non-leaf
name = 'split{0}'.format(root['split_index'])
if feature_names is not None:
label = 'split_feature_name: {0}'.format(feature_names[root['split_feature']])
else:
label = 'split_feature_index: {0}'.format(root['split_feature'])
label += r'\nthreshold: {0}'.format(_float2str(root['threshold'], precision))
for info in show_info:
if info in {'split_gain', 'internal_value'}:
label += r'\n{0}: {1}'.format(info, _float2str(root[info], precision))
elif info == 'internal_count':
label += r'\n{0}: {1}'.format(info, root[info])
graph.node(name, label=label)
if root['decision_type'] == '<=':
l_dec, r_dec = '<=', '>'
elif root['decision_type'] == '==':
l_dec, r_dec = 'is', "isn't"
else:
raise ValueError('Invalid decision type in tree model.')
add(root['left_child'], name, l_dec)
add(root['right_child'], name, r_dec)
else: # leaf
name = 'leaf{0}'.format(root['leaf_index'])
label = 'leaf_index: {0}'.format(root['leaf_index'])
label += r'\nleaf_value: {0}'.format(_float2str(root['leaf_value'], precision))
if 'leaf_count' in show_info:
label += r'\nleaf_count: {0}'.format(root['leaf_count'])
graph.node(name, label=label)
if parent is not None:
graph.edge(parent, name, decision)
graph = Digraph(**kwargs)
add(tree_info['tree_structure'])
return graph | [
"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,
old_node_attr=None, old_edge_attr=None, old_body=None, old_strict=False, **kwargs):
if isinstance(booster, LGBMModel):
booster = booster.booster_
elif not isinstance(booster, Booster):
raise TypeError('booster must be Booster or LGBMModel.')
for param_name in ['old_name', 'old_comment', 'old_filename', 'old_directory',
'old_format', 'old_engine', 'old_encoding', 'old_graph_attr',
'old_node_attr', 'old_edge_attr', 'old_body']:
param = locals().get(param_name)
if param is not None:
warnings.warn('{0} parameter is deprecated and will be removed in 2.4 version.\n'
'Please use **kwargs to pass {1} parameter.'.format(param_name, param_name[4:]),
LGBMDeprecationWarning)
if param_name[4:] not in kwargs:
kwargs[param_name[4:]] = param
if locals().get('strict'):
warnings.warn('old_strict parameter is deprecated and will be removed in 2.4 version.\n'
'Please use **kwargs to pass strict parameter.',
LGBMDeprecationWarning)
if 'strict' not in kwargs:
kwargs['strict'] = True
model = booster.dump_model()
tree_infos = model['tree_info']
if 'feature_names' in model:
feature_names = model['feature_names']
else:
feature_names = None
if tree_index < len(tree_infos):
tree_info = tree_infos[tree_index]
else:
raise IndexError('tree_index is out of range.')
if show_info is None:
show_info = []
graph = _to_graphviz(tree_info, show_info, feature_names, precision, **kwargs)
return graph | [
"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_index : int, optional (default=0)\n The index of a target tree to convert.\n show_info : list of strings or None, optional (default=None)\n What information should be shown in nodes.\n Possible values of list items: 'split_gain', 'internal_value', 'internal_count', 'leaf_count'.\n precision : int or None, optional (default=None)\n Used to restrict the display of floating point values to a certain precision.\n **kwargs\n Other parameters passed to ``Digraph`` constructor.\n Check https://graphviz.readthedocs.io/en/stable/api.html#digraph for the full list of supported parameters.\n\n Returns\n -------\n graph : graphviz.Digraph\n The digraph representation of specified tree.\n "
] |
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
import matplotlib.image as image
else:
raise ImportError('You must install matplotlib to plot tree.')
for param_name in ['old_graph_attr', 'old_node_attr', 'old_edge_attr']:
param = locals().get(param_name)
if param is not None:
warnings.warn('{0} parameter is deprecated and will be removed in 2.4 version.\n'
'Please use **kwargs to pass {1} parameter.'.format(param_name, param_name[4:]),
LGBMDeprecationWarning)
if param_name[4:] not in kwargs:
kwargs[param_name[4:]] = param
if ax is None:
if figsize is not None:
_check_not_tuple_of_2_elements(figsize, 'figsize')
_, ax = plt.subplots(1, 1, figsize=figsize)
graph = create_tree_digraph(booster=booster, tree_index=tree_index,
show_info=show_info, precision=precision, **kwargs)
s = BytesIO()
s.write(graph.pipe(format='png'))
s.seek(0)
img = image.imread(s)
ax.imshow(img)
ax.axis('off')
return ax | [
"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 or LGBMModel instance to be plotted.\n ax : matplotlib.axes.Axes or None, optional (default=None)\n Target axes instance.\n If None, new figure and axes will be created.\n tree_index : int, optional (default=0)\n The index of a target tree to plot.\n figsize : tuple of 2 elements or None, optional (default=None)\n Figure size.\n show_info : list of strings or None, optional (default=None)\n What information should be shown in nodes.\n Possible values of list items: 'split_gain', 'internal_value', 'internal_count', 'leaf_count'.\n precision : int or None, optional (default=None)\n Used to restrict the display of floating point values to a certain precision.\n **kwargs\n Other parameters passed to ``Digraph`` constructor.\n Check https://graphviz.readthedocs.io/en/stable/api.html#digraph for the full list of supported parameters.\n\n Returns\n -------\n ax : matplotlib.axes.Axes\n The plot with single tree.\n "
] |
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 '
'is needed!'
) | [
"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, rank)[rank]
while result_i in ban_set:
rank -= 1
result_i = np.argpartition(cossims, rank)[rank]
return result_i | [
"\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 size len(vectors), which can be passed for efficiency\n\n returns the index of the closest match to query within vectors\n\n "
] |
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,
t=1e-4,
label="__label__",
verbose=2,
pretrainedVectors="",
):
model = "supervised"
a = _build_args(locals())
ft = _FastText()
fasttext.train(ft.f, a)
return ft | [
"\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 mentioned here: http://www.statmt.org/wmt07/baseline.html\n\n The input file must must contain at least one label per line. For an\n example consult the example datasets which are part of the fastText\n repository such as the dataset pulled by classification-example.sh.\n "
] |
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.Vector(dim)
self.f.getSentenceVector(b, text)
return np.array(b) | [
"\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\')"
)
entry += "\n"
return entry
if type(text) == list:
text = [check(entry) for entry in text]
predictions = self.f.multilinePredict(text, k, threshold, on_unicode_error)
dt = np.dtype([('probability', 'float64'), ('label', 'object')])
result_as_pair = np.array(predictions, dtype=dt)
return result_as_pair['label'].tolist(), result_as_pair['probability']
else:
text = check(text)
predictions = self.f.predict(text, k, threshold, on_unicode_error)
probs, labels = zip(*predictions)
return labels, np.array(probs, copy=False) | [
"\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 the returned labels by a threshold on probability. A\n choice of 0.5 will return labels with at least 0.5\n probability. k and threshold will be applied together to\n determine the returned labels.\n\n This function assumes to be given\n a single line of text. We split words on whitespace (space,\n newline, tab, vertical tab) and the control characters carriage\n return, formfeed and the null character.\n\n If the model is not supervised, this function will throw a ValueError.\n\n If given a list of strings, it will return a list of results as usually\n received for a single line of text.\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.array(pair[1]))
else:
return pair[0]
else:
return self.get_words(include_freq) | [
"\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"
return entry
if type(text) == list:
text = [check(entry) for entry in text]
return self.f.multilineGetLine(text, on_unicode_error)
else:
text = check(text)
return self.f.getLine(text, on_unicode_error) | [
"\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()
if not epoch:
epoch = a.epoch
if not lr:
lr = a.lr
if not thread:
thread = a.thread
if not verbose:
verbose = a.verbose
if retrain and not input:
raise ValueError("Need input file path if retraining")
if input is None:
input = ""
self.f.quantize(
input, qout, cutoff, retrain, epoch, lr, thread, verbose, dsub,
qnorm
) | [
"\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 not initial_state:
hidden_states = [None] * len(self.lstm_layers)
elif initial_state[0].size()[0] != len(self.lstm_layers):
raise ConfigurationError("Initial states were passed to forward() but the number of "
"initial states does not match the number of layers.")
else:
hidden_states = list(zip(initial_state[0].split(1, 0),
initial_state[1].split(1, 0)))
output_sequence = inputs
final_h = []
final_c = []
for i, state in enumerate(hidden_states):
forward_layer = getattr(self, 'forward_layer_{}'.format(i))
backward_layer = getattr(self, 'backward_layer_{}'.format(i))
# The state is duplicated to mirror the Pytorch API for LSTMs.
forward_output, final_forward_state = forward_layer(output_sequence, state)
backward_output, final_backward_state = backward_layer(output_sequence, state)
forward_output, lengths = pad_packed_sequence(forward_output, batch_first=True)
backward_output, _ = pad_packed_sequence(backward_output, batch_first=True)
output_sequence = torch.cat([forward_output, backward_output], -1)
# Apply layer wise dropout on each output sequence apart from the
# first (input) and last
if i < (self.num_layers - 1):
output_sequence = self.layer_dropout(output_sequence)
output_sequence = pack_padded_sequence(output_sequence, lengths, batch_first=True)
final_h.extend([final_forward_state[0], final_backward_state[0]])
final_c.extend([final_forward_state[1], final_backward_state[1]])
final_h = torch.cat(final_h, dim=0)
final_c = torch.cat(final_c, dim=0)
final_state_tuple = (final_h, final_c)
return output_sequence, final_state_tuple | [
"\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 hidden state and memory\n of the LSTM. Each tensor has shape (num_layers, batch_size, output_dimension * 2).\n\n Returns\n -------\n output_sequence : PackedSequence\n The encoded sequence of shape (batch_size, sequence_length, hidden_size * 2)\n final_states: torch.Tensor\n The per-layer final (state, memory) states of the LSTM, each with shape\n (num_layers * 2, batch_size, hidden_size * 2).\n "
] |
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 isinstance(regularizer_params, str):
regularizer = Regularizer.by_name(regularizer_params)()
else:
regularizer_type = Regularizer.by_name(regularizer_params.pop("type"))
regularizer = regularizer_type(**regularizer_params) # type: ignore
instantiated_regularizers.append((parameter_regex, regularizer))
return RegularizerApplicator(instantiated_regularizers) | [
"\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 name (which may be no regex and hence no penalty).\n The values can either be strings, in which case they correspond to the names\n of regularizers, or dictionaries, in which case they must contain the \"type\"\n key, corresponding to the name of a regularizer. In addition, they may contain\n auxiliary named parameters which will be fed to the regularizer itself.\n To determine valid auxiliary parameters, please refer to the torch.nn.init documentation.\n\n Parameters\n ----------\n params : ``Params``, required.\n A Params object containing a \"regularizers\" key.\n\n Returns\n -------\n A RegularizerApplicator containing the specified Regularizers,\n or ``None`` if no Regularizers are specified.\n "
] |
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 implementation %s is not registered" % default
raise ConfigurationError(message)
else:
return [default] + [k for k in keys if k != default] | [
"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 list (and moved to cpu if necessary)
return x.cpu().tolist()
elif isinstance(x, numpy.ndarray):
# array needs to be converted to a list
return x.tolist()
elif isinstance(x, numpy.number): # pylint: disable=no-member
# NumPy numbers need to be converted to Python numbers
return x.item()
elif isinstance(x, dict):
# Dicts need their values sanitized
return {key: sanitize(value) for key, value in x.items()}
elif isinstance(x, (spacy.tokens.Token, allennlp.data.Token)):
# Tokens get sanitized to just their text.
return x.text
elif isinstance(x, (list, tuple)):
# Lists and Tuples need their values sanitized
return [sanitize(x_i) for x_i in x]
elif x is None:
return "None"
elif hasattr(x, 'to_json'):
return x.to_json()
else:
raise ValueError(f"Cannot sanitize {x} of type {type(x)}. "
"If this is your own custom class, add a `to_json(self)` method "
"that returns a JSON-like object.") | [
"\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's complicated and hard to remember as a one-liner, so we just\n make a function out of it.\n "
] |
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 desired length.
if padding_on_right:
padded_sequence = sequence[:desired_length]
else:
padded_sequence = sequence[-desired_length:]
# Continues to pad with default_value() until we reach the desired length.
for _ in range(desired_length - len(padded_sequence)):
if padding_on_right:
padded_sequence.append(default_value())
else:
padded_sequence.insert(0, default_value())
return padded_sequence | [
"\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 are truncated to this length, and\n shorter ones are padded to it.\n\n default_value: Callable, default=lambda: 0\n Callable that outputs a default value (of any type) to use as padding values. This is\n a lambda to avoid using the same object when the default value is more complex, like a\n list.\n\n padding_on_right : bool, default=True\n When we add padding tokens (or truncate the sequence), should we do it on the right or\n the left?\n\n Returns\n -------\n padded_sequence : List\n "
] |
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_dict[key] = value + noise
return new_dict | [
"\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 None:
numpy.random.seed(numpy_seed)
if torch_seed is not None:
torch.manual_seed(torch_seed)
# Seed all GPUs with the same seed if available.
if torch.cuda.is_available():
torch.cuda.manual_seed_all(torch_seed)
log_pytorch_version_info() | [
"\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 reproducible. If you are using this from your own\n project, you will want to call this function before importing Pytorch. Complete determinism\n is very difficult to achieve with libraries doing optimized linear algebra due to massively\n parallel execution, which is exacerbated by using GPUs.\n\n Parameters\n ----------\n params: Params object or dict, required.\n A ``Params`` object or dict holding the json parameters.\n "
] |
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_interval(file_friendly_logging)
std_out_file = os.path.join(serialization_dir, "stdout.log")
sys.stdout = TeeLogger(std_out_file, # type: ignore
sys.stdout,
file_friendly_logging)
sys.stderr = TeeLogger(os.path.join(serialization_dir, "stderr.log"), # type: ignore
sys.stderr,
file_friendly_logging)
stdout_handler = logging.FileHandler(std_out_file)
stdout_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s'))
logging.getLogger().addHandler(stdout_handler)
return stdout_handler | [
"\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, which is set in ``allennlp/run.py``.\n\n Parameters\n ----------\n serialization_dir : ``str``, required.\n The directory to stream logs to.\n file_friendly_logging : ``bool``, required.\n Whether logs should clean the output to prevent carriage returns\n (used to update progress bars on a single terminal line). This\n option is typically only used if you are running in an environment\n without a terminal.\n\n Returns\n -------\n ``logging.FileHandler``\n A logging file handler that can later be closed and removed from the global logger.\n "
] |
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, TeeLogger):
sys.stderr = sys.stderr.cleanup() | [
"\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:
disable.append('tagger')
if not parse:
disable.append('parser')
if not ner:
disable.append('ner')
try:
spacy_model = spacy.load(spacy_model_name, disable=disable)
except OSError:
logger.warning(f"Spacy models '{spacy_model_name}' not found. Downloading and installing.")
spacy_download(spacy_model_name)
# NOTE(mattg): The following four lines are a workaround suggested by Ines for spacy
# 2.1.0, which removed the linking that was done in spacy 2.0. importlib doesn't find
# packages that were installed in the same python session, so the way `spacy_download`
# works in 2.1.0 is broken for this use case. These four lines can probably be removed
# at some point in the future, once spacy has figured out a better way to handle this.
# See https://github.com/explosion/spaCy/issues/3435.
from spacy.cli import link
from spacy.util import get_package_path
package_path = get_package_path(spacy_model_name)
link(spacy_model_name, spacy_model_name, model_path=package_path)
spacy_model = spacy.load(spacy_model_name, disable=disable)
LOADED_SPACY_MODELS[options] = spacy_model
return LOADED_SPACY_MODELS[options] | [
"\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, adding it again at
# the end won't hurt anything.
sys.path.append('.')
# Import at top level
module = importlib.import_module(package_name)
path = getattr(module, '__path__', [])
path_string = '' if not path else path[0]
# walk_packages only finds immediate children, so need to recurse.
for module_finder, name, _ in pkgutil.walk_packages(path):
# Sometimes when you import third-party libraries that are on your path,
# `pkgutil.walk_packages` returns those too, so we need to skip them.
if path_string and module_finder.path != path_string:
continue
subpackage = f"{package_name}.{name}"
import_submodules(subpackage) | [
"\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 "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.