INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Pure transformer-style multi-headed attention. Args: x: inputs ((q, k, v), mask) params: parameters (none) num_heads: int: number of attention heads dropout: float: dropout rate mode: str: 'train' or 'eval' **kwargs: other arguments including the rng Returns: Pure Multi-headed attentio...
def PureMultiHeadedAttention(x, params, num_heads=8, dropout=0.0, mode='train', **kwargs): """Pure transformer-style multi-headed attention. Args: x: inputs ((q, k, v), mask) params: parameters (none) num_heads: int: number of attention heads dropout: float: dropout rat...
Transformer-style multi-headed attention. Accepts inputs of the form (q, k, v), mask. Args: feature_depth: int: depth of embedding num_heads: int: number of attention heads dropout: float: dropout rate mode: str: 'train' or 'eval' Returns: Multi-headed self-attention layer.
def MultiHeadedAttentionQKV( feature_depth, num_heads=8, dropout=0.0, mode='train'): """Transformer-style multi-headed attention. Accepts inputs of the form (q, k, v), mask. Args: feature_depth: int: depth of embedding num_heads: int: number of attention heads dropout: float: dropout rate m...
Transformer-style multi-headed attention. Accepts inputs of the form (x, mask) and constructs (q, k, v) from x. Args: feature_depth: int: depth of embedding num_heads: int: number of attention heads dropout: float: dropout rate mode: str: 'train' or 'eval' Returns: Multi-headed self-attent...
def MultiHeadedAttention( feature_depth, num_heads=8, dropout=0.0, mode='train'): """Transformer-style multi-headed attention. Accepts inputs of the form (x, mask) and constructs (q, k, v) from x. Args: feature_depth: int: depth of embedding num_heads: int: number of attention heads dropout: fl...
Helper: calculate output shape for chunked key selector (see below).
def _chunked_selector_output_shape( # pylint: disable=invalid-name input_shapes, selector=None, **unused_kwargs): """Helper: calculate output shape for chunked key selector (see below).""" # Read the main function below first, the shape logic just follows the ops. selector = selector or (lambda x: [] if x < ...
Select which chunks to attend to in chunked attention. Args: x: inputs, a list of elements of the form (q, k, v), mask for each chunk. params: parameters (unused). selector: a function from chunk_number -> list of chunk numbers that says which other chunks should be appended to the given one (previ...
def ChunkedAttentionSelector(x, params, selector=None, **kwargs): """Select which chunks to attend to in chunked attention. Args: x: inputs, a list of elements of the form (q, k, v), mask for each chunk. params: parameters (unused). selector: a function from chunk_number -> list of chunk numbers that s...
Transformer-style causal multi-headed attention operating on chunks. Accepts inputs that are a list of chunks and applies causal attention. Args: feature_depth: int: depth of embedding num_heads: int: number of attention heads dropout: float: dropout rate chunk_selector: a function from chunk num...
def ChunkedCausalMultiHeadedAttention( feature_depth, num_heads=8, dropout=0.0, chunk_selector=None, mode='train'): """Transformer-style causal multi-headed attention operating on chunks. Accepts inputs that are a list of chunks and applies causal attention. Args: feature_depth: int: depth of embedding...
Layer to shift the tensor to the right by padding on axis 1.
def ShiftRight(x, **unused_kwargs): """Layer to shift the tensor to the right by padding on axis 1.""" if not isinstance(x, (list, tuple)): # non-chunked inputs pad_widths = [(0, 0), (1, 0)] padded = np.pad(x, pad_widths, mode='constant') return padded[:, :-1] # Handling chunked inputs. Recall that t...
Helper function: Create a Zipf distribution. Args: nbr_symbols: number of symbols to use in the distribution. alpha: float, Zipf's Law Distribution parameter. Default = 1.5. Usually for modelling natural text distribution is in the range [1.1-1.6]. Returns: distr_map: list of float, Zipf's...
def zipf_distribution(nbr_symbols, alpha): """Helper function: Create a Zipf distribution. Args: nbr_symbols: number of symbols to use in the distribution. alpha: float, Zipf's Law Distribution parameter. Default = 1.5. Usually for modelling natural text distribution is in the range [1.1-1.6]. ...
Helper function: Generate a random Zipf sample of given length. Args: distr_map: list of float, Zipf's distribution over nbr_symbols. sample_len: integer, length of sequence to generate. Returns: sample: list of integer, Zipf's random sample over nbr_symbols.
def zipf_random_sample(distr_map, sample_len): """Helper function: Generate a random Zipf sample of given length. Args: distr_map: list of float, Zipf's distribution over nbr_symbols. sample_len: integer, length of sequence to generate. Returns: sample: list of integer, Zipf's random sample over nbr...
Generator for the reversing nlp-like task on sequences of symbols. The length of the sequence is drawn from a Gaussian(Normal) distribution at random from [1, max_length] and with std deviation of 1%, then symbols are drawn from Zipf's law at random from [0, nbr_symbols) until nbr_cases sequences have been pro...
def reverse_generator_nlplike(nbr_symbols, max_length, nbr_cases, scale_std_dev=100, alpha=1.5): """Generator for the reversing nlp-like task on sequences of symbols. The length of the sequence i...
Helper function: convert a list of digits in the given base to a number.
def lower_endian_to_number(l, base): """Helper function: convert a list of digits in the given base to a number.""" return sum([d * (base**i) for i, d in enumerate(l)])
Helper function: convert a number to a list of digits in the given base.
def number_to_lower_endian(n, base): """Helper function: convert a number to a list of digits in the given base.""" if n < base: return [n] return [n % base] + number_to_lower_endian(n // base, base)
Helper function: generate a random number as a lower-endian digits list.
def random_number_lower_endian(length, base): """Helper function: generate a random number as a lower-endian digits list.""" if length == 1: # Last digit can be 0 only if length is 1. return [np.random.randint(base)] prefix = [np.random.randint(base) for _ in range(length - 1)] return prefix + [np.random.r...
Run command on GCS instance, optionally detached.
def remote_run(cmd, instance_name, detach=False, retries=1): """Run command on GCS instance, optionally detached.""" if detach: cmd = SCREEN.format(command=cmd) args = SSH.format(instance_name=instance_name).split() args.append(cmd) for i in range(retries + 1): try: if i > 0: tf.logging....
Wait for SSH to be available at given IP address.
def wait_for_ssh(ip): """Wait for SSH to be available at given IP address.""" for _ in range(12): with safe_socket() as s: try: s.connect((ip, 22)) return True except socket.timeout: pass time.sleep(10) return False
Launch a GCE instance.
def launch_instance(instance_name, command, existing_ip=None, cpu=1, mem=4, code_dir=None, setup_command=None): """Launch a GCE instance.""" # Create instance ip = existing_ip or create_instance...
Evolved Transformer encoder. See arxiv.org/abs/1901.11117 for more details. Note: Pad remover is not supported. Args: encoder_input: a Tensor. encoder_self_attention_bias: bias Tensor for self-attention (see common_attention.attention_bias()). hparams: hyperparameters for model. name: a stri...
def evolved_transformer_encoder(encoder_input, encoder_self_attention_bias, hparams, name="encoder", nonpadding=None, save_weights_to=None, ...
Evolved Transformer decoder. See arxiv.org/abs/1901.11117 for more details. Args: decoder_input: a Tensor. encoder_output: a Tensor. decoder_self_attention_bias: bias Tensor for self-attention (see common_attention.attention_bias()). encoder_decoder_attention_bias: bias Tensor for encoder-decod...
def evolved_transformer_decoder(decoder_input, encoder_output, decoder_self_attention_bias, encoder_decoder_attention_bias, hparams, cache=None, ...
Add attend-to-encoder layers to cache.
def _add_attend_to_encoder_cache(cache, attention_name, hparams, num_layers, key_channels, value_channels, vars_3d_num_heads, scope_prefix, encoder_output): """Add attend-to-encoder layers to cache.""" for layer in ra...
Create the initial cache for Evolved Transformer fast decoding.
def _init_evolved_transformer_cache(cache, hparams, batch_size, attention_init_length, encoder_output, encoder_decoder_attention_bias, scope_prefix): """Create the initial cache for Evolved Transformer fast dec...
Add Evolved Transformer hparams. Note: These are for the Adam optimizer, not the Adafactor optimizer used in the paper. Args: hparams: Current hparams. Returns: hparams updated with Evolved Transformer values.
def add_evolved_transformer_hparams(hparams): """Add Evolved Transformer hparams. Note: These are for the Adam optimizer, not the Adafactor optimizer used in the paper. Args: hparams: Current hparams. Returns: hparams updated with Evolved Transformer values. """ # Evolved Transformer "layers" a...
Base parameters for Evolved Transformer model on TPU.
def evolved_transformer_base_tpu(): """Base parameters for Evolved Transformer model on TPU.""" hparams = add_evolved_transformer_hparams(transformer.transformer_tpu()) hparams.learning_rate_constant = 1 / hparams.learning_rate_warmup_steps ** 0.5 hparams.learning_rate_schedule = ( "constant*single_cycle_...
Big parameters for Evolved Transformer model on TPU.
def evolved_transformer_big_tpu(): """Big parameters for Evolved Transformer model on TPU.""" hparams = add_evolved_transformer_hparams(transformer.transformer_big_tpu()) hparams.learning_rate_constant = 1 / hparams.learning_rate_warmup_steps ** 0.5 hparams.learning_rate_schedule = ( "constant*single_cycl...
Local mixture of experts that works well on TPU. Adapted from the paper https://arxiv.org/abs/1701.06538 Note: until the algorithm and inferface solidify, we pass in a hyperparameters dictionary in order not to complicate the interface in mtf_transformer.py . Once this code moves out of "research", we should ...
def transformer_moe_layer_v1(inputs, output_dim, hparams, train, master_dtype=tf.bfloat16, slice_dtype=tf.float32): """Local mixture of experts that works well on TPU. Adapted from the paper https://arxiv.org/abs/1701.06538 Note: until the algorithm and ...
2-level mixture of experts. Adapted from the paper https://arxiv.org/abs/1701.06538 Note: until the algorithm and inferface solidify, we pass in a hyperparameters dictionary in order not to complicate the interface in mtf_transformer.py . Once this code moves out of "research", we should pass the hyperparamet...
def transformer_moe_layer_v2(inputs, output_dim, hparams, train, master_dtype=tf.bfloat16, slice_dtype=tf.float32): """2-level mixture of experts. Adapted from the paper https://arxiv.org/abs/1701.06538 Note: until the algorithm and inferface solidify, we pass in a hyperparameters ...
Compute gating for mixture-of-experts in TensorFlow. Note: until the algorithm and inferface solidify, we pass in a hyperparameters dictionary in order not to complicate the interface in mtf_transformer.py . Once this code moves out of "research", we should pass the hyperparameters separately. Hyperparamete...
def _top_2_gating( inputs, outer_expert_dims, experts_dim, expert_capacity_dim, hparams, train, importance=None): """Compute gating for mixture-of-experts in TensorFlow. Note: until the algorithm and inferface solidify, we pass in a hyperparameters dictionary in order not to complicate the interface in m...
Add necessary hyperparameters for mixture-of-experts.
def set_default_moe_hparams(hparams): """Add necessary hyperparameters for mixture-of-experts.""" hparams.moe_num_experts = 16 hparams.moe_loss_coef = 1e-2 hparams.add_hparam("moe_gating", "top_2") # Experts have fixed capacity per batch. We need some extra capacity # in case gating is not perfectly balanc...
Helper function for figuring out how to split a dimensino into groups. We have a dimension with size n and we want to split it into two dimensions: n = num_groups * group_size group_size should be the largest possible value meeting the constraints: group_size <= max_group_size (num_groups = n/group_size...
def _split_into_groups(n, max_group_size, mesh_dim_size): """Helper function for figuring out how to split a dimensino into groups. We have a dimension with size n and we want to split it into two dimensions: n = num_groups * group_size group_size should be the largest possible value meeting the constraints: ...
Reset the batch of environments. Args: indices: The batch indices of the environments to reset. Returns: Batch tensor of the new observations.
def reset(self, indices=None): """Reset the batch of environments. Args: indices: The batch indices of the environments to reset. Returns: Batch tensor of the new observations. """ return tf.cond( tf.cast(tf.reduce_sum(indices + 1), tf.bool), lambda: self._reset_non_emp...
Second-moment decay rate like Adam, subsuming the correction factor. Args: beta2: a float between 0 and 1 Returns: a scalar
def adafactor_decay_rate_adam(beta2): """Second-moment decay rate like Adam, subsuming the correction factor. Args: beta2: a float between 0 and 1 Returns: a scalar """ t = tf.to_float(tf.train.get_or_create_global_step()) + 1.0 decay = beta2 * (1.0 - tf.pow(beta2, t - 1.0)) / (1.0 - tf.pow(beta2, ...
Create an Adafactor optimizer based on model hparams. Args: hparams: model hyperparameters lr: learning rate scalar. Returns: an AdafactorOptimizer Raises: ValueError: on illegal values
def adafactor_optimizer_from_hparams(hparams, lr): """Create an Adafactor optimizer based on model hparams. Args: hparams: model hyperparameters lr: learning rate scalar. Returns: an AdafactorOptimizer Raises: ValueError: on illegal values """ if hparams.optimizer_adafactor_decay_type == "a...
Makes validator for function to ensure it takes nargs args.
def _nargs_validator(nargs, message): """Makes validator for function to ensure it takes nargs args.""" if message is None: message = "Registered function must take exactly %d arguments" % nargs def f(key, value): del key spec = inspect.getfullargspec(value) if (len(spec.args) != nargs or spec.va...
Determines if problem_name specifies a copy and/or reversal. Args: name: str, problem name, possibly with suffixes. Returns: ProblemSpec: namedtuple with ["base_name", "was_reversed", "was_copy"] Raises: ValueError if name contains multiple suffixes of the same type ('_rev' or '_copy'). One o...
def parse_problem_name(name): """Determines if problem_name specifies a copy and/or reversal. Args: name: str, problem name, possibly with suffixes. Returns: ProblemSpec: namedtuple with ["base_name", "was_reversed", "was_copy"] Raises: ValueError if name contains multiple suffixes of the same ty...
Construct a problem name from base and reversed/copy options. Inverse of `parse_problem_name`. Args: base_name: base problem name. Should not end in "_rev" or "_copy" was_reversed: if the problem is to be reversed was_copy: if the problem is to be copied Returns: string name consistent with use...
def get_problem_name(base_name, was_reversed=False, was_copy=False): """Construct a problem name from base and reversed/copy options. Inverse of `parse_problem_name`. Args: base_name: base problem name. Should not end in "_rev" or "_copy" was_reversed: if the problem is to be reversed was_copy: if t...
Get pre-registered optimizer keyed by name. `name` should be snake case, though SGD -> sgd, RMSProp -> rms_prop and UpperCamelCase -> snake_case conversions included for legacy support. Args: name: name of optimizer used in registration. This should be a snake case identifier, though others supported ...
def optimizer(name): """Get pre-registered optimizer keyed by name. `name` should be snake case, though SGD -> sgd, RMSProp -> rms_prop and UpperCamelCase -> snake_case conversions included for legacy support. Args: name: name of optimizer used in registration. This should be a snake case identifier...
Get possibly copied/reversed problem in `base_registry` or `env_registry`. Args: problem_name: string problem name. See `parse_problem_name`. **kwargs: forwarded to env problem's initialize method. Returns: possibly reversed/copied version of base problem registered in the given registry.
def problem(problem_name, **kwargs): """Get possibly copied/reversed problem in `base_registry` or `env_registry`. Args: problem_name: string problem name. See `parse_problem_name`. **kwargs: forwarded to env problem's initialize method. Returns: possibly reversed/copied version of base problem regi...
Get and initialize the `EnvProblem` with the given name and batch size. Args: env_problem_name: string name of the registered env problem. **kwargs: forwarded to env problem's initialize method. Returns: an initialized EnvProblem with the given batch size.
def env_problem(env_problem_name, **kwargs): """Get and initialize the `EnvProblem` with the given name and batch size. Args: env_problem_name: string name of the registered env problem. **kwargs: forwarded to env problem's initialize method. Returns: an initialized EnvProblem with the given batch s...
Creates a help string for names_list grouped by prefix.
def display_list_by_prefix(names_list, starting_spaces=0): """Creates a help string for names_list grouped by prefix.""" cur_prefix, result_lines = None, [] space = " " * starting_spaces for name in sorted(names_list): split = name.split("_", 1) prefix = split[0] if cur_prefix != prefix: resul...
Generate help string with contents of registry.
def help_string(): """Generate help string with contents of registry.""" help_str = """ Registry contents: ------------------ Models: %s HParams: %s RangedHParams: %s Problems: %s Optimizers: %s Attacks: %s Attack HParams: %s Pruning HParams: %s Pruning Strategies: %s Env Problems: %s ...
Validation function run before setting. Uses function from __init__.
def validate(self, key, value): """Validation function run before setting. Uses function from __init__.""" if self._validator is not None: self._validator(key, value)
Callback called on successful set. Uses function from __init__.
def on_set(self, key, value): """Callback called on successful set. Uses function from __init__.""" if self._on_set is not None: self._on_set(key, value)
Decorator to register a function, or registration itself. This is primarily intended for use as a decorator, either with or without a key/parentheses. ```python @my_registry.register('key1') def value_fn(x, y, z): pass @my_registry.register() def another_fn(x, y): pass @my...
def register(self, key_or_value=None): """Decorator to register a function, or registration itself. This is primarily intended for use as a decorator, either with or without a key/parentheses. ```python @my_registry.register('key1') def value_fn(x, y, z): pass @my_registry.register()...
Check the dynamic symbol versions. Parameters ---------- objdump_string : string The dynamic symbol table entries of the file (result of `objdump -T` command).
def check_dependicies(objdump_string): """Check the dynamic symbol versions. Parameters ---------- objdump_string : string The dynamic symbol table entries of the file (result of `objdump -T` command). """ GLIBC_version = re.compile(r'0{16}[ \t]+GLIBC_(\d{1,2})[.](\d{1,3})[.]?\d{,3}[ \t...
Decorate an objective function. Note ---- For multi-class task, the y_pred is group by class_id first, then group by row_id. If you want to get i-th row y_pred in j-th class, the access way is y_pred[j * num_data + i] and you should group grad and hess in this way as well. Parameters -----...
def _objective_function_wrapper(func): """Decorate an objective function. Note ---- For multi-class task, the y_pred is group by class_id first, then group by row_id. If you want to get i-th row y_pred in j-th class, the access way is y_pred[j * num_data + i] and you should group grad and hess ...
Decorate an eval function. Note ---- For multi-class task, the y_pred is group by class_id first, then group by row_id. If you want to get i-th row y_pred in j-th class, the access way is y_pred[j * num_data + i]. Parameters ---------- func : callable Expects a callable with follow...
def _eval_function_wrapper(func): """Decorate an eval function. Note ---- For multi-class task, the y_pred is group by class_id first, then group by row_id. If you want to get i-th row y_pred in j-th class, the access way is y_pred[j * num_data + i]. Parameters ---------- func : callab...
Get parameters for this estimator. Parameters ---------- deep : bool, optional (default=True) If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns ------- params : dict Parameter...
def get_params(self, deep=True): """Get parameters for this estimator. Parameters ---------- deep : bool, optional (default=True) If True, will return the parameters for this estimator and contained subobjects that are estimators. Returns -------...
Build a gradient boosting model from the training set (X, y). Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] Input feature matrix. y : array-like of shape = [n_samples] The target values (class labels in classification, r...
def fit(self, X, y, sample_weight=None, init_score=None, group=None, eval_set=None, eval_names=None, eval_sample_weight=None, eval_class_weight=None, eval_init_score=None, eval_group=None, eval_metric=None, early_stopping_rounds=None, verbose=True, feature_nam...
Return the predicted value for each sample. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] Input features matrix. raw_score : bool, optional (default=False) Whether to predict raw scores. num_iteration : int or No...
def predict(self, X, raw_score=False, num_iteration=None, pred_leaf=False, pred_contrib=False, **kwargs): """Return the predicted value for each sample. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] Input features ma...
Docstring is inherited from the LGBMModel.
def fit(self, X, y, sample_weight=None, init_score=None, eval_set=None, eval_names=None, eval_sample_weight=None, eval_init_score=None, eval_metric=None, early_stopping_rounds=None, verbose=True, feature_name='auto', categorical_feature='auto', callbacks=None): ""...
Get feature importances. Note ---- Feature importance in sklearn interface used to normalize to 1, it's deprecated after 2.0.4 and is the same as Booster.feature_importance() now. ``importance_type`` attribute is passed to the function to configure the type of importance...
def feature_importances_(self): """Get feature importances. Note ---- Feature importance in sklearn interface used to normalize to 1, it's deprecated after 2.0.4 and is the same as Booster.feature_importance() now. ``importance_type`` attribute is passed to the function ...
Docstring is inherited from the LGBMModel.
def fit(self, X, y, sample_weight=None, init_score=None, eval_set=None, eval_names=None, eval_sample_weight=None, eval_class_weight=None, eval_init_score=None, eval_metric=None, early_stopping_rounds=None, verbose=True, feature_name='auto', categorical_feature...
Docstring is inherited from the LGBMModel.
def predict(self, X, raw_score=False, num_iteration=None, pred_leaf=False, pred_contrib=False, **kwargs): """Docstring is inherited from the LGBMModel.""" result = self.predict_proba(X, raw_score, num_iteration, pred_leaf, pred_contrib, **kwargs) ...
Return the predicted probability for each class for each sample. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_features] Input features matrix. raw_score : bool, optional (default=False) Whether to predict raw scores. num_...
def predict_proba(self, X, raw_score=False, num_iteration=None, pred_leaf=False, pred_contrib=False, **kwargs): """Return the predicted probability for each class for each sample. Parameters ---------- X : array-like or sparse matrix of shape = [n_samples, n_featur...
Docstring is inherited from the LGBMModel.
def fit(self, X, y, sample_weight=None, init_score=None, group=None, eval_set=None, eval_names=None, eval_sample_weight=None, eval_init_score=None, eval_group=None, eval_metric=None, eval_at=[1], early_stopping_rounds=None, verbose=True, feature_name='auto', c...
Parse config header file. Parameters ---------- config_hpp : string Path to the config header file. Returns ------- infos : tuple Tuple with names and content of sections.
def get_parameter_infos(config_hpp): """Parse config header file. Parameters ---------- config_hpp : string Path to the config header file. Returns ------- infos : tuple Tuple with names and content of sections. """ is_inparameter = False parameter_group = None ...
Get names of all parameters. Parameters ---------- infos : list Content of the config header file. Returns ------- names : list Names of all parameters.
def get_names(infos): """Get names of all parameters. Parameters ---------- infos : list Content of the config header file. Returns ------- names : list Names of all parameters. """ names = [] for x in infos: for y in x: names.append(y["name"...
Get aliases of all parameters. Parameters ---------- infos : list Content of the config header file. Returns ------- pairs : list List of tuples (param alias, param name).
def get_alias(infos): """Get aliases of all parameters. Parameters ---------- infos : list Content of the config header file. Returns ------- pairs : list List of tuples (param alias, param name). """ pairs = [] for x in infos: for y in x: if...
Construct code for auto config file for one param value. Parameters ---------- name : string Name of the parameter. param_type : string Type of the parameter. checks : list Constraints of the parameter. Returns ------- ret : string Lines of auto config f...
def set_one_var_from_string(name, param_type, checks): """Construct code for auto config file for one param value. Parameters ---------- name : string Name of the parameter. param_type : string Type of the parameter. checks : list Constraints of the parameter. Retur...
Write descriptions of parameters to the documentation file. Parameters ---------- sections : list Names of parameters sections. descriptions : list Structured descriptions of parameters. params_rst : string Path to the file with parameters documentation.
def gen_parameter_description(sections, descriptions, params_rst): """Write descriptions of parameters to the documentation file. Parameters ---------- sections : list Names of parameters sections. descriptions : list Structured descriptions of parameters. params_rst : string ...
Generate auto config file. Parameters ---------- config_hpp : string Path to the config header file. config_out_cpp : string Path to the auto config file. Returns ------- infos : tuple Tuple with names and content of sections.
def gen_parameter_code(config_hpp, config_out_cpp): """Generate auto config file. Parameters ---------- config_hpp : string Path to the config header file. config_out_cpp : string Path to the auto config file. Returns ------- infos : tuple Tuple with names and c...
Load LightGBM library.
def _load_lib(): """Load LightGBM library.""" lib_path = find_lib_path() if len(lib_path) == 0: return None lib = ctypes.cdll.LoadLibrary(lib_path[0]) lib.LGBM_GetLastError.restype = ctypes.c_char_p return lib
Convert data to 1-D numpy array.
def list_to_1d_numpy(data, dtype=np.float32, name='list'): """Convert data to 1-D numpy array.""" if is_numpy_1d_array(data): if data.dtype == dtype: return data else: return data.astype(dtype=dtype, copy=False) elif is_1d_list(data): return np.array(data, dty...
Convert a ctypes float pointer array to a numpy array.
def cfloat32_array_to_numpy(cptr, length): """Convert a ctypes float pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_float)): return np.fromiter(cptr, dtype=np.float32, count=length) else: raise RuntimeError('Expected float pointer')
Convert a ctypes double pointer array to a numpy array.
def cfloat64_array_to_numpy(cptr, length): """Convert a ctypes double pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_double)): return np.fromiter(cptr, dtype=np.float64, count=length) else: raise RuntimeError('Expected double pointer')
Convert a ctypes int pointer array to a numpy array.
def cint32_array_to_numpy(cptr, length): """Convert a ctypes int pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_int32)): return np.fromiter(cptr, dtype=np.int32, count=length) else: raise RuntimeError('Expected int pointer')
Convert a ctypes int pointer array to a numpy array.
def cint8_array_to_numpy(cptr, length): """Convert a ctypes int pointer array to a numpy array.""" if isinstance(cptr, ctypes.POINTER(ctypes.c_int8)): return np.fromiter(cptr, dtype=np.int8, count=length) else: raise RuntimeError('Expected int pointer')
Convert Python dictionary to string, which is passed to C API.
def param_dict_to_str(data): """Convert Python dictionary to string, which is passed to C API.""" if data is None or not data: return "" pairs = [] for key, val in data.items(): if isinstance(val, (list, tuple, set)) or is_numpy_1d_array(val): pairs.append(str(key) + '=' + ',...
Fix the memory of multi-dimensional sliced object.
def convert_from_sliced_object(data): """Fix the memory of multi-dimensional sliced object.""" if data.base is not None and isinstance(data, np.ndarray) and isinstance(data.base, np.ndarray): if not data.flags.c_contiguous: warnings.warn("Usage of np.ndarray subset (sliced data) is not recom...
Get pointer of float numpy array / list.
def c_float_array(data): """Get pointer of float numpy array / list.""" if is_1d_list(data): data = np.array(data, copy=False) if is_numpy_1d_array(data): data = convert_from_sliced_object(data) assert data.flags.c_contiguous if data.dtype == np.float32: ptr_data ...
Get pointer of int numpy array / list.
def c_int_array(data): """Get pointer of int numpy array / list.""" if is_1d_list(data): data = np.array(data, copy=False) if is_numpy_1d_array(data): data = convert_from_sliced_object(data) assert data.flags.c_contiguous if data.dtype == np.int32: ptr_data = data...
Predict logic. Parameters ---------- data : string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.sparse Data source for prediction. When data type is string, it represents the path of txt file. num_iteration : int, optional (default=-1) ...
def predict(self, data, num_iteration=-1, raw_score=False, pred_leaf=False, pred_contrib=False, data_has_header=False, is_reshape=True): """Predict logic. Parameters ---------- data : string, numpy array, pandas DataFrame, H2O DataTable's Frame or scipy.s...
Get size of prediction result.
def __get_num_preds(self, num_iteration, nrow, predict_type): """Get size of prediction result.""" if nrow > MAX_INT32: raise LightGBMError('LightGBM cannot perform prediction for data' 'with number of rows greater than MAX_INT32 (%d).\n' ...
Predict for a 2-D numpy matrix.
def __pred_for_np2d(self, mat, num_iteration, predict_type): """Predict for a 2-D numpy matrix.""" if len(mat.shape) != 2: raise ValueError('Input numpy.ndarray or list must be 2 dimensional') def inner_predict(mat, num_iteration, predict_type, preds=None): if mat.dtype ...
Predict for a CSR data.
def __pred_for_csr(self, csr, num_iteration, predict_type): """Predict for a CSR data.""" def inner_predict(csr, num_iteration, predict_type, preds=None): nrow = len(csr.indptr) - 1 n_preds = self.__get_num_preds(num_iteration, nrow, predict_type) if preds is None: ...
Predict for a CSC data.
def __pred_for_csc(self, csc, num_iteration, predict_type): """Predict for a CSC data.""" nrow = csc.shape[0] if nrow > MAX_INT32: return self.__pred_for_csr(csc.tocsr(), num_iteration, predict_type) n_preds = self.__get_num_preds(num_iteration, nrow, predict_type) pr...
Initialize data from a 2-D numpy matrix.
def __init_from_np2d(self, mat, params_str, ref_dataset): """Initialize data from a 2-D numpy matrix.""" if len(mat.shape) != 2: raise ValueError('Input numpy.ndarray must be 2 dimensional') self.handle = ctypes.c_void_p() if mat.dtype == np.float32 or mat.dtype == np.float6...
Initialize data from a list of 2-D numpy matrices.
def __init_from_list_np2d(self, mats, params_str, ref_dataset): """Initialize data from a list of 2-D numpy matrices.""" ncol = mats[0].shape[1] nrow = np.zeros((len(mats),), np.int32) if mats[0].dtype == np.float64: ptr_data = (ctypes.POINTER(ctypes.c_double) * len(mats))() ...
Initialize data from a CSR matrix.
def __init_from_csr(self, csr, params_str, ref_dataset): """Initialize data from a CSR matrix.""" if len(csr.indices) != len(csr.data): raise ValueError('Length mismatch: {} vs {}'.format(len(csr.indices), len(csr.data))) self.handle = ctypes.c_void_p() ptr_indptr, type_ptr_...
Initialize data from a CSC matrix.
def __init_from_csc(self, csc, params_str, ref_dataset): """Initialize data from a CSC matrix.""" if len(csc.indices) != len(csc.data): raise ValueError('Length mismatch: {} vs {}'.format(len(csc.indices), len(csc.data))) self.handle = ctypes.c_void_p() ptr_indptr, type_ptr_...
Lazy init. Returns ------- self : Dataset Constructed Dataset object.
def construct(self): """Lazy init. Returns ------- self : Dataset Constructed Dataset object. """ if self.handle is None: if self.reference is not None: if self.used_indices is None: # create valid ...
Create validation data align with current Dataset. Parameters ---------- data : string, numpy array, pandas DataFrame, H2O DataTable's Frame, scipy.sparse or list of numpy arrays Data source of Dataset. If string, it represents the path to txt file. label : list,...
def create_valid(self, data, label=None, weight=None, group=None, init_score=None, silent=False, params=None): """Create validation data align with current Dataset. Parameters ---------- data : string, numpy array, pandas DataFrame, H2O DataTable's Frame, scipy.spar...
Get subset of current Dataset. Parameters ---------- used_indices : list of int Indices used to create the subset. params : dict or None, optional (default=None) These parameters will be passed to Dataset constructor. Returns ------- subs...
def subset(self, used_indices, params=None): """Get subset of current Dataset. Parameters ---------- used_indices : list of int Indices used to create the subset. params : dict or None, optional (default=None) These parameters will be passed to Dataset co...
Save Dataset to a binary file. Parameters ---------- filename : string Name of the output file. Returns ------- self : Dataset Returns self.
def save_binary(self, filename): """Save Dataset to a binary file. Parameters ---------- filename : string Name of the output file. Returns ------- self : Dataset Returns self. """ _safe_call(_LIB.LGBM_DatasetSaveBinary( ...
Set property into the Dataset. Parameters ---------- field_name : string The field name of the information. data : list, numpy 1-D array, pandas Series or None The array of data to be set. Returns ------- self : Dataset Datase...
def set_field(self, field_name, data): """Set property into the Dataset. Parameters ---------- field_name : string The field name of the information. data : list, numpy 1-D array, pandas Series or None The array of data to be set. Returns ...
Get property from the Dataset. Parameters ---------- field_name : string The field name of the information. Returns ------- info : numpy array A numpy array with information from the Dataset.
def get_field(self, field_name): """Get property from the Dataset. Parameters ---------- field_name : string The field name of the information. Returns ------- info : numpy array A numpy array with information from the Dataset. ""...
Set categorical features. Parameters ---------- categorical_feature : list of int or strings Names or indices of categorical features. Returns ------- self : Dataset Dataset with set categorical features.
def set_categorical_feature(self, categorical_feature): """Set categorical features. Parameters ---------- categorical_feature : list of int or strings Names or indices of categorical features. Returns ------- self : Dataset Dataset with ...
Set predictor for continued training. It is not recommended for user to call this function. Please use init_model argument in engine.train() or engine.cv() instead.
def _set_predictor(self, predictor): """Set predictor for continued training. It is not recommended for user to call this function. Please use init_model argument in engine.train() or engine.cv() instead. """ if predictor is self._predictor: return self if se...
Set reference Dataset. Parameters ---------- reference : Dataset Reference that is used as a template to construct the current Dataset. Returns ------- self : Dataset Dataset with set reference.
def set_reference(self, reference): """Set reference Dataset. Parameters ---------- reference : Dataset Reference that is used as a template to construct the current Dataset. Returns ------- self : Dataset Dataset with set reference. ...
Set feature name. Parameters ---------- feature_name : list of strings Feature names. Returns ------- self : Dataset Dataset with set feature name.
def set_feature_name(self, feature_name): """Set feature name. Parameters ---------- feature_name : list of strings Feature names. Returns ------- self : Dataset Dataset with set feature name. """ if feature_name != 'auto'...
Set label of Dataset. Parameters ---------- label : list, numpy 1-D array, pandas Series / one-column DataFrame or None The label information to be set into Dataset. Returns ------- self : Dataset Dataset with set label.
def set_label(self, label): """Set label of Dataset. Parameters ---------- label : list, numpy 1-D array, pandas Series / one-column DataFrame or None The label information to be set into Dataset. Returns ------- self : Dataset Dataset wi...
Set weight of each instance. Parameters ---------- weight : list, numpy 1-D array, pandas Series or None Weight to be set for each data point. Returns ------- self : Dataset Dataset with set weight.
def set_weight(self, weight): """Set weight of each instance. Parameters ---------- weight : list, numpy 1-D array, pandas Series or None Weight to be set for each data point. Returns ------- self : Dataset Dataset with set weight. ...
Set init score of Booster to start from. Parameters ---------- init_score : list, numpy 1-D array, pandas Series or None Init score for Booster. Returns ------- self : Dataset Dataset with set init score.
def set_init_score(self, init_score): """Set init score of Booster to start from. Parameters ---------- init_score : list, numpy 1-D array, pandas Series or None Init score for Booster. Returns ------- self : Dataset Dataset with set init...
Set group size of Dataset (used for ranking). Parameters ---------- group : list, numpy 1-D array, pandas Series or None Group size of each group. Returns ------- self : Dataset Dataset with set group.
def set_group(self, group): """Set group size of Dataset (used for ranking). Parameters ---------- group : list, numpy 1-D array, pandas Series or None Group size of each group. Returns ------- self : Dataset Dataset with set group. ...
Get the label of the Dataset. Returns ------- label : numpy array or None The label information from the Dataset.
def get_label(self): """Get the label of the Dataset. Returns ------- label : numpy array or None The label information from the Dataset. """ if self.label is None: self.label = self.get_field('label') return self.label
Get the weight of the Dataset. Returns ------- weight : numpy array or None Weight for each data point from the Dataset.
def get_weight(self): """Get the weight of the Dataset. Returns ------- weight : numpy array or None Weight for each data point from the Dataset. """ if self.weight is None: self.weight = self.get_field('weight') return self.weight
Get the feature penalty of the Dataset. Returns ------- feature_penalty : numpy array or None Feature penalty for each feature in the Dataset.
def get_feature_penalty(self): """Get the feature penalty of the Dataset. Returns ------- feature_penalty : numpy array or None Feature penalty for each feature in the Dataset. """ if self.feature_penalty is None: self.feature_penalty = self.get_f...
Get the monotone constraints of the Dataset. Returns ------- monotone_constraints : numpy array or None Monotone constraints: -1, 0 or 1, for each feature in the Dataset.
def get_monotone_constraints(self): """Get the monotone constraints of the Dataset. Returns ------- monotone_constraints : numpy array or None Monotone constraints: -1, 0 or 1, for each feature in the Dataset. """ if self.monotone_constraints is None: ...
Get the initial score of the Dataset. Returns ------- init_score : numpy array or None Init score of Booster.
def get_init_score(self): """Get the initial score of the Dataset. Returns ------- init_score : numpy array or None Init score of Booster. """ if self.init_score is None: self.init_score = self.get_field('init_score') return self.init_scor...
Get the raw data of the Dataset. Returns ------- data : string, numpy array, pandas DataFrame, H2O DataTable's Frame, scipy.sparse, list of numpy arrays or None Raw data used in the Dataset construction.
def get_data(self): """Get the raw data of the Dataset. Returns ------- data : string, numpy array, pandas DataFrame, H2O DataTable's Frame, scipy.sparse, list of numpy arrays or None Raw data used in the Dataset construction. """ if self.handle is None: ...
Get the group of the Dataset. Returns ------- group : numpy array or None Group size of each group.
def get_group(self): """Get the group of the Dataset. Returns ------- group : numpy array or None Group size of each group. """ if self.group is None: self.group = self.get_field('group') if self.group is not None: # gr...