text stringlengths 81 112k |
|---|
Adafactor with recommended learning rate schedule.
def afx_adafactor():
"""Adafactor with recommended learning rate schedule."""
hparams = afx_adam()
hparams.optimizer = "Adafactor"
hparams.learning_rate_schedule = "rsqrt_decay"
hparams.learning_rate_warmup_steps = 10000
return hparams |
Small transformer model with small batch size for fast step times.
def afx_small():
"""Small transformer model with small batch size for fast step times."""
hparams = transformer.transformer_tpu()
hparams.filter_size = 1024
hparams.num_heads = 4
hparams.num_hidden_layers = 3
hparams.batch_size = 512
retu... |
Emily's model hparams.
def next_frame_emily():
"""Emily's model hparams."""
hparams = sv2p_params.next_frame_sv2p()
hparams.video_num_input_frames = 2
hparams.video_num_target_frames = 10
hparams.learning_rate_constant = 1e-4
seq_length = hparams.video_num_input_frames + hparams.video_num_target_frames
#... |
Convert a file to examples.
def main(_):
"""Convert a file to examples."""
if FLAGS.subword_text_encoder_filename:
encoder = text_encoder.SubwordTextEncoder(
FLAGS.subword_text_encoder_filename)
elif FLAGS.token_text_encoder_filename:
encoder = text_encoder.TokenTextEncoder(FLAGS.token_text_encod... |
Return a mix of env and video data fields and decoders.
def example_reading_spec(self):
"""Return a mix of env and video data fields and decoders."""
video_fields, video_decoders = (
video_utils.VideoProblem.example_reading_spec(self))
env_fields, env_decoders = env_problem.EnvProblem.example_readi... |
Transforms time step observations to frames of a video.
def _generate_time_steps(self, trajectory_list):
"""Transforms time step observations to frames of a video."""
for time_step in env_problem.EnvProblem._generate_time_steps(
self, trajectory_list):
# Convert the rendered observations from num... |
Iterate through lines of file.
def txt_line_iterator(txt_path):
"""Iterate through lines of file."""
with tf.gfile.Open(txt_path) as f:
for line in f:
yield line.strip() |
Yield dicts for Text2TextProblem.generate_samples from lines of files.
def text2text_txt_iterator(source_txt_path, target_txt_path):
"""Yield dicts for Text2TextProblem.generate_samples from lines of files."""
for inputs, targets in zip(
txt_line_iterator(source_txt_path), txt_line_iterator(target_txt_path))... |
Yield dicts for Text2TextProblem.generate_samples from lines of files.
def text2text_distill_iterator(source_txt_path, target_txt_path,
distill_txt_path):
"""Yield dicts for Text2TextProblem.generate_samples from lines of files."""
for inputs, targets, dist_targets in zip(
txt_... |
Yield dicts for Text2ClassProblem.generate_samples from lines of files.
Args:
source_txt_path: txt file with record per line.
label_txt_path: txt file with label per line, either as int or str. If
string, must provide class_strs.
class_strs: list<str> of class label names. Must be in correct order ... |
Yield dicts for Text2TextProblem.generate_samples from lines of txt_path.
Args:
txt_path: path to txt file with a record per line, source and target
are tab-separated.
Yields:
{"inputs": inputs, "targets": targets}
def text2text_txt_tab_iterator(txt_path):
"""Yield dicts for Text2TextProblem.gene... |
Encode Text2Text samples from the generator with the vocab.
def text2text_generate_encoded(sample_generator,
vocab,
targets_vocab=None,
has_inputs=True,
inputs_prefix="",
... |
For packed datasets, returns a function to pack examples.
Returns:
None or a function from list of TFRecords to list of TFRecords
def _pack_fn(self):
"""For packed datasets, returns a function to pack examples.
Returns:
None or a function from list of TFRecords to list of TFRecords
"""
... |
Wraps generator with packer if self.packed_length.
def _maybe_pack_examples(self, generator):
"""Wraps generator with packer if self.packed_length."""
if not self.packed_length:
return generator
return generator_utils.pack_examples(
generator,
self.has_inputs,
self.packed_leng... |
List of input filepaths for a particular training or dev shard.
Args:
tmp_dir: a string
task_id: an integer less than self.num_shards
Returns:
a list of tuples (filepath, start_pos, num_bytes)
def text_filepaths_for_task(self, tmp_dir, task_id):
"""List of input filepaths for a particula... |
Read text out of an input file.
The default just reads the text, converts to unicode and yields one
unicode string.
Subclasses can override this function in order to preprocess, and can
yield any number of strings.
Args:
filepath: a string
Yields:
unicode strings.
def filepath_to... |
Read complete text of input files and yield unicode strings.
By default, one unicode string is produced per file, but this is
not guaranteed, since subclasses can override
filepath_to_unicode_strings().
max_chars_per_file and max_chars_total can also be specified, in which
case some strings may be... |
Generator for examples.
Args:
encoder: a TextEncoder
tmp_dir: a string
task_id: an integer
Yields:
feature dictionaries
def example_generator(self, encoder, tmp_dir, task_id):
"""Generator for examples.
Args:
encoder: a TextEncoder
tmp_dir: a string
task_id: ... |
Make sure that the data is prepared and the vocab is generated.
def prepare_to_generate(self, data_dir, tmp_dir):
"""Make sure that the data is prepared and the vocab is generated."""
self.get_or_create_vocab(data_dir, tmp_dir)
self.train_text_filepaths(tmp_dir)
self.dev_text_filepaths(tmp_dir) |
Generates training/dev data.
Args:
data_dir: a string
tmp_dir: a string
task_id: an optional integer
Returns:
shard or shards for which data was generated.
def generate_data(self, data_dir, tmp_dir, task_id=-1):
"""Generates training/dev data.
Args:
data_dir: a string
... |
ResNet convolutional striding block.
def ConvBlock(kernel_size, filters, strides):
"""ResNet convolutional striding block."""
ks = kernel_size
filters1, filters2, filters3 = filters
main = layers.Serial(
layers.Conv(filters1, (1, 1), strides),
layers.BatchNorm(),
layers.Relu(),
layers.C... |
ResNet identical size block.
def IdentityBlock(kernel_size, filters):
"""ResNet identical size block."""
ks = kernel_size
filters1, filters2, filters3 = filters
main = layers.Serial(
layers.Conv(filters1, (1, 1)),
layers.BatchNorm(),
layers.Relu(),
layers.Conv(filters2, (ks, ks), paddin... |
ResNet.
Args:
hidden_size: the size of the first hidden layer (multiplied later).
num_output_classes: how many classes to distinguish.
mode: whether we are training or evaluating or doing inference.
Returns:
The ResNet model with the given layer and output sizes.
def Resnet50(hidden_size=64, num_... |
WideResnet convolutational block.
def WideResnetBlock(channels, strides=(1, 1), channel_mismatch=False):
"""WideResnet convolutational block."""
main = layers.Serial(layers.BatchNorm(), layers.Relu(),
layers.Conv(channels, (3, 3), strides, padding='SAME'),
layers.Batch... |
WideResnet from https://arxiv.org/pdf/1605.07146.pdf.
Args:
num_blocks: int, number of blocks in a group.
hidden_size: the size of the first hidden layer (multiplied later).
num_output_classes: int, number of classes to distinguish.
mode: is it training or eval.
Returns:
The WideResnet model w... |
Builds a traditional GRU cell with dense internal transformations.
Gated Recurrent Unit paper: https://arxiv.org/abs/1412.3555
Args:
units: Number of hidden units.
Returns:
A Stax model representing a traditional GRU RNN cell.
def GRUCell(units):
"""Builds a traditional GRU cell with dense internal... |
Builds a convolutional GRU.
Paper: https://arxiv.org/abs/1511.06432.
Args:
units: Number of hidden units
kernel_size: Kernel size for convolution
Returns:
A Stax model representing a GRU cell with convolution transforms.
def ConvGRUCell(units, kernel_size=(3, 3)):
"""Builds a convolutional GRU.
... |
r"""Parametrized Gated Recurrent Unit (GRU) cell construction.
GRU update equations:
$$ Update gate: u_t = \sigmoid(U' * s_{t-1} + B') $$
$$ Reset gate: r_t = \sigmoid(U'' * s_{t-1} + B'') $$
$$ Candidate memory: c_t = \tanh(U * (r_t \odot s_{t-1}) + B) $$
$$ New State: s_t = u_t \odot s_{t-1} + (1 - u_t) \o... |
Create an attention mask to hide padding and future words.
def MakeTargetMask(target, pad=0):
"""Create an attention mask to hide padding and future words."""
target_mask = (target != pad)[ :, np.newaxis, :]
target_dtype = target_mask.dtype
causal_mask = onp.tril(onp.ones((1, target.shape[-1], target.shape[-1]... |
Build masks for this batch.
Args:
source: (batch, source_len) array of integer-coded symbols for inputs
target_in: (batch, batch_len) array of integer-coded symbols for targets
pad: int: the padding symbol used to pad the above
Returns:
Prepared batch of tuple of arrays: source, input-target, shif... |
Helper: create layer norm parameters.
def _layer_norm_new_params(input_shape, rng, epsilon=1e-6): # pylint: disable=invalid-name
"""Helper: create layer norm parameters."""
del rng, epsilon
features = input_shape[-1]
scale = np.ones(features)
bias = np.zeros(features)
return (scale, bias) |
Helper: create positional encoding parameters.
def _positional_encoding_new_params(input_shape, rng, max_len=2048): # pylint: disable=invalid-name
"""Helper: create positional encoding parameters."""
del rng
# Check if we are operating on chunked inputs by checking if the first
# shape is a list/tuple of shap... |
Implements bare positional encoding.
def PositionalEncoding(x, params, **unused_kwargs):
"""Implements bare positional encoding."""
if not isinstance(x, (list, tuple)): # non-chunked inputs
symbol_size = np.shape(x)[1]
return x + params[:, :symbol_size, :]
# Chunked case: apply to all chunks selecting a... |
Core dot product self-attention.
Args:
query: array of representations
key: array of representations
value: array of representations
mask: attention-mask, gates attention
dropout: float: dropout rate
mode: 'eval' or 'train': whether to use dropout
rng: JAX PRNGKey: subkey for disposable u... |
Pure single-headed self-attention.
Args:
dropout: float: dropout rate
mode: str: 'train' or 'eval'
Returns:
Pure single-headed attention layer. (No Dense transforms on input.)
def PureDotProductAttention(dropout=0.0, mode='train'):
"""Pure single-headed self-attention.
Args:
dropout: float: ... |
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... |
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 MultiHeade... |
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... |
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 logi... |
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... |
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... |
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')
re... |
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... |
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_... |
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... |
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.rando... |
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... |
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 = existi... |
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... |
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... |
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-encod... |
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... |
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.
Not... |
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.l... |
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.... |
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 ... |
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... |
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... |
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 ex... |
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... |
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.
Retu... |
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
... |
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.
... |
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.get... |
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... |
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... |
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 ... |
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 pro... |
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):... |
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)
p... |
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:
... |
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... |
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 : strin... |
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
-----... |
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... |
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... |
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... |
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... |
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... |
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... |
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,
... |
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,
... |
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_... |
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, verb... |
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
----------
... |
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... |
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 : li... |
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... |
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_d... |
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, con... |
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):... |
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 RuntimeErr... |
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 Runtime... |
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('Expe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.