partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
WideResnet
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...
tensor2tensor/trax/models/resnet.py
def WideResnet(num_blocks=3, hidden_size=64, num_output_classes=10, mode='train'): """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, num...
def WideResnet(num_blocks=3, hidden_size=64, num_output_classes=10, mode='train'): """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, num...
[ "WideResnet", "from", "https", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1605", ".", "07146", ".", "pdf", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/models/resnet.py#L129-L149
[ "def", "WideResnet", "(", "num_blocks", "=", "3", ",", "hidden_size", "=", "64", ",", "num_output_classes", "=", "10", ",", "mode", "=", "'train'", ")", ":", "del", "mode", "return", "layers", ".", "Serial", "(", "layers", ".", "Conv", "(", "hidden_size"...
272500b6efe353aeb638d2745ed56e519462ca31
train
GRUCell
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.
tensor2tensor/trax/layers/rnn.py
def GRUCell(units): """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. """ return GeneralGRUCell( candidate_tra...
def GRUCell(units): """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. """ return GeneralGRUCell( candidate_tra...
[ "Builds", "a", "traditional", "GRU", "cell", "with", "dense", "internal", "transformations", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/rnn.py#L28-L44
[ "def", "GRUCell", "(", "units", ")", ":", "return", "GeneralGRUCell", "(", "candidate_transform", "=", "lambda", ":", "core", ".", "Dense", "(", "units", "=", "units", ")", ",", "memory_transform", "=", "combinators", ".", "Identity", ",", "gate_nonlinearity",...
272500b6efe353aeb638d2745ed56e519462ca31
train
ConvGRUCell
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.
tensor2tensor/trax/layers/rnn.py
def ConvGRUCell(units, kernel_size=(3, 3)): """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 BuildConv(): ...
def ConvGRUCell(units, kernel_size=(3, 3)): """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 BuildConv(): ...
[ "Builds", "a", "convolutional", "GRU", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/rnn.py#L47-L67
[ "def", "ConvGRUCell", "(", "units", ",", "kernel_size", "=", "(", "3", ",", "3", ")", ")", ":", "def", "BuildConv", "(", ")", ":", "return", "core", ".", "Conv", "(", "filters", "=", "units", ",", "kernel_size", "=", "kernel_size", ",", "padding", "=...
272500b6efe353aeb638d2745ed56e519462ca31
train
GeneralGRUCell
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...
tensor2tensor/trax/layers/rnn.py
def GeneralGRUCell(candidate_transform, memory_transform=combinators.Identity, gate_nonlinearity=core.Sigmoid, candidate_nonlinearity=core.Tanh, dropout_rate_c=0.1, sigmoid_bias=0.5): r"""Parametrized Gated Recurrent Unit (...
def GeneralGRUCell(candidate_transform, memory_transform=combinators.Identity, gate_nonlinearity=core.Sigmoid, candidate_nonlinearity=core.Tanh, dropout_rate_c=0.1, sigmoid_bias=0.5): r"""Parametrized Gated Recurrent Unit (...
[ "r", "Parametrized", "Gated", "Recurrent", "Unit", "(", "GRU", ")", "cell", "construction", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/rnn.py#L70-L140
[ "def", "GeneralGRUCell", "(", "candidate_transform", ",", "memory_transform", "=", "combinators", ".", "Identity", ",", "gate_nonlinearity", "=", "core", ".", "Sigmoid", ",", "candidate_nonlinearity", "=", "core", ".", "Tanh", ",", "dropout_rate_c", "=", "0.1", ",...
272500b6efe353aeb638d2745ed56e519462ca31
train
MakeTargetMask
Create an attention mask to hide padding and future words.
tensor2tensor/trax/layers/attention.py
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]), dtype=target_dtype), k=...
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]), dtype=target_dtype), k=...
[ "Create", "an", "attention", "mask", "to", "hide", "padding", "and", "future", "words", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L43-L50
[ "def", "MakeTargetMask", "(", "target", ",", "pad", "=", "0", ")", ":", "target_mask", "=", "(", "target", "!=", "pad", ")", "[", ":", ",", "np", ".", "newaxis", ",", ":", "]", "target_dtype", "=", "target_mask", ".", "dtype", "causal_mask", "=", "on...
272500b6efe353aeb638d2745ed56e519462ca31
train
PreparePairedSequenceBatch
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...
tensor2tensor/trax/layers/attention.py
def PreparePairedSequenceBatch(source, target_in, pad=0): """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: ...
def PreparePairedSequenceBatch(source, target_in, pad=0): """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: ...
[ "Build", "masks", "for", "this", "batch", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L53-L74
[ "def", "PreparePairedSequenceBatch", "(", "source", ",", "target_in", ",", "pad", "=", "0", ")", ":", "target", "=", "target_in", "[", ":", ",", ":", "-", "1", "]", "target_y", "=", "target_in", "[", ":", ",", "1", ":", "]", "source_mask", "=", "np",...
272500b6efe353aeb638d2745ed56e519462ca31
train
_layer_norm_new_params
Helper: create layer norm parameters.
tensor2tensor/trax/layers/attention.py
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)
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", "layer", "norm", "parameters", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L78-L84
[ "def", "_layer_norm_new_params", "(", "input_shape", ",", "rng", ",", "epsilon", "=", "1e-6", ")", ":", "# pylint: disable=invalid-name", "del", "rng", ",", "epsilon", "features", "=", "input_shape", "[", "-", "1", "]", "scale", "=", "np", ".", "ones", "(", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_positional_encoding_new_params
Helper: create positional encoding parameters.
tensor2tensor/trax/layers/attention.py
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 shapes (otherwise it's an int or numpy array). is_...
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 shapes (otherwise it's an int or numpy array). is_...
[ "Helper", ":", "create", "positional", "encoding", "parameters", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L97-L111
[ "def", "_positional_encoding_new_params", "(", "input_shape", ",", "rng", ",", "max_len", "=", "2048", ")", ":", "# pylint: disable=invalid-name", "del", "rng", "# Check if we are operating on chunked inputs by checking if the first", "# shape is a list/tuple of shapes (otherwise it'...
272500b6efe353aeb638d2745ed56e519462ca31
train
PositionalEncoding
Implements bare positional encoding.
tensor2tensor/trax/layers/attention.py
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 as much as needed. offset = 0 resul...
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 as much as needed. offset = 0 resul...
[ "Implements", "bare", "positional", "encoding", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L115-L127
[ "def", "PositionalEncoding", "(", "x", ",", "params", ",", "*", "*", "unused_kwargs", ")", ":", "if", "not", "isinstance", "(", "x", ",", "(", "list", ",", "tuple", ")", ")", ":", "# non-chunked inputs", "symbol_size", "=", "np", ".", "shape", "(", "x"...
272500b6efe353aeb638d2745ed56e519462ca31
train
DotProductAttention
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...
tensor2tensor/trax/layers/attention.py
def DotProductAttention(query, key, value, mask, dropout, mode, rng): """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 't...
def DotProductAttention(query, key, value, mask, dropout, mode, rng): """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 't...
[ "Core", "dot", "product", "self", "-", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L130-L157
[ "def", "DotProductAttention", "(", "query", ",", "key", ",", "value", ",", "mask", ",", "dropout", ",", "mode", ",", "rng", ")", ":", "depth", "=", "np", ".", "shape", "(", "query", ")", "[", "-", "1", "]", "dots", "=", "np", ".", "matmul", "(", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
PureDotProductAttention
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.)
tensor2tensor/trax/layers/attention.py
def PureDotProductAttention(dropout=0.0, mode='train'): """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 init_fun(_, input_shapes): # pylint: disable=invalid...
def PureDotProductAttention(dropout=0.0, mode='train'): """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 init_fun(_, input_shapes): # pylint: disable=invalid...
[ "Pure", "single", "-", "headed", "self", "-", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L161-L181
[ "def", "PureDotProductAttention", "(", "dropout", "=", "0.0", ",", "mode", "=", "'train'", ")", ":", "def", "init_fun", "(", "_", ",", "input_shapes", ")", ":", "# pylint: disable=invalid-name", "q_shape", ",", "_", ",", "v_shape", ",", "_", "=", "input_shap...
272500b6efe353aeb638d2745ed56e519462ca31
train
PureMultiHeadedAttention
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...
tensor2tensor/trax/layers/attention.py
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...
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...
[ "Pure", "transformer", "-", "style", "multi", "-", "headed", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L192-L226
[ "def", "PureMultiHeadedAttention", "(", "x", ",", "params", ",", "num_heads", "=", "8", ",", "dropout", "=", "0.0", ",", "mode", "=", "'train'", ",", "*", "*", "kwargs", ")", ":", "del", "params", "rng", "=", "kwargs", ".", "get", "(", "'rng'", ",", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
MultiHeadedAttentionQKV
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.
tensor2tensor/trax/layers/attention.py
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...
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", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L229-L257
[ "def", "MultiHeadedAttentionQKV", "(", "feature_depth", ",", "num_heads", "=", "8", ",", "dropout", "=", "0.0", ",", "mode", "=", "'train'", ")", ":", "return", "combinators", ".", "Serial", "(", "combinators", ".", "Parallel", "(", "combinators", ".", "Para...
272500b6efe353aeb638d2745ed56e519462ca31
train
MultiHeadedAttention
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...
tensor2tensor/trax/layers/attention.py
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...
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...
[ "Transformer", "-", "style", "multi", "-", "headed", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L260-L282
[ "def", "MultiHeadedAttention", "(", "feature_depth", ",", "num_heads", "=", "8", ",", "dropout", "=", "0.0", ",", "mode", "=", "'train'", ")", ":", "return", "combinators", ".", "Serial", "(", "combinators", ".", "Parallel", "(", "combinators", ".", "Branch"...
272500b6efe353aeb638d2745ed56e519462ca31
train
_chunked_selector_output_shape
Helper: calculate output shape for chunked key selector (see below).
tensor2tensor/trax/layers/attention.py
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 < ...
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 < ...
[ "Helper", ":", "calculate", "output", "shape", "for", "chunked", "key", "selector", "(", "see", "below", ")", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L286-L308
[ "def", "_chunked_selector_output_shape", "(", "# pylint: disable=invalid-name", "input_shapes", ",", "selector", "=", "None", ",", "*", "*", "unused_kwargs", ")", ":", "# Read the main function below first, the shape logic just follows the ops.", "selector", "=", "selector", "o...
272500b6efe353aeb638d2745ed56e519462ca31
train
ChunkedAttentionSelector
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...
tensor2tensor/trax/layers/attention.py
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...
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...
[ "Select", "which", "chunks", "to", "attend", "to", "in", "chunked", "attention", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L312-L348
[ "def", "ChunkedAttentionSelector", "(", "x", ",", "params", ",", "selector", "=", "None", ",", "*", "*", "kwargs", ")", ":", "del", "params", ",", "kwargs", "selector", "=", "selector", "or", "(", "lambda", "x", ":", "[", "]", "if", "x", "<", "1", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
ChunkedCausalMultiHeadedAttention
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...
tensor2tensor/trax/layers/attention.py
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...
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...
[ "Transformer", "-", "style", "causal", "multi", "-", "headed", "attention", "operating", "on", "chunks", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L351-L389
[ "def", "ChunkedCausalMultiHeadedAttention", "(", "feature_depth", ",", "num_heads", "=", "8", ",", "dropout", "=", "0.0", ",", "chunk_selector", "=", "None", ",", "mode", "=", "'train'", ")", ":", "prepare_attention_input", "=", "combinators", ".", "Serial", "("...
272500b6efe353aeb638d2745ed56e519462ca31
train
ShiftRight
Layer to shift the tensor to the right by padding on axis 1.
tensor2tensor/trax/layers/attention.py
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...
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...
[ "Layer", "to", "shift", "the", "tensor", "to", "the", "right", "by", "padding", "on", "axis", "1", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L393-L409
[ "def", "ShiftRight", "(", "x", ",", "*", "*", "unused_kwargs", ")", ":", "if", "not", "isinstance", "(", "x", ",", "(", "list", ",", "tuple", ")", ")", ":", "# non-chunked inputs", "pad_widths", "=", "[", "(", "0", ",", "0", ")", ",", "(", "1", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
zipf_distribution
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...
tensor2tensor/data_generators/algorithmic.py
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]. ...
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", ":", "Create", "a", "Zipf", "distribution", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic.py#L208-L223
[ "def", "zipf_distribution", "(", "nbr_symbols", ",", "alpha", ")", ":", "tmp", "=", "np", ".", "power", "(", "np", ".", "arange", "(", "1", ",", "nbr_symbols", "+", "1", ")", ",", "-", "alpha", ")", "zeta", "=", "np", ".", "r_", "[", "0.0", ",", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
zipf_random_sample
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.
tensor2tensor/data_generators/algorithmic.py
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...
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...
[ "Helper", "function", ":", "Generate", "a", "random", "Zipf", "sample", "of", "given", "length", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic.py#L226-L240
[ "def", "zipf_random_sample", "(", "distr_map", ",", "sample_len", ")", ":", "u", "=", "np", ".", "random", ".", "random", "(", "sample_len", ")", "# Random produces values in range [0.0,1.0); even if it is almost", "# improbable(but possible) that it can generate a clear 0.000....
272500b6efe353aeb638d2745ed56e519462ca31
train
reverse_generator_nlplike
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...
tensor2tensor/data_generators/algorithmic.py
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...
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...
[ "Generator", "for", "the", "reversing", "nlp", "-", "like", "task", "on", "sequences", "of", "symbols", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic.py#L243-L274
[ "def", "reverse_generator_nlplike", "(", "nbr_symbols", ",", "max_length", ",", "nbr_cases", ",", "scale_std_dev", "=", "100", ",", "alpha", "=", "1.5", ")", ":", "std_dev", "=", "max_length", "/", "scale_std_dev", "distr_map", "=", "zipf_distribution", "(", "nb...
272500b6efe353aeb638d2745ed56e519462ca31
train
lower_endian_to_number
Helper function: convert a list of digits in the given base to a number.
tensor2tensor/data_generators/algorithmic.py
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)])
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", "list", "of", "digits", "in", "the", "given", "base", "to", "a", "number", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic.py#L311-L313
[ "def", "lower_endian_to_number", "(", "l", ",", "base", ")", ":", "return", "sum", "(", "[", "d", "*", "(", "base", "**", "i", ")", "for", "i", ",", "d", "in", "enumerate", "(", "l", ")", "]", ")" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
number_to_lower_endian
Helper function: convert a number to a list of digits in the given base.
tensor2tensor/data_generators/algorithmic.py
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)
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", ":", "convert", "a", "number", "to", "a", "list", "of", "digits", "in", "the", "given", "base", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic.py#L316-L320
[ "def", "number_to_lower_endian", "(", "n", ",", "base", ")", ":", "if", "n", "<", "base", ":", "return", "[", "n", "]", "return", "[", "n", "%", "base", "]", "+", "number_to_lower_endian", "(", "n", "//", "base", ",", "base", ")" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
random_number_lower_endian
Helper function: generate a random number as a lower-endian digits list.
tensor2tensor/data_generators/algorithmic.py
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...
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...
[ "Helper", "function", ":", "generate", "a", "random", "number", "as", "a", "lower", "-", "endian", "digits", "list", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic.py#L323-L328
[ "def", "random_number_lower_endian", "(", "length", ",", "base", ")", ":", "if", "length", "==", "1", ":", "# Last digit can be 0 only if length is 1.", "return", "[", "np", ".", "random", ".", "randint", "(", "base", ")", "]", "prefix", "=", "[", "np", ".",...
272500b6efe353aeb638d2745ed56e519462ca31
train
remote_run
Run command on GCS instance, optionally detached.
tensor2tensor/data_generators/wikisum/parallel_launch.py
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....
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....
[ "Run", "command", "on", "GCS", "instance", "optionally", "detached", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/parallel_launch.py#L98-L111
[ "def", "remote_run", "(", "cmd", ",", "instance_name", ",", "detach", "=", "False", ",", "retries", "=", "1", ")", ":", "if", "detach", ":", "cmd", "=", "SCREEN", ".", "format", "(", "command", "=", "cmd", ")", "args", "=", "SSH", ".", "format", "(...
272500b6efe353aeb638d2745ed56e519462ca31
train
wait_for_ssh
Wait for SSH to be available at given IP address.
tensor2tensor/data_generators/wikisum/parallel_launch.py
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
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
[ "Wait", "for", "SSH", "to", "be", "available", "at", "given", "IP", "address", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/parallel_launch.py#L128-L138
[ "def", "wait_for_ssh", "(", "ip", ")", ":", "for", "_", "in", "range", "(", "12", ")", ":", "with", "safe_socket", "(", ")", "as", "s", ":", "try", ":", "s", ".", "connect", "(", "(", "ip", ",", "22", ")", ")", "return", "True", "except", "sock...
272500b6efe353aeb638d2745ed56e519462ca31
train
launch_instance
Launch a GCE instance.
tensor2tensor/data_generators/wikisum/parallel_launch.py
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...
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...
[ "Launch", "a", "GCE", "instance", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/parallel_launch.py#L171-L198
[ "def", "launch_instance", "(", "instance_name", ",", "command", ",", "existing_ip", "=", "None", ",", "cpu", "=", "1", ",", "mem", "=", "4", ",", "code_dir", "=", "None", ",", "setup_command", "=", "None", ")", ":", "# Create instance", "ip", "=", "exist...
272500b6efe353aeb638d2745ed56e519462ca31
train
evolved_transformer_encoder
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...
tensor2tensor/models/evolved_transformer.py
def evolved_transformer_encoder(encoder_input, encoder_self_attention_bias, hparams, name="encoder", nonpadding=None, save_weights_to=None, ...
def evolved_transformer_encoder(encoder_input, encoder_self_attention_bias, hparams, name="encoder", nonpadding=None, save_weights_to=None, ...
[ "Evolved", "Transformer", "encoder", ".", "See", "arxiv", ".", "org", "/", "abs", "/", "1901", ".", "11117", "for", "more", "details", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/evolved_transformer.py#L76-L246
[ "def", "evolved_transformer_encoder", "(", "encoder_input", ",", "encoder_self_attention_bias", ",", "hparams", ",", "name", "=", "\"encoder\"", ",", "nonpadding", "=", "None", ",", "save_weights_to", "=", "None", ",", "make_image_summary", "=", "True", ",", "losses...
272500b6efe353aeb638d2745ed56e519462ca31
train
evolved_transformer_decoder
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...
tensor2tensor/models/evolved_transformer.py
def evolved_transformer_decoder(decoder_input, encoder_output, decoder_self_attention_bias, encoder_decoder_attention_bias, hparams, cache=None, ...
def evolved_transformer_decoder(decoder_input, encoder_output, decoder_self_attention_bias, encoder_decoder_attention_bias, hparams, cache=None, ...
[ "Evolved", "Transformer", "decoder", ".", "See", "arxiv", ".", "org", "/", "abs", "/", "1901", ".", "11117", "for", "more", "details", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/evolved_transformer.py#L249-L589
[ "def", "evolved_transformer_decoder", "(", "decoder_input", ",", "encoder_output", ",", "decoder_self_attention_bias", ",", "encoder_decoder_attention_bias", ",", "hparams", ",", "cache", "=", "None", ",", "decode_loop_step", "=", "None", ",", "name", "=", "\"decoder\""...
272500b6efe353aeb638d2745ed56e519462ca31
train
_add_attend_to_encoder_cache
Add attend-to-encoder layers to cache.
tensor2tensor/models/evolved_transformer.py
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...
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...
[ "Add", "attend", "-", "to", "-", "encoder", "layers", "to", "cache", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/evolved_transformer.py#L592-L617
[ "def", "_add_attend_to_encoder_cache", "(", "cache", ",", "attention_name", ",", "hparams", ",", "num_layers", ",", "key_channels", ",", "value_channels", ",", "vars_3d_num_heads", ",", "scope_prefix", ",", "encoder_output", ")", ":", "for", "layer", "in", "range", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_init_evolved_transformer_cache
Create the initial cache for Evolved Transformer fast decoding.
tensor2tensor/models/evolved_transformer.py
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...
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...
[ "Create", "the", "initial", "cache", "for", "Evolved", "Transformer", "fast", "decoding", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/evolved_transformer.py#L620-L700
[ "def", "_init_evolved_transformer_cache", "(", "cache", ",", "hparams", ",", "batch_size", ",", "attention_init_length", ",", "encoder_output", ",", "encoder_decoder_attention_bias", ",", "scope_prefix", ")", ":", "key_channels", "=", "hparams", ".", "attention_key_channe...
272500b6efe353aeb638d2745ed56e519462ca31
train
add_evolved_transformer_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.
tensor2tensor/models/evolved_transformer.py
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...
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...
[ "Add", "Evolved", "Transformer", "hparams", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/evolved_transformer.py#L704-L733
[ "def", "add_evolved_transformer_hparams", "(", "hparams", ")", ":", "# Evolved Transformer \"layers\" are twice as deep as Transformer, so roughly", "# halve the number that we use. These numbers are taken from", "# arxiv.org/abs/1901.11117 .", "hparams", ".", "num_encoder_layers", "=", "3...
272500b6efe353aeb638d2745ed56e519462ca31
train
evolved_transformer_base_tpu
Base parameters for Evolved Transformer model on TPU.
tensor2tensor/models/evolved_transformer.py
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_...
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_...
[ "Base", "parameters", "for", "Evolved", "Transformer", "model", "on", "TPU", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/evolved_transformer.py#L749-L755
[ "def", "evolved_transformer_base_tpu", "(", ")", ":", "hparams", "=", "add_evolved_transformer_hparams", "(", "transformer", ".", "transformer_tpu", "(", ")", ")", "hparams", ".", "learning_rate_constant", "=", "1", "/", "hparams", ".", "learning_rate_warmup_steps", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
evolved_transformer_big_tpu
Big parameters for Evolved Transformer model on TPU.
tensor2tensor/models/evolved_transformer.py
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...
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...
[ "Big", "parameters", "for", "Evolved", "Transformer", "model", "on", "TPU", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/evolved_transformer.py#L759-L765
[ "def", "evolved_transformer_big_tpu", "(", ")", ":", "hparams", "=", "add_evolved_transformer_hparams", "(", "transformer", ".", "transformer_big_tpu", "(", ")", ")", "hparams", ".", "learning_rate_constant", "=", "1", "/", "hparams", ".", "learning_rate_warmup_steps", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
transformer_moe_layer_v1
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 ...
tensor2tensor/models/research/moe.py
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 ...
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 ...
[ "Local", "mixture", "of", "experts", "that", "works", "well", "on", "TPU", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe.py#L30-L156
[ "def", "transformer_moe_layer_v1", "(", "inputs", ",", "output_dim", ",", "hparams", ",", "train", ",", "master_dtype", "=", "tf", ".", "bfloat16", ",", "slice_dtype", "=", "tf", ".", "float32", ")", ":", "orig_inputs", "=", "inputs", "input_dim", "=", "inpu...
272500b6efe353aeb638d2745ed56e519462ca31
train
transformer_moe_layer_v2
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...
tensor2tensor/models/research/moe.py
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 ...
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 ...
[ "2", "-", "level", "mixture", "of", "experts", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe.py#L159-L411
[ "def", "transformer_moe_layer_v2", "(", "inputs", ",", "output_dim", ",", "hparams", ",", "train", ",", "master_dtype", "=", "tf", ".", "bfloat16", ",", "slice_dtype", "=", "tf", ".", "float32", ")", ":", "insert_outer_batch_dim", "=", "(", "len", "(", "inpu...
272500b6efe353aeb638d2745ed56e519462ca31
train
_top_2_gating
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...
tensor2tensor/models/research/moe.py
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...
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...
[ "Compute", "gating", "for", "mixture", "-", "of", "-", "experts", "in", "TensorFlow", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe.py#L414-L610
[ "def", "_top_2_gating", "(", "inputs", ",", "outer_expert_dims", ",", "experts_dim", ",", "expert_capacity_dim", ",", "hparams", ",", "train", ",", "importance", "=", "None", ")", ":", "group_size_dim", ",", "unused_input_dim", "=", "inputs", ".", "shape", ".", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
set_default_moe_hparams
Add necessary hyperparameters for mixture-of-experts.
tensor2tensor/models/research/moe.py
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...
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...
[ "Add", "necessary", "hyperparameters", "for", "mixture", "-", "of", "-", "experts", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe.py#L613-L643
[ "def", "set_default_moe_hparams", "(", "hparams", ")", ":", "hparams", ".", "moe_num_experts", "=", "16", "hparams", ".", "moe_loss_coef", "=", "1e-2", "hparams", ".", "add_hparam", "(", "\"moe_gating\"", ",", "\"top_2\"", ")", "# Experts have fixed capacity per batch...
272500b6efe353aeb638d2745ed56e519462ca31
train
_split_into_groups
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...
tensor2tensor/models/research/moe.py
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: ...
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: ...
[ "Helper", "function", "for", "figuring", "out", "how", "to", "split", "a", "dimensino", "into", "groups", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe.py#L646-L679
[ "def", "_split_into_groups", "(", "n", ",", "max_group_size", ",", "mesh_dim_size", ")", ":", "if", "n", "%", "mesh_dim_size", "!=", "0", ":", "raise", "ValueError", "(", "\"n=%d is not a multiple of mesh_dim_size=%d\"", "%", "(", "n", ",", "mesh_dim_size", ")", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
InGraphBatchEnv.reset
Reset the batch of environments. Args: indices: The batch indices of the environments to reset. Returns: Batch tensor of the new observations.
tensor2tensor/rl/envs/in_graph_batch_env.py
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...
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...
[ "Reset", "the", "batch", "of", "environments", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/envs/in_graph_batch_env.py#L62-L74
[ "def", "reset", "(", "self", ",", "indices", "=", "None", ")", ":", "return", "tf", ".", "cond", "(", "tf", ".", "cast", "(", "tf", ".", "reduce_sum", "(", "indices", "+", "1", ")", ",", "tf", ".", "bool", ")", ",", "lambda", ":", "self", ".", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
adafactor_decay_rate_adam
Second-moment decay rate like Adam, subsuming the correction factor. Args: beta2: a float between 0 and 1 Returns: a scalar
tensor2tensor/utils/adafactor.py
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, ...
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, ...
[ "Second", "-", "moment", "decay", "rate", "like", "Adam", "subsuming", "the", "correction", "factor", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/adafactor.py#L289-L300
[ "def", "adafactor_decay_rate_adam", "(", "beta2", ")", ":", "t", "=", "tf", ".", "to_float", "(", "tf", ".", "train", ".", "get_or_create_global_step", "(", ")", ")", "+", "1.0", "decay", "=", "beta2", "*", "(", "1.0", "-", "tf", ".", "pow", "(", "be...
272500b6efe353aeb638d2745ed56e519462ca31
train
adafactor_optimizer_from_hparams
Create an Adafactor optimizer based on model hparams. Args: hparams: model hyperparameters lr: learning rate scalar. Returns: an AdafactorOptimizer Raises: ValueError: on illegal values
tensor2tensor/utils/adafactor.py
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...
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...
[ "Create", "an", "Adafactor", "optimizer", "based", "on", "model", "hparams", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/adafactor.py#L318-L353
[ "def", "adafactor_optimizer_from_hparams", "(", "hparams", ",", "lr", ")", ":", "if", "hparams", ".", "optimizer_adafactor_decay_type", "==", "\"adam\"", ":", "decay_rate", "=", "adafactor_decay_rate_adam", "(", "hparams", ".", "optimizer_adafactor_beta2", ")", "elif", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
_nargs_validator
Makes validator for function to ensure it takes nargs args.
tensor2tensor/utils/registry.py
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...
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...
[ "Makes", "validator", "for", "function", "to", "ensure", "it", "takes", "nargs", "args", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/registry.py#L287-L299
[ "def", "_nargs_validator", "(", "nargs", ",", "message", ")", ":", "if", "message", "is", "None", ":", "message", "=", "\"Registered function must take exactly %d arguments\"", "%", "nargs", "def", "f", "(", "key", ",", "value", ")", ":", "del", "key", "spec",...
272500b6efe353aeb638d2745ed56e519462ca31
train
parse_problem_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 type ('_rev' or '_copy'). One o...
tensor2tensor/utils/registry.py
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...
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...
[ "Determines", "if", "problem_name", "specifies", "a", "copy", "and", "/", "or", "reversal", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/registry.py#L306-L334
[ "def", "parse_problem_name", "(", "name", ")", ":", "# Recursively strip tags until we reach a base name.", "if", "name", ".", "endswith", "(", "\"_rev\"", ")", ":", "base", ",", "was_reversed", ",", "was_copy", "=", "parse_problem_name", "(", "name", "[", ":", "-...
272500b6efe353aeb638d2745ed56e519462ca31
train
get_problem_name
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...
tensor2tensor/utils/registry.py
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...
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...
[ "Construct", "a", "problem", "name", "from", "base", "and", "reversed", "/", "copy", "options", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/registry.py#L337-L360
[ "def", "get_problem_name", "(", "base_name", ",", "was_reversed", "=", "False", ",", "was_copy", "=", "False", ")", ":", "if", "any", "(", "base_name", ".", "endswith", "(", "suffix", ")", "for", "suffix", "in", "(", "\"_rev\"", ",", "\"_copy\"", ")", ")...
272500b6efe353aeb638d2745ed56e519462ca31
train
optimizer
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 ...
tensor2tensor/utils/registry.py
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...
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", "pre", "-", "registered", "optimizer", "keyed", "by", "name", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/registry.py#L435-L463
[ "def", "optimizer", "(", "name", ")", ":", "warn_msg", "=", "(", "\"Please update `registry.optimizer` callsite \"", "\"(likely due to a `HParams.optimizer` value)\"", ")", "if", "name", "==", "\"SGD\"", ":", "name", "=", "\"sgd\"", "tf", ".", "logging", ".", "warning...
272500b6efe353aeb638d2745ed56e519462ca31
train
problem
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.
tensor2tensor/utils/registry.py
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...
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", "possibly", "copied", "/", "reversed", "problem", "in", "base_registry", "or", "env_registry", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/registry.py#L496-L513
[ "def", "problem", "(", "problem_name", ",", "*", "*", "kwargs", ")", ":", "spec", "=", "parse_problem_name", "(", "problem_name", ")", "try", ":", "return", "Registries", ".", "problems", "[", "spec", ".", "base_name", "]", "(", "was_copy", "=", "spec", ...
272500b6efe353aeb638d2745ed56e519462ca31
train
env_problem
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.
tensor2tensor/utils/registry.py
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...
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...
[ "Get", "and", "initialize", "the", "EnvProblem", "with", "the", "given", "name", "and", "batch", "size", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/registry.py#L516-L530
[ "def", "env_problem", "(", "env_problem_name", ",", "*", "*", "kwargs", ")", ":", "ep_cls", "=", "Registries", ".", "env_problems", "[", "env_problem_name", "]", "ep", "=", "ep_cls", "(", ")", "ep", ".", "initialize", "(", "*", "*", "kwargs", ")", "retur...
272500b6efe353aeb638d2745ed56e519462ca31
train
display_list_by_prefix
Creates a help string for names_list grouped by prefix.
tensor2tensor/utils/registry.py
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...
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...
[ "Creates", "a", "help", "string", "for", "names_list", "grouped", "by", "prefix", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/registry.py#L557-L568
[ "def", "display_list_by_prefix", "(", "names_list", ",", "starting_spaces", "=", "0", ")", ":", "cur_prefix", ",", "result_lines", "=", "None", ",", "[", "]", "space", "=", "\" \"", "*", "starting_spaces", "for", "name", "in", "sorted", "(", "names_list", ")...
272500b6efe353aeb638d2745ed56e519462ca31
train
help_string
Generate help string with contents of registry.
tensor2tensor/utils/registry.py
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 ...
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 ...
[ "Generate", "help", "string", "with", "contents", "of", "registry", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/registry.py#L571-L620
[ "def", "help_string", "(", ")", ":", "help_str", "=", "\"\"\"\nRegistry contents:\n------------------\n\n Models:\n%s\n\n HParams:\n%s\n\n RangedHParams:\n%s\n\n Problems:\n%s\n\n Optimizers:\n%s\n\n Attacks:\n%s\n\n Attack HParams:\n%s\n\n Pruning HParams:\n%s\n\n Pruning Strategies:\n%s\n\n...
272500b6efe353aeb638d2745ed56e519462ca31
train
Registry.validate
Validation function run before setting. Uses function from __init__.
tensor2tensor/utils/registry.py
def validate(self, key, value): """Validation function run before setting. Uses function from __init__.""" if self._validator is not None: self._validator(key, value)
def validate(self, key, value): """Validation function run before setting. Uses function from __init__.""" if self._validator is not None: self._validator(key, value)
[ "Validation", "function", "run", "before", "setting", ".", "Uses", "function", "from", "__init__", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/registry.py#L169-L172
[ "def", "validate", "(", "self", ",", "key", ",", "value", ")", ":", "if", "self", ".", "_validator", "is", "not", "None", ":", "self", ".", "_validator", "(", "key", ",", "value", ")" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
Registry.on_set
Callback called on successful set. Uses function from __init__.
tensor2tensor/utils/registry.py
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)
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)
[ "Callback", "called", "on", "successful", "set", ".", "Uses", "function", "from", "__init__", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/registry.py#L174-L177
[ "def", "on_set", "(", "self", ",", "key", ",", "value", ")", ":", "if", "self", ".", "_on_set", "is", "not", "None", ":", "self", ".", "_on_set", "(", "key", ",", "value", ")" ]
272500b6efe353aeb638d2745ed56e519462ca31
train
Registry.register
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...
tensor2tensor/utils/registry.py
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()...
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()...
[ "Decorator", "to", "register", "a", "function", "or", "registration", "itself", "." ]
tensorflow/tensor2tensor
python
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/registry.py#L201-L249
[ "def", "register", "(", "self", ",", "key_or_value", "=", "None", ")", ":", "def", "decorator", "(", "value", ",", "key", ")", ":", "self", "[", "key", "]", "=", "value", "return", "value", "# Handle if decorator was used without parens", "if", "callable", "...
272500b6efe353aeb638d2745ed56e519462ca31
train
check_dependicies
Check the dynamic symbol versions. Parameters ---------- objdump_string : string The dynamic symbol table entries of the file (result of `objdump -T` command).
helpers/check_dynamic_dependencies.py
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...
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...
[ "Check", "the", "dynamic", "symbol", "versions", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/helpers/check_dynamic_dependencies.py#L10-L38
[ "def", "check_dependicies", "(", "objdump_string", ")", ":", "GLIBC_version", "=", "re", ".", "compile", "(", "r'0{16}[ \\t]+GLIBC_(\\d{1,2})[.](\\d{1,3})[.]?\\d{,3}[ \\t]+'", ")", "versions", "=", "GLIBC_version", ".", "findall", "(", "objdump_string", ")", "assert", "...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
_objective_function_wrapper
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 -----...
python-package/lightgbm/sklearn.py
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 ...
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", "objective", "function", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/sklearn.py#L18-L78
[ "def", "_objective_function_wrapper", "(", "func", ")", ":", "def", "inner", "(", "preds", ",", "dataset", ")", ":", "\"\"\"Call passed function with appropriate arguments.\"\"\"", "labels", "=", "dataset", ".", "get_label", "(", ")", "argc", "=", "argc_", "(", "f...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
_eval_function_wrapper
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...
python-package/lightgbm/sklearn.py
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...
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...
[ "Decorate", "an", "eval", "function", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/sklearn.py#L81-L130
[ "def", "_eval_function_wrapper", "(", "func", ")", ":", "def", "inner", "(", "preds", ",", "dataset", ")", ":", "\"\"\"Call passed function with appropriate arguments.\"\"\"", "labels", "=", "dataset", ".", "get_label", "(", ")", "argc", "=", "argc_", "(", "func",...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
LGBMModel.get_params
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...
python-package/lightgbm/sklearn.py
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 -------...
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 -------...
[ "Get", "parameters", "for", "this", "estimator", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/sklearn.py#L293-L309
[ "def", "get_params", "(", "self", ",", "deep", "=", "True", ")", ":", "params", "=", "super", "(", "LGBMModel", ",", "self", ")", ".", "get_params", "(", "deep", "=", "deep", ")", "params", ".", "update", "(", "self", ".", "_other_params", ")", "retu...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
LGBMModel.fit
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...
python-package/lightgbm/sklearn.py
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...
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...
[ "Build", "a", "gradient", "boosting", "model", "from", "the", "training", "set", "(", "X", "y", ")", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/sklearn.py#L332-L562
[ "def", "fit", "(", "self", ",", "X", ",", "y", ",", "sample_weight", "=", "None", ",", "init_score", "=", "None", ",", "group", "=", "None", ",", "eval_set", "=", "None", ",", "eval_names", "=", "None", ",", "eval_sample_weight", "=", "None", ",", "e...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
LGBMModel.predict
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...
python-package/lightgbm/sklearn.py
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...
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...
[ "Return", "the", "predicted", "value", "for", "each", "sample", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/sklearn.py#L564-L614
[ "def", "predict", "(", "self", ",", "X", ",", "raw_score", "=", "False", ",", "num_iteration", "=", "None", ",", "pred_leaf", "=", "False", ",", "pred_contrib", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_n_features", "is", ...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
LGBMModel.feature_importances_
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...
python-package/lightgbm/sklearn.py
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 ...
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 ...
[ "Get", "feature", "importances", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/sklearn.py#L659-L671
[ "def", "feature_importances_", "(", "self", ")", ":", "if", "self", ".", "_n_features", "is", "None", ":", "raise", "LGBMNotFittedError", "(", "'No feature_importances found. Need to call fit beforehand.'", ")", "return", "self", ".", "booster_", ".", "feature_importanc...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
LGBMRegressor.fit
Docstring is inherited from the LGBMModel.
python-package/lightgbm/sklearn.py
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): ""...
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): ""...
[ "Docstring", "is", "inherited", "from", "the", "LGBMModel", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/sklearn.py#L677-L693
[ "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", ...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
LGBMClassifier.fit
Docstring is inherited from the LGBMModel.
python-package/lightgbm/sklearn.py
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...
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", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/sklearn.py#L703-L752
[ "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",...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
LGBMClassifier.predict
Docstring is inherited from the LGBMModel.
python-package/lightgbm/sklearn.py
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) ...
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) ...
[ "Docstring", "is", "inherited", "from", "the", "LGBMModel", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/sklearn.py#L756-L765
[ "def", "predict", "(", "self", ",", "X", ",", "raw_score", "=", "False", ",", "num_iteration", "=", "None", ",", "pred_leaf", "=", "False", ",", "pred_contrib", "=", "False", ",", "*", "*", "kwargs", ")", ":", "result", "=", "self", ".", "predict_proba...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
LGBMClassifier.predict_proba
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_...
python-package/lightgbm/sklearn.py
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...
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...
[ "Return", "the", "predicted", "probability", "for", "each", "class", "for", "each", "sample", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/sklearn.py#L769-L813
[ "def", "predict_proba", "(", "self", ",", "X", ",", "raw_score", "=", "False", ",", "num_iteration", "=", "None", ",", "pred_leaf", "=", "False", ",", "pred_contrib", "=", "False", ",", "*", "*", "kwargs", ")", ":", "result", "=", "super", "(", "LGBMCl...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
LGBMRanker.fit
Docstring is inherited from the LGBMModel.
python-package/lightgbm/sklearn.py
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...
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...
[ "Docstring", "is", "inherited", "from", "the", "LGBMModel", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/sklearn.py#L833-L867
[ "def", "fit", "(", "self", ",", "X", ",", "y", ",", "sample_weight", "=", "None", ",", "init_score", "=", "None", ",", "group", "=", "None", ",", "eval_set", "=", "None", ",", "eval_names", "=", "None", ",", "eval_sample_weight", "=", "None", ",", "e...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
get_parameter_infos
Parse config header file. Parameters ---------- config_hpp : string Path to the config header file. Returns ------- infos : tuple Tuple with names and content of sections.
helpers/parameter_generator.py
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 ...
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 ...
[ "Parse", "config", "header", "file", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/helpers/parameter_generator.py#L12-L77
[ "def", "get_parameter_infos", "(", "config_hpp", ")", ":", "is_inparameter", "=", "False", "parameter_group", "=", "None", "cur_key", "=", "None", "cur_info", "=", "{", "}", "keys", "=", "[", "]", "member_infos", "=", "[", "]", "with", "open", "(", "config...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
get_names
Get names of all parameters. Parameters ---------- infos : list Content of the config header file. Returns ------- names : list Names of all parameters.
helpers/parameter_generator.py
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"...
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", "names", "of", "all", "parameters", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/helpers/parameter_generator.py#L80-L97
[ "def", "get_names", "(", "infos", ")", ":", "names", "=", "[", "]", "for", "x", "in", "infos", ":", "for", "y", "in", "x", ":", "names", ".", "append", "(", "y", "[", "\"name\"", "]", "[", "0", "]", ")", "return", "names" ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
get_alias
Get aliases of all parameters. Parameters ---------- infos : list Content of the config header file. Returns ------- pairs : list List of tuples (param alias, param name).
helpers/parameter_generator.py
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...
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...
[ "Get", "aliases", "of", "all", "parameters", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/helpers/parameter_generator.py#L100-L121
[ "def", "get_alias", "(", "infos", ")", ":", "pairs", "=", "[", "]", "for", "x", "in", "infos", ":", "for", "y", "in", "x", ":", "if", "\"alias\"", "in", "y", ":", "name", "=", "y", "[", "\"name\"", "]", "[", "0", "]", "alias", "=", "y", "[", ...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
set_one_var_from_string
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...
helpers/parameter_generator.py
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...
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...
[ "Construct", "code", "for", "auto", "config", "file", "for", "one", "param", "value", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/helpers/parameter_generator.py#L124-L157
[ "def", "set_one_var_from_string", "(", "name", ",", "param_type", ",", "checks", ")", ":", "ret", "=", "\"\"", "univar_mapper", "=", "{", "\"int\"", ":", "\"GetInt\"", ",", "\"double\"", ":", "\"GetDouble\"", ",", "\"bool\"", ":", "\"GetBool\"", ",", "\"std::s...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
gen_parameter_description
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.
helpers/parameter_generator.py
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 ...
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 ...
[ "Write", "descriptions", "of", "parameters", "to", "the", "documentation", "file", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/helpers/parameter_generator.py#L160-L242
[ "def", "gen_parameter_description", "(", "sections", ",", "descriptions", ",", "params_rst", ")", ":", "def", "parse_check", "(", "check", ",", "reverse", "=", "False", ")", ":", "\"\"\"Parse the constraint.\n\n Parameters\n ----------\n check : string\n ...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
gen_parameter_code
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.
helpers/parameter_generator.py
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...
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...
[ "Generate", "auto", "config", "file", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/helpers/parameter_generator.py#L245-L320
[ "def", "gen_parameter_code", "(", "config_hpp", ",", "config_out_cpp", ")", ":", "keys", ",", "infos", "=", "get_parameter_infos", "(", "config_hpp", ")", "names", "=", "get_names", "(", "infos", ")", "alias", "=", "get_alias", "(", "infos", ")", "str_to_write...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
_load_lib
Load LightGBM library.
python-package/lightgbm/basic.py
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
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
[ "Load", "LightGBM", "library", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L25-L32
[ "def", "_load_lib", "(", ")", ":", "lib_path", "=", "find_lib_path", "(", ")", "if", "len", "(", "lib_path", ")", "==", "0", ":", "return", "None", "lib", "=", "ctypes", ".", "cdll", ".", "LoadLibrary", "(", "lib_path", "[", "0", "]", ")", "lib", "...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
list_to_1d_numpy
Convert data to 1-D numpy array.
python-package/lightgbm/basic.py
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...
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", "data", "to", "1", "-", "D", "numpy", "array", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L71-L84
[ "def", "list_to_1d_numpy", "(", "data", ",", "dtype", "=", "np", ".", "float32", ",", "name", "=", "'list'", ")", ":", "if", "is_numpy_1d_array", "(", "data", ")", ":", "if", "data", ".", "dtype", "==", "dtype", ":", "return", "data", "else", ":", "r...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
cfloat32_array_to_numpy
Convert a ctypes float pointer array to a numpy array.
python-package/lightgbm/basic.py
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')
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", "float", "pointer", "array", "to", "a", "numpy", "array", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L87-L92
[ "def", "cfloat32_array_to_numpy", "(", "cptr", ",", "length", ")", ":", "if", "isinstance", "(", "cptr", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_float", ")", ")", ":", "return", "np", ".", "fromiter", "(", "cptr", ",", "dtype", "=", "np",...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
cfloat64_array_to_numpy
Convert a ctypes double pointer array to a numpy array.
python-package/lightgbm/basic.py
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')
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", "double", "pointer", "array", "to", "a", "numpy", "array", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L95-L100
[ "def", "cfloat64_array_to_numpy", "(", "cptr", ",", "length", ")", ":", "if", "isinstance", "(", "cptr", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_double", ")", ")", ":", "return", "np", ".", "fromiter", "(", "cptr", ",", "dtype", "=", "np"...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
cint32_array_to_numpy
Convert a ctypes int pointer array to a numpy array.
python-package/lightgbm/basic.py
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')
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", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L103-L108
[ "def", "cint32_array_to_numpy", "(", "cptr", ",", "length", ")", ":", "if", "isinstance", "(", "cptr", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_int32", ")", ")", ":", "return", "np", ".", "fromiter", "(", "cptr", ",", "dtype", "=", "np", ...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
cint8_array_to_numpy
Convert a ctypes int pointer array to a numpy array.
python-package/lightgbm/basic.py
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')
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", "a", "ctypes", "int", "pointer", "array", "to", "a", "numpy", "array", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L111-L116
[ "def", "cint8_array_to_numpy", "(", "cptr", ",", "length", ")", ":", "if", "isinstance", "(", "cptr", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_int8", ")", ")", ":", "return", "np", ".", "fromiter", "(", "cptr", ",", "dtype", "=", "np", "...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
param_dict_to_str
Convert Python dictionary to string, which is passed to C API.
python-package/lightgbm/basic.py
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) + '=' + ',...
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) + '=' + ',...
[ "Convert", "Python", "dictionary", "to", "string", "which", "is", "passed", "to", "C", "API", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L129-L142
[ "def", "param_dict_to_str", "(", "data", ")", ":", "if", "data", "is", "None", "or", "not", "data", ":", "return", "\"\"", "pairs", "=", "[", "]", "for", "key", ",", "val", "in", "data", ".", "items", "(", ")", ":", "if", "isinstance", "(", "val", ...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
convert_from_sliced_object
Fix the memory of multi-dimensional sliced object.
python-package/lightgbm/basic.py
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...
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...
[ "Fix", "the", "memory", "of", "multi", "-", "dimensional", "sliced", "object", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L203-L210
[ "def", "convert_from_sliced_object", "(", "data", ")", ":", "if", "data", ".", "base", "is", "not", "None", "and", "isinstance", "(", "data", ",", "np", ".", "ndarray", ")", "and", "isinstance", "(", "data", ".", "base", ",", "np", ".", "ndarray", ")",...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
c_float_array
Get pointer of float numpy array / list.
python-package/lightgbm/basic.py
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 ...
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", "float", "numpy", "array", "/", "list", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L213-L231
[ "def", "c_float_array", "(", "data", ")", ":", "if", "is_1d_list", "(", "data", ")", ":", "data", "=", "np", ".", "array", "(", "data", ",", "copy", "=", "False", ")", "if", "is_numpy_1d_array", "(", "data", ")", ":", "data", "=", "convert_from_sliced_...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
c_int_array
Get pointer of int numpy array / list.
python-package/lightgbm/basic.py
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...
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...
[ "Get", "pointer", "of", "int", "numpy", "array", "/", "list", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L234-L252
[ "def", "c_int_array", "(", "data", ")", ":", "if", "is_1d_list", "(", "data", ")", ":", "data", "=", "np", ".", "array", "(", "data", ",", "copy", "=", "False", ")", "if", "is_numpy_1d_array", "(", "data", ")", ":", "data", "=", "convert_from_sliced_ob...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
_InnerPredictor.predict
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) ...
python-package/lightgbm/basic.py
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...
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...
[ "Predict", "logic", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L417-L503
[ "def", "predict", "(", "self", ",", "data", ",", "num_iteration", "=", "-", "1", ",", "raw_score", "=", "False", ",", "pred_leaf", "=", "False", ",", "pred_contrib", "=", "False", ",", "data_has_header", "=", "False", ",", "is_reshape", "=", "True", ")",...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
_InnerPredictor.__get_num_preds
Get size of prediction result.
python-package/lightgbm/basic.py
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' ...
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' ...
[ "Get", "size", "of", "prediction", "result", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L505-L519
[ "def", "__get_num_preds", "(", "self", ",", "num_iteration", ",", "nrow", ",", "predict_type", ")", ":", "if", "nrow", ">", "MAX_INT32", ":", "raise", "LightGBMError", "(", "'LightGBM cannot perform prediction for data'", "'with number of rows greater than MAX_INT32 (%d).\\...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
_InnerPredictor.__pred_for_np2d
Predict for a 2-D numpy matrix.
python-package/lightgbm/basic.py
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 ...
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", "2", "-", "D", "numpy", "matrix", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L521-L568
[ "def", "__pred_for_np2d", "(", "self", ",", "mat", ",", "num_iteration", ",", "predict_type", ")", ":", "if", "len", "(", "mat", ".", "shape", ")", "!=", "2", ":", "raise", "ValueError", "(", "'Input numpy.ndarray or list must be 2 dimensional'", ")", "def", "...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
_InnerPredictor.__pred_for_csr
Predict for a CSR data.
python-package/lightgbm/basic.py
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: ...
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", "CSR", "data", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L570-L619
[ "def", "__pred_for_csr", "(", "self", ",", "csr", ",", "num_iteration", ",", "predict_type", ")", ":", "def", "inner_predict", "(", "csr", ",", "num_iteration", ",", "predict_type", ",", "preds", "=", "None", ")", ":", "nrow", "=", "len", "(", "csr", "."...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
_InnerPredictor.__pred_for_csc
Predict for a CSC data.
python-package/lightgbm/basic.py
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...
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...
[ "Predict", "for", "a", "CSC", "data", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L621-L653
[ "def", "__pred_for_csc", "(", "self", ",", "csc", ",", "num_iteration", ",", "predict_type", ")", ":", "nrow", "=", "csc", ".", "shape", "[", "0", "]", "if", "nrow", ">", "MAX_INT32", ":", "return", "self", ".", "__pred_for_csr", "(", "csc", ".", "tocs...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
Dataset.__init_from_np2d
Initialize data from a 2-D numpy matrix.
python-package/lightgbm/basic.py
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...
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", "2", "-", "D", "numpy", "matrix", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L848-L870
[ "def", "__init_from_np2d", "(", "self", ",", "mat", ",", "params_str", ",", "ref_dataset", ")", ":", "if", "len", "(", "mat", ".", "shape", ")", "!=", "2", ":", "raise", "ValueError", "(", "'Input numpy.ndarray must be 2 dimensional'", ")", "self", ".", "han...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
Dataset.__init_from_list_np2d
Initialize data from a list of 2-D numpy matrices.
python-package/lightgbm/basic.py
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))() ...
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", "list", "of", "2", "-", "D", "numpy", "matrices", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L872-L917
[ "def", "__init_from_list_np2d", "(", "self", ",", "mats", ",", "params_str", ",", "ref_dataset", ")", ":", "ncol", "=", "mats", "[", "0", "]", ".", "shape", "[", "1", "]", "nrow", "=", "np", ".", "zeros", "(", "(", "len", "(", "mats", ")", ",", "...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
Dataset.__init_from_csr
Initialize data from a CSR matrix.
python-package/lightgbm/basic.py
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_...
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", "CSR", "matrix", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L919-L943
[ "def", "__init_from_csr", "(", "self", ",", "csr", ",", "params_str", ",", "ref_dataset", ")", ":", "if", "len", "(", "csr", ".", "indices", ")", "!=", "len", "(", "csr", ".", "data", ")", ":", "raise", "ValueError", "(", "'Length mismatch: {} vs {}'", "...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
Dataset.__init_from_csc
Initialize data from a CSC matrix.
python-package/lightgbm/basic.py
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_...
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_...
[ "Initialize", "data", "from", "a", "CSC", "matrix", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L945-L969
[ "def", "__init_from_csc", "(", "self", ",", "csc", ",", "params_str", ",", "ref_dataset", ")", ":", "if", "len", "(", "csc", ".", "indices", ")", "!=", "len", "(", "csc", ".", "data", ")", ":", "raise", "ValueError", "(", "'Length mismatch: {} vs {}'", "...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
Dataset.construct
Lazy init. Returns ------- self : Dataset Constructed Dataset object.
python-package/lightgbm/basic.py
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 ...
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 ...
[ "Lazy", "init", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L971-L1018
[ "def", "construct", "(", "self", ")", ":", "if", "self", ".", "handle", "is", "None", ":", "if", "self", ".", "reference", "is", "not", "None", ":", "if", "self", ".", "used_indices", "is", "None", ":", "# create valid", "self", ".", "_lazy_init", "(",...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
Dataset.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,...
python-package/lightgbm/basic.py
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...
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...
[ "Create", "validation", "data", "align", "with", "current", "Dataset", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1020-L1052
[ "def", "create_valid", "(", "self", ",", "data", ",", "label", "=", "None", ",", "weight", "=", "None", ",", "group", "=", "None", ",", "init_score", "=", "None", ",", "silent", "=", "False", ",", "params", "=", "None", ")", ":", "ret", "=", "Datas...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
Dataset.subset
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...
python-package/lightgbm/basic.py
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...
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...
[ "Get", "subset", "of", "current", "Dataset", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1054-L1077
[ "def", "subset", "(", "self", ",", "used_indices", ",", "params", "=", "None", ")", ":", "if", "params", "is", "None", ":", "params", "=", "self", ".", "params", "ret", "=", "Dataset", "(", "None", ",", "reference", "=", "self", ",", "feature_name", ...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
Dataset.save_binary
Save Dataset to a binary file. Parameters ---------- filename : string Name of the output file. Returns ------- self : Dataset Returns self.
python-package/lightgbm/basic.py
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( ...
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( ...
[ "Save", "Dataset", "to", "a", "binary", "file", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1079-L1095
[ "def", "save_binary", "(", "self", ",", "filename", ")", ":", "_safe_call", "(", "_LIB", ".", "LGBM_DatasetSaveBinary", "(", "self", ".", "construct", "(", ")", ".", "handle", ",", "c_str", "(", "filename", ")", ")", ")", "return", "self" ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
Dataset.set_field
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...
python-package/lightgbm/basic.py
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 ...
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 ...
[ "Set", "property", "into", "the", "Dataset", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1114-L1160
[ "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", ":", "# se...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
Dataset.get_field
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.
python-package/lightgbm/basic.py
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. ""...
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. ""...
[ "Get", "property", "from", "the", "Dataset", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1162-L1199
[ "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", "(", ")",...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
Dataset.set_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 categorical features.
python-package/lightgbm/basic.py
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 ...
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", "categorical", "features", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1201-L1230
[ "def", "set_categorical_feature", "(", "self", ",", "categorical_feature", ")", ":", "if", "self", ".", "categorical_feature", "==", "categorical_feature", ":", "return", "self", "if", "self", ".", "data", "is", "not", "None", ":", "if", "self", ".", "categori...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
Dataset._set_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.
python-package/lightgbm/basic.py
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...
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", "predictor", "for", "continued", "training", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1232-L1245
[ "def", "_set_predictor", "(", "self", ",", "predictor", ")", ":", "if", "predictor", "is", "self", ".", "_predictor", ":", "return", "self", "if", "self", ".", "data", "is", "not", "None", ":", "self", ".", "_predictor", "=", "predictor", "return", "self...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
Dataset.set_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.
python-package/lightgbm/basic.py
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. ...
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", "reference", "Dataset", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1247-L1271
[ "def", "set_reference", "(", "self", ",", "reference", ")", ":", "self", ".", "set_categorical_feature", "(", "reference", ".", "categorical_feature", ")", ".", "set_feature_name", "(", "reference", ".", "feature_name", ")", ".", "_set_predictor", "(", "reference"...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
train
Dataset.set_feature_name
Set feature name. Parameters ---------- feature_name : list of strings Feature names. Returns ------- self : Dataset Dataset with set feature name.
python-package/lightgbm/basic.py
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'...
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", "feature", "name", "." ]
Microsoft/LightGBM
python
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1273-L1297
[ "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", ...
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147