id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
22,800
tensorflow/tensor2tensor
tensor2tensor/utils/decoding.py
run_postdecode_hooks
def run_postdecode_hooks(decode_hook_args, dataset_split): """Run hooks after decodes have run.""" hooks = decode_hook_args.problem.decode_hooks if not hooks: return global_step = latest_checkpoint_step(decode_hook_args.estimator.model_dir) if global_step is None: tf.logging.info( "Skipping decode hooks because no checkpoint yet available.") return tf.logging.info("Running decode hooks.") parent_dir = os.path.join(decode_hook_args.output_dirs[0], os.pardir) child_dir = decode_hook_args.decode_hparams.summaries_log_dir if dataset_split is not None: child_dir += "_{}".format(dataset_split) final_dir = os.path.join(parent_dir, child_dir) summary_writer = tf.summary.FileWriter(final_dir) for hook in hooks: # Isolate each hook in case it creates TF ops with tf.Graph().as_default(): summaries = hook(decode_hook_args) if summaries: summary = tf.Summary(value=list(summaries)) summary_writer.add_summary(summary, global_step) summary_writer.close() tf.logging.info("Decode hooks done.")
python
def run_postdecode_hooks(decode_hook_args, dataset_split): """Run hooks after decodes have run.""" hooks = decode_hook_args.problem.decode_hooks if not hooks: return global_step = latest_checkpoint_step(decode_hook_args.estimator.model_dir) if global_step is None: tf.logging.info( "Skipping decode hooks because no checkpoint yet available.") return tf.logging.info("Running decode hooks.") parent_dir = os.path.join(decode_hook_args.output_dirs[0], os.pardir) child_dir = decode_hook_args.decode_hparams.summaries_log_dir if dataset_split is not None: child_dir += "_{}".format(dataset_split) final_dir = os.path.join(parent_dir, child_dir) summary_writer = tf.summary.FileWriter(final_dir) for hook in hooks: # Isolate each hook in case it creates TF ops with tf.Graph().as_default(): summaries = hook(decode_hook_args) if summaries: summary = tf.Summary(value=list(summaries)) summary_writer.add_summary(summary, global_step) summary_writer.close() tf.logging.info("Decode hooks done.")
[ "def", "run_postdecode_hooks", "(", "decode_hook_args", ",", "dataset_split", ")", ":", "hooks", "=", "decode_hook_args", ".", "problem", ".", "decode_hooks", "if", "not", "hooks", ":", "return", "global_step", "=", "latest_checkpoint_step", "(", "decode_hook_args", ".", "estimator", ".", "model_dir", ")", "if", "global_step", "is", "None", ":", "tf", ".", "logging", ".", "info", "(", "\"Skipping decode hooks because no checkpoint yet available.\"", ")", "return", "tf", ".", "logging", ".", "info", "(", "\"Running decode hooks.\"", ")", "parent_dir", "=", "os", ".", "path", ".", "join", "(", "decode_hook_args", ".", "output_dirs", "[", "0", "]", ",", "os", ".", "pardir", ")", "child_dir", "=", "decode_hook_args", ".", "decode_hparams", ".", "summaries_log_dir", "if", "dataset_split", "is", "not", "None", ":", "child_dir", "+=", "\"_{}\"", ".", "format", "(", "dataset_split", ")", "final_dir", "=", "os", ".", "path", ".", "join", "(", "parent_dir", ",", "child_dir", ")", "summary_writer", "=", "tf", ".", "summary", ".", "FileWriter", "(", "final_dir", ")", "for", "hook", "in", "hooks", ":", "# Isolate each hook in case it creates TF ops", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", ":", "summaries", "=", "hook", "(", "decode_hook_args", ")", "if", "summaries", ":", "summary", "=", "tf", ".", "Summary", "(", "value", "=", "list", "(", "summaries", ")", ")", "summary_writer", ".", "add_summary", "(", "summary", ",", "global_step", ")", "summary_writer", ".", "close", "(", ")", "tf", ".", "logging", ".", "info", "(", "\"Decode hooks done.\"", ")" ]
Run hooks after decodes have run.
[ "Run", "hooks", "after", "decodes", "have", "run", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/decoding.py#L982-L1008
22,801
tensorflow/tensor2tensor
tensor2tensor/data_generators/style_transfer.py
StyleTransferProblemShakespeare.dataset_splits
def dataset_splits(self): """Splits of data to produce and number of output shards for each.""" return [{ "split": problem.DatasetSplit.TRAIN, "shards": _TRAIN_SHARDS, }, { "split": problem.DatasetSplit.EVAL, "shards": _DEV_SHARDS, }]
python
def dataset_splits(self): """Splits of data to produce and number of output shards for each.""" return [{ "split": problem.DatasetSplit.TRAIN, "shards": _TRAIN_SHARDS, }, { "split": problem.DatasetSplit.EVAL, "shards": _DEV_SHARDS, }]
[ "def", "dataset_splits", "(", "self", ")", ":", "return", "[", "{", "\"split\"", ":", "problem", ".", "DatasetSplit", ".", "TRAIN", ",", "\"shards\"", ":", "_TRAIN_SHARDS", ",", "}", ",", "{", "\"split\"", ":", "problem", ".", "DatasetSplit", ".", "EVAL", ",", "\"shards\"", ":", "_DEV_SHARDS", ",", "}", "]" ]
Splits of data to produce and number of output shards for each.
[ "Splits", "of", "data", "to", "produce", "and", "number", "of", "output", "shards", "for", "each", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/style_transfer.py#L87-L95
22,802
tensorflow/tensor2tensor
tensor2tensor/models/mtf_image_transformer.py
local_attention1d_spatial_decoder
def local_attention1d_spatial_decoder(x, kv_dim, heads_dim, feedforward_dim, hparams): """Image Transformer decoder with local1D spatial layers.""" batch_dim, length_dim, model_dim = x.shape.dims blocks_w_dim = mtf.Dimension("blocksw", hparams.block_length) num_w_blocks_dim = mtf.Dimension("num_wblocks", length_dim.size // blocks_w_dim.size) x = mtf.reshape( x, mtf.Shape([batch_dim, num_w_blocks_dim, blocks_w_dim, model_dim])) # [ self attention - ffn - residual + dropout] x n for layer in range(hparams.num_decoder_layers): layer_name = "decoder_layer_%d" % layer with tf.variable_scope(layer_name): # Self attention layer x += layer_prepostprocess_dropout( mtf.layers.local_self_attention_spatial_blocks( mtf.layers.layer_norm(x, model_dim, name="layer_norm_att"), kv_dim, heads_dim, memory_w_dim=blocks_w_dim, mask_right=True, name="self_att"), hparams) # ffn layer x += layer_prepostprocess_dropout( mtf.layers.dense_relu_dense( mtf.layers.layer_norm(x, model_dim, name="layer_norm_ffn"), feedforward_dim, hparams.dropout, dropout_broadcast_dims=[length_dim]), hparams) output = mtf.layers.layer_norm(x, model_dim, name="final_layer_norm") return output
python
def local_attention1d_spatial_decoder(x, kv_dim, heads_dim, feedforward_dim, hparams): """Image Transformer decoder with local1D spatial layers.""" batch_dim, length_dim, model_dim = x.shape.dims blocks_w_dim = mtf.Dimension("blocksw", hparams.block_length) num_w_blocks_dim = mtf.Dimension("num_wblocks", length_dim.size // blocks_w_dim.size) x = mtf.reshape( x, mtf.Shape([batch_dim, num_w_blocks_dim, blocks_w_dim, model_dim])) # [ self attention - ffn - residual + dropout] x n for layer in range(hparams.num_decoder_layers): layer_name = "decoder_layer_%d" % layer with tf.variable_scope(layer_name): # Self attention layer x += layer_prepostprocess_dropout( mtf.layers.local_self_attention_spatial_blocks( mtf.layers.layer_norm(x, model_dim, name="layer_norm_att"), kv_dim, heads_dim, memory_w_dim=blocks_w_dim, mask_right=True, name="self_att"), hparams) # ffn layer x += layer_prepostprocess_dropout( mtf.layers.dense_relu_dense( mtf.layers.layer_norm(x, model_dim, name="layer_norm_ffn"), feedforward_dim, hparams.dropout, dropout_broadcast_dims=[length_dim]), hparams) output = mtf.layers.layer_norm(x, model_dim, name="final_layer_norm") return output
[ "def", "local_attention1d_spatial_decoder", "(", "x", ",", "kv_dim", ",", "heads_dim", ",", "feedforward_dim", ",", "hparams", ")", ":", "batch_dim", ",", "length_dim", ",", "model_dim", "=", "x", ".", "shape", ".", "dims", "blocks_w_dim", "=", "mtf", ".", "Dimension", "(", "\"blocksw\"", ",", "hparams", ".", "block_length", ")", "num_w_blocks_dim", "=", "mtf", ".", "Dimension", "(", "\"num_wblocks\"", ",", "length_dim", ".", "size", "//", "blocks_w_dim", ".", "size", ")", "x", "=", "mtf", ".", "reshape", "(", "x", ",", "mtf", ".", "Shape", "(", "[", "batch_dim", ",", "num_w_blocks_dim", ",", "blocks_w_dim", ",", "model_dim", "]", ")", ")", "# [ self attention - ffn - residual + dropout] x n", "for", "layer", "in", "range", "(", "hparams", ".", "num_decoder_layers", ")", ":", "layer_name", "=", "\"decoder_layer_%d\"", "%", "layer", "with", "tf", ".", "variable_scope", "(", "layer_name", ")", ":", "# Self attention layer", "x", "+=", "layer_prepostprocess_dropout", "(", "mtf", ".", "layers", ".", "local_self_attention_spatial_blocks", "(", "mtf", ".", "layers", ".", "layer_norm", "(", "x", ",", "model_dim", ",", "name", "=", "\"layer_norm_att\"", ")", ",", "kv_dim", ",", "heads_dim", ",", "memory_w_dim", "=", "blocks_w_dim", ",", "mask_right", "=", "True", ",", "name", "=", "\"self_att\"", ")", ",", "hparams", ")", "# ffn layer", "x", "+=", "layer_prepostprocess_dropout", "(", "mtf", ".", "layers", ".", "dense_relu_dense", "(", "mtf", ".", "layers", ".", "layer_norm", "(", "x", ",", "model_dim", ",", "name", "=", "\"layer_norm_ffn\"", ")", ",", "feedforward_dim", ",", "hparams", ".", "dropout", ",", "dropout_broadcast_dims", "=", "[", "length_dim", "]", ")", ",", "hparams", ")", "output", "=", "mtf", ".", "layers", ".", "layer_norm", "(", "x", ",", "model_dim", ",", "name", "=", "\"final_layer_norm\"", ")", "return", "output" ]
Image Transformer decoder with local1D spatial layers.
[ "Image", "Transformer", "decoder", "with", "local1D", "spatial", "layers", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L252-L283
22,803
tensorflow/tensor2tensor
tensor2tensor/models/mtf_image_transformer.py
local_attention2d_spatial_decoder
def local_attention2d_spatial_decoder(x, kv_dim, heads_dim, feedforward_dim, hparams): """Image Transformer decoder with local2D spatial layers.""" batch_dim, length_dim, model_dim = x.shape.dims blocks_h_dim = mtf.Dimension("blocksh", hparams.block_height) blocks_w_dim = mtf.Dimension("blocksw", hparams.block_width) num_h_blocks_dim = mtf.Dimension("num_h_blocks", hparams.img_len // hparams.block_height) num_w_blocks_dim = mtf.Dimension( "num_w_blocks", hparams.img_len * hparams.num_channels // hparams.block_width) x = mtf.transpose( mtf.reshape( x, mtf.Shape([ batch_dim, num_h_blocks_dim, blocks_h_dim, num_w_blocks_dim, blocks_w_dim, model_dim ])), mtf.Shape([ batch_dim, num_h_blocks_dim, num_w_blocks_dim, blocks_h_dim, blocks_w_dim, model_dim ])) # Image Transformer Decoder # [ self attention - ffn - residual + dropout] x n for layer in range(hparams.num_decoder_layers): layer_name = "decoder_layer_%d" % layer with tf.variable_scope(layer_name): # Self attention layer x += layer_prepostprocess_dropout( mtf.layers.local_2d_self_attention_spatial_blocks( mtf.layers.layer_norm(x, model_dim, name="layer_norm_att"), kv_dim, heads_dim, memory_h_dim=num_h_blocks_dim, memory_w_dim=num_w_blocks_dim, name="self_att"), hparams) # ffn layer x += layer_prepostprocess_dropout( mtf.layers.dense_relu_dense( mtf.layers.layer_norm(x, model_dim, name="layer_norm_ffn"), feedforward_dim, hparams.dropout, dropout_broadcast_dims=[length_dim]), hparams) output = mtf.layers.layer_norm(x, model_dim, name="final_layer_norm") return output
python
def local_attention2d_spatial_decoder(x, kv_dim, heads_dim, feedforward_dim, hparams): """Image Transformer decoder with local2D spatial layers.""" batch_dim, length_dim, model_dim = x.shape.dims blocks_h_dim = mtf.Dimension("blocksh", hparams.block_height) blocks_w_dim = mtf.Dimension("blocksw", hparams.block_width) num_h_blocks_dim = mtf.Dimension("num_h_blocks", hparams.img_len // hparams.block_height) num_w_blocks_dim = mtf.Dimension( "num_w_blocks", hparams.img_len * hparams.num_channels // hparams.block_width) x = mtf.transpose( mtf.reshape( x, mtf.Shape([ batch_dim, num_h_blocks_dim, blocks_h_dim, num_w_blocks_dim, blocks_w_dim, model_dim ])), mtf.Shape([ batch_dim, num_h_blocks_dim, num_w_blocks_dim, blocks_h_dim, blocks_w_dim, model_dim ])) # Image Transformer Decoder # [ self attention - ffn - residual + dropout] x n for layer in range(hparams.num_decoder_layers): layer_name = "decoder_layer_%d" % layer with tf.variable_scope(layer_name): # Self attention layer x += layer_prepostprocess_dropout( mtf.layers.local_2d_self_attention_spatial_blocks( mtf.layers.layer_norm(x, model_dim, name="layer_norm_att"), kv_dim, heads_dim, memory_h_dim=num_h_blocks_dim, memory_w_dim=num_w_blocks_dim, name="self_att"), hparams) # ffn layer x += layer_prepostprocess_dropout( mtf.layers.dense_relu_dense( mtf.layers.layer_norm(x, model_dim, name="layer_norm_ffn"), feedforward_dim, hparams.dropout, dropout_broadcast_dims=[length_dim]), hparams) output = mtf.layers.layer_norm(x, model_dim, name="final_layer_norm") return output
[ "def", "local_attention2d_spatial_decoder", "(", "x", ",", "kv_dim", ",", "heads_dim", ",", "feedforward_dim", ",", "hparams", ")", ":", "batch_dim", ",", "length_dim", ",", "model_dim", "=", "x", ".", "shape", ".", "dims", "blocks_h_dim", "=", "mtf", ".", "Dimension", "(", "\"blocksh\"", ",", "hparams", ".", "block_height", ")", "blocks_w_dim", "=", "mtf", ".", "Dimension", "(", "\"blocksw\"", ",", "hparams", ".", "block_width", ")", "num_h_blocks_dim", "=", "mtf", ".", "Dimension", "(", "\"num_h_blocks\"", ",", "hparams", ".", "img_len", "//", "hparams", ".", "block_height", ")", "num_w_blocks_dim", "=", "mtf", ".", "Dimension", "(", "\"num_w_blocks\"", ",", "hparams", ".", "img_len", "*", "hparams", ".", "num_channels", "//", "hparams", ".", "block_width", ")", "x", "=", "mtf", ".", "transpose", "(", "mtf", ".", "reshape", "(", "x", ",", "mtf", ".", "Shape", "(", "[", "batch_dim", ",", "num_h_blocks_dim", ",", "blocks_h_dim", ",", "num_w_blocks_dim", ",", "blocks_w_dim", ",", "model_dim", "]", ")", ")", ",", "mtf", ".", "Shape", "(", "[", "batch_dim", ",", "num_h_blocks_dim", ",", "num_w_blocks_dim", ",", "blocks_h_dim", ",", "blocks_w_dim", ",", "model_dim", "]", ")", ")", "# Image Transformer Decoder", "# [ self attention - ffn - residual + dropout] x n", "for", "layer", "in", "range", "(", "hparams", ".", "num_decoder_layers", ")", ":", "layer_name", "=", "\"decoder_layer_%d\"", "%", "layer", "with", "tf", ".", "variable_scope", "(", "layer_name", ")", ":", "# Self attention layer", "x", "+=", "layer_prepostprocess_dropout", "(", "mtf", ".", "layers", ".", "local_2d_self_attention_spatial_blocks", "(", "mtf", ".", "layers", ".", "layer_norm", "(", "x", ",", "model_dim", ",", "name", "=", "\"layer_norm_att\"", ")", ",", "kv_dim", ",", "heads_dim", ",", "memory_h_dim", "=", "num_h_blocks_dim", ",", "memory_w_dim", "=", "num_w_blocks_dim", ",", "name", "=", "\"self_att\"", ")", ",", "hparams", ")", "# ffn layer", "x", "+=", "layer_prepostprocess_dropout", "(", "mtf", ".", "layers", ".", "dense_relu_dense", "(", "mtf", ".", "layers", ".", "layer_norm", "(", "x", ",", "model_dim", ",", "name", "=", "\"layer_norm_ffn\"", ")", ",", "feedforward_dim", ",", "hparams", ".", "dropout", ",", "dropout_broadcast_dims", "=", "[", "length_dim", "]", ")", ",", "hparams", ")", "output", "=", "mtf", ".", "layers", ".", "layer_norm", "(", "x", ",", "model_dim", ",", "name", "=", "\"final_layer_norm\"", ")", "return", "output" ]
Image Transformer decoder with local2D spatial layers.
[ "Image", "Transformer", "decoder", "with", "local2D", "spatial", "layers", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L286-L331
22,804
tensorflow/tensor2tensor
tensor2tensor/models/mtf_image_transformer.py
local_attention1d_masked_decoder
def local_attention1d_masked_decoder(x, kv_dim, heads_dim, feedforward_dim, hparams): """Image Transformer decoder with local1D masked layers.""" print(x) _, length_dim, model_dim = x.shape.dims for layer in range(hparams.num_decoder_layers): layer_name = "decoder_layer_%d" % layer with tf.variable_scope(layer_name): # Self attention layer length_per_split = mtf.tensor_dim_to_size_per_split( hparams.layout, hparams.mesh_shape, length_dim) x += layer_prepostprocess_dropout( mtf.layers.masked_local_attention_1d( mtf.layers.layer_norm(x, model_dim, name="layer_norm_att"), kv_dim, heads_dim, window_size=hparams.block_length, length_per_split=length_per_split, name="self_att"), hparams) # ffn layer x += layer_prepostprocess_dropout( mtf.layers.dense_relu_dense( mtf.layers.layer_norm(x, model_dim, name="layer_norm_ffn"), feedforward_dim, hparams.dropout, dropout_broadcast_dims=[length_dim]), hparams) output = mtf.layers.layer_norm(x, model_dim, name="final_layer_norm") return output
python
def local_attention1d_masked_decoder(x, kv_dim, heads_dim, feedforward_dim, hparams): """Image Transformer decoder with local1D masked layers.""" print(x) _, length_dim, model_dim = x.shape.dims for layer in range(hparams.num_decoder_layers): layer_name = "decoder_layer_%d" % layer with tf.variable_scope(layer_name): # Self attention layer length_per_split = mtf.tensor_dim_to_size_per_split( hparams.layout, hparams.mesh_shape, length_dim) x += layer_prepostprocess_dropout( mtf.layers.masked_local_attention_1d( mtf.layers.layer_norm(x, model_dim, name="layer_norm_att"), kv_dim, heads_dim, window_size=hparams.block_length, length_per_split=length_per_split, name="self_att"), hparams) # ffn layer x += layer_prepostprocess_dropout( mtf.layers.dense_relu_dense( mtf.layers.layer_norm(x, model_dim, name="layer_norm_ffn"), feedforward_dim, hparams.dropout, dropout_broadcast_dims=[length_dim]), hparams) output = mtf.layers.layer_norm(x, model_dim, name="final_layer_norm") return output
[ "def", "local_attention1d_masked_decoder", "(", "x", ",", "kv_dim", ",", "heads_dim", ",", "feedforward_dim", ",", "hparams", ")", ":", "print", "(", "x", ")", "_", ",", "length_dim", ",", "model_dim", "=", "x", ".", "shape", ".", "dims", "for", "layer", "in", "range", "(", "hparams", ".", "num_decoder_layers", ")", ":", "layer_name", "=", "\"decoder_layer_%d\"", "%", "layer", "with", "tf", ".", "variable_scope", "(", "layer_name", ")", ":", "# Self attention layer", "length_per_split", "=", "mtf", ".", "tensor_dim_to_size_per_split", "(", "hparams", ".", "layout", ",", "hparams", ".", "mesh_shape", ",", "length_dim", ")", "x", "+=", "layer_prepostprocess_dropout", "(", "mtf", ".", "layers", ".", "masked_local_attention_1d", "(", "mtf", ".", "layers", ".", "layer_norm", "(", "x", ",", "model_dim", ",", "name", "=", "\"layer_norm_att\"", ")", ",", "kv_dim", ",", "heads_dim", ",", "window_size", "=", "hparams", ".", "block_length", ",", "length_per_split", "=", "length_per_split", ",", "name", "=", "\"self_att\"", ")", ",", "hparams", ")", "# ffn layer", "x", "+=", "layer_prepostprocess_dropout", "(", "mtf", ".", "layers", ".", "dense_relu_dense", "(", "mtf", ".", "layers", ".", "layer_norm", "(", "x", ",", "model_dim", ",", "name", "=", "\"layer_norm_ffn\"", ")", ",", "feedforward_dim", ",", "hparams", ".", "dropout", ",", "dropout_broadcast_dims", "=", "[", "length_dim", "]", ")", ",", "hparams", ")", "output", "=", "mtf", ".", "layers", ".", "layer_norm", "(", "x", ",", "model_dim", ",", "name", "=", "\"final_layer_norm\"", ")", "return", "output" ]
Image Transformer decoder with local1D masked layers.
[ "Image", "Transformer", "decoder", "with", "local1D", "masked", "layers", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/mtf_image_transformer.py#L334-L362
22,805
tensorflow/tensor2tensor
tensor2tensor/layers/reversible_layers.py
create_degrees
def create_degrees(input_dim, hidden_dims, input_order='left-to-right', hidden_order='left-to-right'): """Returns a list of degree vectors, one for each input and hidden layer. A unit with degree d can only receive input from units with degree < d. Output units always have the same degree as their associated input unit. Args: input_dim: Number of inputs. hidden_dims: list with the number of hidden units per layer. It does not include the output layer. Each hidden unit size must be at least the size of length (otherwise autoregressivity is not possible). input_order: Order of degrees to the input units: 'random', 'left-to-right', 'right-to-left', or an array of an explicit order. For example, 'left-to-right' builds an autoregressive model p(x) = p(x1) p(x2 | x1) ... p(xD | x<D). hidden_order: Order of degrees to the hidden units: 'random', 'left-to-right'. If 'left-to-right', hidden units are allocated equally (up to a remainder term) to each degree. """ if (isinstance(input_order, str) and input_order not in ('random', 'left-to-right', 'right-to-left')): raise ValueError('Input order is not valid.') if hidden_order not in ('random', 'left-to-right'): raise ValueError('Hidden order is not valid.') degrees = [] if isinstance(input_order, str): input_degrees = np.arange(1, input_dim + 1) if input_order == 'right-to-left': input_degrees = np.flip(input_degrees, 0) elif input_order == 'random': np.random.shuffle(input_degrees) else: input_order = np.array(input_order) if np.all(np.sort(input_order) != np.arange(1, input_dim + 1)): raise ValueError('invalid input order') input_degrees = input_order degrees.append(input_degrees) for units in hidden_dims: if hidden_order == 'random': min_prev_degree = min(np.min(degrees[-1]), input_dim - 1) hidden_degrees = np.random.randint( low=min_prev_degree, high=input_dim, size=units) elif hidden_order == 'left-to-right': hidden_degrees = (np.arange(units) % max(1, input_dim - 1) + min(1, input_dim - 1)) degrees.append(hidden_degrees) return degrees
python
def create_degrees(input_dim, hidden_dims, input_order='left-to-right', hidden_order='left-to-right'): """Returns a list of degree vectors, one for each input and hidden layer. A unit with degree d can only receive input from units with degree < d. Output units always have the same degree as their associated input unit. Args: input_dim: Number of inputs. hidden_dims: list with the number of hidden units per layer. It does not include the output layer. Each hidden unit size must be at least the size of length (otherwise autoregressivity is not possible). input_order: Order of degrees to the input units: 'random', 'left-to-right', 'right-to-left', or an array of an explicit order. For example, 'left-to-right' builds an autoregressive model p(x) = p(x1) p(x2 | x1) ... p(xD | x<D). hidden_order: Order of degrees to the hidden units: 'random', 'left-to-right'. If 'left-to-right', hidden units are allocated equally (up to a remainder term) to each degree. """ if (isinstance(input_order, str) and input_order not in ('random', 'left-to-right', 'right-to-left')): raise ValueError('Input order is not valid.') if hidden_order not in ('random', 'left-to-right'): raise ValueError('Hidden order is not valid.') degrees = [] if isinstance(input_order, str): input_degrees = np.arange(1, input_dim + 1) if input_order == 'right-to-left': input_degrees = np.flip(input_degrees, 0) elif input_order == 'random': np.random.shuffle(input_degrees) else: input_order = np.array(input_order) if np.all(np.sort(input_order) != np.arange(1, input_dim + 1)): raise ValueError('invalid input order') input_degrees = input_order degrees.append(input_degrees) for units in hidden_dims: if hidden_order == 'random': min_prev_degree = min(np.min(degrees[-1]), input_dim - 1) hidden_degrees = np.random.randint( low=min_prev_degree, high=input_dim, size=units) elif hidden_order == 'left-to-right': hidden_degrees = (np.arange(units) % max(1, input_dim - 1) + min(1, input_dim - 1)) degrees.append(hidden_degrees) return degrees
[ "def", "create_degrees", "(", "input_dim", ",", "hidden_dims", ",", "input_order", "=", "'left-to-right'", ",", "hidden_order", "=", "'left-to-right'", ")", ":", "if", "(", "isinstance", "(", "input_order", ",", "str", ")", "and", "input_order", "not", "in", "(", "'random'", ",", "'left-to-right'", ",", "'right-to-left'", ")", ")", ":", "raise", "ValueError", "(", "'Input order is not valid.'", ")", "if", "hidden_order", "not", "in", "(", "'random'", ",", "'left-to-right'", ")", ":", "raise", "ValueError", "(", "'Hidden order is not valid.'", ")", "degrees", "=", "[", "]", "if", "isinstance", "(", "input_order", ",", "str", ")", ":", "input_degrees", "=", "np", ".", "arange", "(", "1", ",", "input_dim", "+", "1", ")", "if", "input_order", "==", "'right-to-left'", ":", "input_degrees", "=", "np", ".", "flip", "(", "input_degrees", ",", "0", ")", "elif", "input_order", "==", "'random'", ":", "np", ".", "random", ".", "shuffle", "(", "input_degrees", ")", "else", ":", "input_order", "=", "np", ".", "array", "(", "input_order", ")", "if", "np", ".", "all", "(", "np", ".", "sort", "(", "input_order", ")", "!=", "np", ".", "arange", "(", "1", ",", "input_dim", "+", "1", ")", ")", ":", "raise", "ValueError", "(", "'invalid input order'", ")", "input_degrees", "=", "input_order", "degrees", ".", "append", "(", "input_degrees", ")", "for", "units", "in", "hidden_dims", ":", "if", "hidden_order", "==", "'random'", ":", "min_prev_degree", "=", "min", "(", "np", ".", "min", "(", "degrees", "[", "-", "1", "]", ")", ",", "input_dim", "-", "1", ")", "hidden_degrees", "=", "np", ".", "random", ".", "randint", "(", "low", "=", "min_prev_degree", ",", "high", "=", "input_dim", ",", "size", "=", "units", ")", "elif", "hidden_order", "==", "'left-to-right'", ":", "hidden_degrees", "=", "(", "np", ".", "arange", "(", "units", ")", "%", "max", "(", "1", ",", "input_dim", "-", "1", ")", "+", "min", "(", "1", ",", "input_dim", "-", "1", ")", ")", "degrees", ".", "append", "(", "hidden_degrees", ")", "return", "degrees" ]
Returns a list of degree vectors, one for each input and hidden layer. A unit with degree d can only receive input from units with degree < d. Output units always have the same degree as their associated input unit. Args: input_dim: Number of inputs. hidden_dims: list with the number of hidden units per layer. It does not include the output layer. Each hidden unit size must be at least the size of length (otherwise autoregressivity is not possible). input_order: Order of degrees to the input units: 'random', 'left-to-right', 'right-to-left', or an array of an explicit order. For example, 'left-to-right' builds an autoregressive model p(x) = p(x1) p(x2 | x1) ... p(xD | x<D). hidden_order: Order of degrees to the hidden units: 'random', 'left-to-right'. If 'left-to-right', hidden units are allocated equally (up to a remainder term) to each degree.
[ "Returns", "a", "list", "of", "degree", "vectors", "one", "for", "each", "input", "and", "hidden", "layer", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/reversible_layers.py#L218-L269
22,806
tensorflow/tensor2tensor
tensor2tensor/layers/reversible_layers.py
create_masks
def create_masks(input_dim, hidden_dims, input_order='left-to-right', hidden_order='left-to-right'): """Returns a list of binary mask matrices respecting autoregressive ordering. Args: input_dim: Number of inputs. hidden_dims: list with the number of hidden units per layer. It does not include the output layer; those number of units will always be set to input_dim downstream. Each hidden unit size must be at least the size of length (otherwise autoregressivity is not possible). input_order: Order of degrees to the input units: 'random', 'left-to-right', 'right-to-left', or an array of an explicit order. For example, 'left-to-right' builds an autoregressive model p(x) = p(x1) p(x2 | x1) ... p(xD | x<D). hidden_order: Order of degrees to the hidden units: 'random', 'left-to-right'. If 'left-to-right', hidden units are allocated equally (up to a remainder term) to each degree. """ degrees = create_degrees(input_dim, hidden_dims, input_order, hidden_order) masks = [] # Create input-to-hidden and hidden-to-hidden masks. for input_degrees, output_degrees in zip(degrees[:-1], degrees[1:]): mask = tf.cast(input_degrees[:, np.newaxis] <= output_degrees, tf.float32) masks.append(mask) # Create hidden-to-output mask. mask = tf.cast(degrees[-1][:, np.newaxis] < degrees[0], tf.float32) masks.append(mask) return masks
python
def create_masks(input_dim, hidden_dims, input_order='left-to-right', hidden_order='left-to-right'): """Returns a list of binary mask matrices respecting autoregressive ordering. Args: input_dim: Number of inputs. hidden_dims: list with the number of hidden units per layer. It does not include the output layer; those number of units will always be set to input_dim downstream. Each hidden unit size must be at least the size of length (otherwise autoregressivity is not possible). input_order: Order of degrees to the input units: 'random', 'left-to-right', 'right-to-left', or an array of an explicit order. For example, 'left-to-right' builds an autoregressive model p(x) = p(x1) p(x2 | x1) ... p(xD | x<D). hidden_order: Order of degrees to the hidden units: 'random', 'left-to-right'. If 'left-to-right', hidden units are allocated equally (up to a remainder term) to each degree. """ degrees = create_degrees(input_dim, hidden_dims, input_order, hidden_order) masks = [] # Create input-to-hidden and hidden-to-hidden masks. for input_degrees, output_degrees in zip(degrees[:-1], degrees[1:]): mask = tf.cast(input_degrees[:, np.newaxis] <= output_degrees, tf.float32) masks.append(mask) # Create hidden-to-output mask. mask = tf.cast(degrees[-1][:, np.newaxis] < degrees[0], tf.float32) masks.append(mask) return masks
[ "def", "create_masks", "(", "input_dim", ",", "hidden_dims", ",", "input_order", "=", "'left-to-right'", ",", "hidden_order", "=", "'left-to-right'", ")", ":", "degrees", "=", "create_degrees", "(", "input_dim", ",", "hidden_dims", ",", "input_order", ",", "hidden_order", ")", "masks", "=", "[", "]", "# Create input-to-hidden and hidden-to-hidden masks.", "for", "input_degrees", ",", "output_degrees", "in", "zip", "(", "degrees", "[", ":", "-", "1", "]", ",", "degrees", "[", "1", ":", "]", ")", ":", "mask", "=", "tf", ".", "cast", "(", "input_degrees", "[", ":", ",", "np", ".", "newaxis", "]", "<=", "output_degrees", ",", "tf", ".", "float32", ")", "masks", ".", "append", "(", "mask", ")", "# Create hidden-to-output mask.", "mask", "=", "tf", ".", "cast", "(", "degrees", "[", "-", "1", "]", "[", ":", ",", "np", ".", "newaxis", "]", "<", "degrees", "[", "0", "]", ",", "tf", ".", "float32", ")", "masks", ".", "append", "(", "mask", ")", "return", "masks" ]
Returns a list of binary mask matrices respecting autoregressive ordering. Args: input_dim: Number of inputs. hidden_dims: list with the number of hidden units per layer. It does not include the output layer; those number of units will always be set to input_dim downstream. Each hidden unit size must be at least the size of length (otherwise autoregressivity is not possible). input_order: Order of degrees to the input units: 'random', 'left-to-right', 'right-to-left', or an array of an explicit order. For example, 'left-to-right' builds an autoregressive model p(x) = p(x1) p(x2 | x1) ... p(xD | x<D). hidden_order: Order of degrees to the hidden units: 'random', 'left-to-right'. If 'left-to-right', hidden units are allocated equally (up to a remainder term) to each degree.
[ "Returns", "a", "list", "of", "binary", "mask", "matrices", "respecting", "autoregressive", "ordering", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/reversible_layers.py#L272-L302
22,807
tensorflow/tensor2tensor
tensor2tensor/layers/reversible_layers.py
sinkhorn
def sinkhorn(inputs, n_iters=20): """Performs incomplete Sinkhorn normalization to inputs. By a theorem by Sinkhorn and Knopp [1], a sufficiently well-behaved matrix with positive entries can be turned into a doubly-stochastic matrix (i.e. its rows and columns add up to one) via the succesive row and column normalization. -To ensure positivity, the effective input to sinkhorn has to be exp(inputs) (elementwise). -However, for stability, sinkhorn works in the log-space. It is only at return time that entries are exponentiated. Code is adapted from Mena et al. [2]. [1] Richard Sinkhorn and Paul Knopp. Concerning nonnegative matrices and doubly stochastic matrices. Pacific Journal of Mathematics, 1967. [2] Gonzalo Mena, David Belanger, Scott Linderman, Jasper Snoek. Learning latent permutations with Gumbel-Sinkhorn networks. International Conference on Learning Representations, 2018. Args: inputs: A `Tensor` with shape `[..., vocab_size, vocab_size]`. n_iters: Number of sinkhorn iterations (in practice, as little as 20 iterations are needed to achieve decent convergence for `vocab_size` ~100) Returns: outputs: A `Tensor` of close-to-doubly-stochastic matrices with shape `[:, vocab_size, vocab_size]`. """ vocab_size = tf.shape(inputs)[-1] log_alpha = tf.reshape(inputs, [-1, vocab_size, vocab_size]) for _ in range(n_iters): log_alpha -= tf.reshape(tf.reduce_logsumexp(log_alpha, axis=2), [-1, vocab_size, 1]) log_alpha -= tf.reshape(tf.reduce_logsumexp(log_alpha, axis=1), [-1, 1, vocab_size]) outputs = tf.exp(log_alpha) return outputs
python
def sinkhorn(inputs, n_iters=20): """Performs incomplete Sinkhorn normalization to inputs. By a theorem by Sinkhorn and Knopp [1], a sufficiently well-behaved matrix with positive entries can be turned into a doubly-stochastic matrix (i.e. its rows and columns add up to one) via the succesive row and column normalization. -To ensure positivity, the effective input to sinkhorn has to be exp(inputs) (elementwise). -However, for stability, sinkhorn works in the log-space. It is only at return time that entries are exponentiated. Code is adapted from Mena et al. [2]. [1] Richard Sinkhorn and Paul Knopp. Concerning nonnegative matrices and doubly stochastic matrices. Pacific Journal of Mathematics, 1967. [2] Gonzalo Mena, David Belanger, Scott Linderman, Jasper Snoek. Learning latent permutations with Gumbel-Sinkhorn networks. International Conference on Learning Representations, 2018. Args: inputs: A `Tensor` with shape `[..., vocab_size, vocab_size]`. n_iters: Number of sinkhorn iterations (in practice, as little as 20 iterations are needed to achieve decent convergence for `vocab_size` ~100) Returns: outputs: A `Tensor` of close-to-doubly-stochastic matrices with shape `[:, vocab_size, vocab_size]`. """ vocab_size = tf.shape(inputs)[-1] log_alpha = tf.reshape(inputs, [-1, vocab_size, vocab_size]) for _ in range(n_iters): log_alpha -= tf.reshape(tf.reduce_logsumexp(log_alpha, axis=2), [-1, vocab_size, 1]) log_alpha -= tf.reshape(tf.reduce_logsumexp(log_alpha, axis=1), [-1, 1, vocab_size]) outputs = tf.exp(log_alpha) return outputs
[ "def", "sinkhorn", "(", "inputs", ",", "n_iters", "=", "20", ")", ":", "vocab_size", "=", "tf", ".", "shape", "(", "inputs", ")", "[", "-", "1", "]", "log_alpha", "=", "tf", ".", "reshape", "(", "inputs", ",", "[", "-", "1", ",", "vocab_size", ",", "vocab_size", "]", ")", "for", "_", "in", "range", "(", "n_iters", ")", ":", "log_alpha", "-=", "tf", ".", "reshape", "(", "tf", ".", "reduce_logsumexp", "(", "log_alpha", ",", "axis", "=", "2", ")", ",", "[", "-", "1", ",", "vocab_size", ",", "1", "]", ")", "log_alpha", "-=", "tf", ".", "reshape", "(", "tf", ".", "reduce_logsumexp", "(", "log_alpha", ",", "axis", "=", "1", ")", ",", "[", "-", "1", ",", "1", ",", "vocab_size", "]", ")", "outputs", "=", "tf", ".", "exp", "(", "log_alpha", ")", "return", "outputs" ]
Performs incomplete Sinkhorn normalization to inputs. By a theorem by Sinkhorn and Knopp [1], a sufficiently well-behaved matrix with positive entries can be turned into a doubly-stochastic matrix (i.e. its rows and columns add up to one) via the succesive row and column normalization. -To ensure positivity, the effective input to sinkhorn has to be exp(inputs) (elementwise). -However, for stability, sinkhorn works in the log-space. It is only at return time that entries are exponentiated. Code is adapted from Mena et al. [2]. [1] Richard Sinkhorn and Paul Knopp. Concerning nonnegative matrices and doubly stochastic matrices. Pacific Journal of Mathematics, 1967. [2] Gonzalo Mena, David Belanger, Scott Linderman, Jasper Snoek. Learning latent permutations with Gumbel-Sinkhorn networks. International Conference on Learning Representations, 2018. Args: inputs: A `Tensor` with shape `[..., vocab_size, vocab_size]`. n_iters: Number of sinkhorn iterations (in practice, as little as 20 iterations are needed to achieve decent convergence for `vocab_size` ~100) Returns: outputs: A `Tensor` of close-to-doubly-stochastic matrices with shape `[:, vocab_size, vocab_size]`.
[ "Performs", "incomplete", "Sinkhorn", "normalization", "to", "inputs", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/reversible_layers.py#L319-L358
22,808
tensorflow/tensor2tensor
tensor2tensor/layers/vq_discrete.py
DiscreteBottleneck.slice_hidden
def slice_hidden(self, x): """Slice encoder hidden state into block_dim. Args: x: Encoder hidden state of shape [-1, hidden_size]. Returns: Sliced states of shape [-1, num_blocks, block_dim]. """ x_sliced = tf.reshape( x, shape=[-1, self.hparams.num_blocks, self.hparams.block_dim]) return x_sliced
python
def slice_hidden(self, x): """Slice encoder hidden state into block_dim. Args: x: Encoder hidden state of shape [-1, hidden_size]. Returns: Sliced states of shape [-1, num_blocks, block_dim]. """ x_sliced = tf.reshape( x, shape=[-1, self.hparams.num_blocks, self.hparams.block_dim]) return x_sliced
[ "def", "slice_hidden", "(", "self", ",", "x", ")", ":", "x_sliced", "=", "tf", ".", "reshape", "(", "x", ",", "shape", "=", "[", "-", "1", ",", "self", ".", "hparams", ".", "num_blocks", ",", "self", ".", "hparams", ".", "block_dim", "]", ")", "return", "x_sliced" ]
Slice encoder hidden state into block_dim. Args: x: Encoder hidden state of shape [-1, hidden_size]. Returns: Sliced states of shape [-1, num_blocks, block_dim].
[ "Slice", "encoder", "hidden", "state", "into", "block_dim", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/vq_discrete.py#L61-L72
22,809
tensorflow/tensor2tensor
tensor2tensor/layers/vq_discrete.py
DiscreteBottleneck.embedding_lookup
def embedding_lookup(self, x, means): """Compute nearest neighbors and loss for training the embeddings. Args: x: Batch of encoder continuous latent states sliced/projected into shape [-1, num_blocks, block_dim]. means: Embedding means. Returns: The nearest neighbor in one hot form, the nearest neighbor itself, the commitment loss, embedding training loss. """ x_means_hot = self.nearest_neighbor(x, means) x_means_hot_flat = tf.reshape( x_means_hot, [-1, self.hparams.num_blocks, self.hparams.block_v_size]) x_means = tf.matmul(tf.transpose(x_means_hot_flat, perm=[1, 0, 2]), means) x_means = tf.transpose(x_means, [1, 0, 2]) q_loss = tf.reduce_mean( tf.squared_difference(tf.stop_gradient(x), x_means)) e_loss = tf.reduce_mean( tf.squared_difference(x, tf.stop_gradient(x_means))) return x_means_hot, x_means, q_loss, e_loss
python
def embedding_lookup(self, x, means): """Compute nearest neighbors and loss for training the embeddings. Args: x: Batch of encoder continuous latent states sliced/projected into shape [-1, num_blocks, block_dim]. means: Embedding means. Returns: The nearest neighbor in one hot form, the nearest neighbor itself, the commitment loss, embedding training loss. """ x_means_hot = self.nearest_neighbor(x, means) x_means_hot_flat = tf.reshape( x_means_hot, [-1, self.hparams.num_blocks, self.hparams.block_v_size]) x_means = tf.matmul(tf.transpose(x_means_hot_flat, perm=[1, 0, 2]), means) x_means = tf.transpose(x_means, [1, 0, 2]) q_loss = tf.reduce_mean( tf.squared_difference(tf.stop_gradient(x), x_means)) e_loss = tf.reduce_mean( tf.squared_difference(x, tf.stop_gradient(x_means))) return x_means_hot, x_means, q_loss, e_loss
[ "def", "embedding_lookup", "(", "self", ",", "x", ",", "means", ")", ":", "x_means_hot", "=", "self", ".", "nearest_neighbor", "(", "x", ",", "means", ")", "x_means_hot_flat", "=", "tf", ".", "reshape", "(", "x_means_hot", ",", "[", "-", "1", ",", "self", ".", "hparams", ".", "num_blocks", ",", "self", ".", "hparams", ".", "block_v_size", "]", ")", "x_means", "=", "tf", ".", "matmul", "(", "tf", ".", "transpose", "(", "x_means_hot_flat", ",", "perm", "=", "[", "1", ",", "0", ",", "2", "]", ")", ",", "means", ")", "x_means", "=", "tf", ".", "transpose", "(", "x_means", ",", "[", "1", ",", "0", ",", "2", "]", ")", "q_loss", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "squared_difference", "(", "tf", ".", "stop_gradient", "(", "x", ")", ",", "x_means", ")", ")", "e_loss", "=", "tf", ".", "reduce_mean", "(", "tf", ".", "squared_difference", "(", "x", ",", "tf", ".", "stop_gradient", "(", "x_means", ")", ")", ")", "return", "x_means_hot", ",", "x_means", ",", "q_loss", ",", "e_loss" ]
Compute nearest neighbors and loss for training the embeddings. Args: x: Batch of encoder continuous latent states sliced/projected into shape [-1, num_blocks, block_dim]. means: Embedding means. Returns: The nearest neighbor in one hot form, the nearest neighbor itself, the commitment loss, embedding training loss.
[ "Compute", "nearest", "neighbors", "and", "loss", "for", "training", "the", "embeddings", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/vq_discrete.py#L122-L145
22,810
tensorflow/tensor2tensor
tensor2tensor/layers/vq_discrete.py
DiscreteBottleneck.discrete_bottleneck
def discrete_bottleneck(self, x): """Discretization bottleneck for latent variables. Args: x: Input to the discretization bottleneck. Returns: Embedding to pass to the decoder, discrete latent, loss, and the embedding function. Raises: ValueError: If projection_tensors is None for reshape_method project, or ema_count or ema_means is None if we are using ema, or unknown args. """ x_reshaped = self.slice_hidden(x) x_means_hot = [] x_means = 0 loss = 0 x_means_hot, x_means, q_loss, e_loss = self.embedding_lookup( x_reshaped, self.means) if self.hparams.ema: tf.logging.info("Using EMA with beta = {}".format(self.hparams.beta)) updated_ema_count = \ moving_averages.assign_moving_average( self.ema_count, tf.reduce_sum( tf.reshape( x_means_hot, shape=[-1, self.hparams.num_blocks, self.hparams.block_v_size]), axis=0), self.hparams.decay, zero_debias=False) dw = tf.matmul( tf.transpose(x_means_hot, perm=[1, 2, 0]), tf.transpose(x_reshaped, perm=[1, 0, 2])) updated_ema_means = \ moving_averages.assign_moving_average( self.ema_means, dw, self.hparams.decay, zero_debias=False) n = tf.reduce_sum(updated_ema_count, axis=-1, keep_dims=True) updated_ema_count = ((updated_ema_count + self.hparams.epsilon) / ( n + 2**self.hparams.z_size * self.hparams.epsilon) * n) updated_ema_means = updated_ema_means / tf.expand_dims( updated_ema_count, axis=-1) with tf.control_dependencies([e_loss]): update_means = tf.assign(self.means, updated_ema_means) with tf.control_dependencies([update_means]): loss += self.hparams.beta * e_loss else: # Use a gradient based loss for learning the cluster centers loss += q_loss + self.hparams.beta * e_loss # Get the discrete latent representation x_means_idx = tf.argmax(x_means_hot, axis=-1) # Get the binary representation num_bits = int(self.hparams.z_size // self.hparams.num_blocks) x_means_bits = self.int_to_bit(x_means_idx, num_bits=num_bits, base=2) x_discrete = self.bit_to_int( tf.to_int32(x_means_bits), num_bits=self.hparams.z_size, base=2) # Reshape x_discrete shape_x = common_layers.shape_list(x) shape_discrete = shape_x[:-1] x_discrete = tf.reshape(x_discrete, shape_discrete) x_means = tf.reshape(x_means, shape=shape_x) h1 = x + tf.stop_gradient(x_means - x) h2 = tf.layers.dense(tf.nn.relu(h1), self.hparams.filter_size, name="vch2") res = tf.layers.dense( tf.nn.relu(h2), self.hparams.hidden_size, name="vcfin") embed_fn = partial(self.embed) return { "dense": res, "discrete": x_discrete, "loss": loss, "embed": embed_fn }
python
def discrete_bottleneck(self, x): """Discretization bottleneck for latent variables. Args: x: Input to the discretization bottleneck. Returns: Embedding to pass to the decoder, discrete latent, loss, and the embedding function. Raises: ValueError: If projection_tensors is None for reshape_method project, or ema_count or ema_means is None if we are using ema, or unknown args. """ x_reshaped = self.slice_hidden(x) x_means_hot = [] x_means = 0 loss = 0 x_means_hot, x_means, q_loss, e_loss = self.embedding_lookup( x_reshaped, self.means) if self.hparams.ema: tf.logging.info("Using EMA with beta = {}".format(self.hparams.beta)) updated_ema_count = \ moving_averages.assign_moving_average( self.ema_count, tf.reduce_sum( tf.reshape( x_means_hot, shape=[-1, self.hparams.num_blocks, self.hparams.block_v_size]), axis=0), self.hparams.decay, zero_debias=False) dw = tf.matmul( tf.transpose(x_means_hot, perm=[1, 2, 0]), tf.transpose(x_reshaped, perm=[1, 0, 2])) updated_ema_means = \ moving_averages.assign_moving_average( self.ema_means, dw, self.hparams.decay, zero_debias=False) n = tf.reduce_sum(updated_ema_count, axis=-1, keep_dims=True) updated_ema_count = ((updated_ema_count + self.hparams.epsilon) / ( n + 2**self.hparams.z_size * self.hparams.epsilon) * n) updated_ema_means = updated_ema_means / tf.expand_dims( updated_ema_count, axis=-1) with tf.control_dependencies([e_loss]): update_means = tf.assign(self.means, updated_ema_means) with tf.control_dependencies([update_means]): loss += self.hparams.beta * e_loss else: # Use a gradient based loss for learning the cluster centers loss += q_loss + self.hparams.beta * e_loss # Get the discrete latent representation x_means_idx = tf.argmax(x_means_hot, axis=-1) # Get the binary representation num_bits = int(self.hparams.z_size // self.hparams.num_blocks) x_means_bits = self.int_to_bit(x_means_idx, num_bits=num_bits, base=2) x_discrete = self.bit_to_int( tf.to_int32(x_means_bits), num_bits=self.hparams.z_size, base=2) # Reshape x_discrete shape_x = common_layers.shape_list(x) shape_discrete = shape_x[:-1] x_discrete = tf.reshape(x_discrete, shape_discrete) x_means = tf.reshape(x_means, shape=shape_x) h1 = x + tf.stop_gradient(x_means - x) h2 = tf.layers.dense(tf.nn.relu(h1), self.hparams.filter_size, name="vch2") res = tf.layers.dense( tf.nn.relu(h2), self.hparams.hidden_size, name="vcfin") embed_fn = partial(self.embed) return { "dense": res, "discrete": x_discrete, "loss": loss, "embed": embed_fn }
[ "def", "discrete_bottleneck", "(", "self", ",", "x", ")", ":", "x_reshaped", "=", "self", ".", "slice_hidden", "(", "x", ")", "x_means_hot", "=", "[", "]", "x_means", "=", "0", "loss", "=", "0", "x_means_hot", ",", "x_means", ",", "q_loss", ",", "e_loss", "=", "self", ".", "embedding_lookup", "(", "x_reshaped", ",", "self", ".", "means", ")", "if", "self", ".", "hparams", ".", "ema", ":", "tf", ".", "logging", ".", "info", "(", "\"Using EMA with beta = {}\"", ".", "format", "(", "self", ".", "hparams", ".", "beta", ")", ")", "updated_ema_count", "=", "moving_averages", ".", "assign_moving_average", "(", "self", ".", "ema_count", ",", "tf", ".", "reduce_sum", "(", "tf", ".", "reshape", "(", "x_means_hot", ",", "shape", "=", "[", "-", "1", ",", "self", ".", "hparams", ".", "num_blocks", ",", "self", ".", "hparams", ".", "block_v_size", "]", ")", ",", "axis", "=", "0", ")", ",", "self", ".", "hparams", ".", "decay", ",", "zero_debias", "=", "False", ")", "dw", "=", "tf", ".", "matmul", "(", "tf", ".", "transpose", "(", "x_means_hot", ",", "perm", "=", "[", "1", ",", "2", ",", "0", "]", ")", ",", "tf", ".", "transpose", "(", "x_reshaped", ",", "perm", "=", "[", "1", ",", "0", ",", "2", "]", ")", ")", "updated_ema_means", "=", "moving_averages", ".", "assign_moving_average", "(", "self", ".", "ema_means", ",", "dw", ",", "self", ".", "hparams", ".", "decay", ",", "zero_debias", "=", "False", ")", "n", "=", "tf", ".", "reduce_sum", "(", "updated_ema_count", ",", "axis", "=", "-", "1", ",", "keep_dims", "=", "True", ")", "updated_ema_count", "=", "(", "(", "updated_ema_count", "+", "self", ".", "hparams", ".", "epsilon", ")", "/", "(", "n", "+", "2", "**", "self", ".", "hparams", ".", "z_size", "*", "self", ".", "hparams", ".", "epsilon", ")", "*", "n", ")", "updated_ema_means", "=", "updated_ema_means", "/", "tf", ".", "expand_dims", "(", "updated_ema_count", ",", "axis", "=", "-", "1", ")", "with", "tf", ".", "control_dependencies", "(", "[", "e_loss", "]", ")", ":", "update_means", "=", "tf", ".", "assign", "(", "self", ".", "means", ",", "updated_ema_means", ")", "with", "tf", ".", "control_dependencies", "(", "[", "update_means", "]", ")", ":", "loss", "+=", "self", ".", "hparams", ".", "beta", "*", "e_loss", "else", ":", "# Use a gradient based loss for learning the cluster centers", "loss", "+=", "q_loss", "+", "self", ".", "hparams", ".", "beta", "*", "e_loss", "# Get the discrete latent representation", "x_means_idx", "=", "tf", ".", "argmax", "(", "x_means_hot", ",", "axis", "=", "-", "1", ")", "# Get the binary representation", "num_bits", "=", "int", "(", "self", ".", "hparams", ".", "z_size", "//", "self", ".", "hparams", ".", "num_blocks", ")", "x_means_bits", "=", "self", ".", "int_to_bit", "(", "x_means_idx", ",", "num_bits", "=", "num_bits", ",", "base", "=", "2", ")", "x_discrete", "=", "self", ".", "bit_to_int", "(", "tf", ".", "to_int32", "(", "x_means_bits", ")", ",", "num_bits", "=", "self", ".", "hparams", ".", "z_size", ",", "base", "=", "2", ")", "# Reshape x_discrete", "shape_x", "=", "common_layers", ".", "shape_list", "(", "x", ")", "shape_discrete", "=", "shape_x", "[", ":", "-", "1", "]", "x_discrete", "=", "tf", ".", "reshape", "(", "x_discrete", ",", "shape_discrete", ")", "x_means", "=", "tf", ".", "reshape", "(", "x_means", ",", "shape", "=", "shape_x", ")", "h1", "=", "x", "+", "tf", ".", "stop_gradient", "(", "x_means", "-", "x", ")", "h2", "=", "tf", ".", "layers", ".", "dense", "(", "tf", ".", "nn", ".", "relu", "(", "h1", ")", ",", "self", ".", "hparams", ".", "filter_size", ",", "name", "=", "\"vch2\"", ")", "res", "=", "tf", ".", "layers", ".", "dense", "(", "tf", ".", "nn", ".", "relu", "(", "h2", ")", ",", "self", ".", "hparams", ".", "hidden_size", ",", "name", "=", "\"vcfin\"", ")", "embed_fn", "=", "partial", "(", "self", ".", "embed", ")", "return", "{", "\"dense\"", ":", "res", ",", "\"discrete\"", ":", "x_discrete", ",", "\"loss\"", ":", "loss", ",", "\"embed\"", ":", "embed_fn", "}" ]
Discretization bottleneck for latent variables. Args: x: Input to the discretization bottleneck. Returns: Embedding to pass to the decoder, discrete latent, loss, and the embedding function. Raises: ValueError: If projection_tensors is None for reshape_method project, or ema_count or ema_means is None if we are using ema, or unknown args.
[ "Discretization", "bottleneck", "for", "latent", "variables", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/layers/vq_discrete.py#L225-L310
22,811
tensorflow/tensor2tensor
tensor2tensor/models/research/adafactor_experiments.py
mimic_adam_with_adafactor
def mimic_adam_with_adafactor(hparams): """Switch from Adam to Adafactor, approximating the behavior of Adam. Some minor things may be different, like epsilon and beta1 correction. Args: hparams: model hyperparameters where "adam" in hparams.optimizer """ assert "adam" in hparams.optimizer hparams.optimizer = "adafactor" hparams.optimizer_adafactor_beta1 = hparams.optimizer_adam_beta1 hparams.optimizer_adafactor_beta2 = hparams.optimizer_adam_beta2 hparams.optimizer_adafactor_multiply_by_parameter_scale = False hparams.optimizer_adafactor_factored = False hparams.optimizer_adafactor_clipping_threshold = None hparams.optimizer_adafactor_decay_type = "adam"
python
def mimic_adam_with_adafactor(hparams): """Switch from Adam to Adafactor, approximating the behavior of Adam. Some minor things may be different, like epsilon and beta1 correction. Args: hparams: model hyperparameters where "adam" in hparams.optimizer """ assert "adam" in hparams.optimizer hparams.optimizer = "adafactor" hparams.optimizer_adafactor_beta1 = hparams.optimizer_adam_beta1 hparams.optimizer_adafactor_beta2 = hparams.optimizer_adam_beta2 hparams.optimizer_adafactor_multiply_by_parameter_scale = False hparams.optimizer_adafactor_factored = False hparams.optimizer_adafactor_clipping_threshold = None hparams.optimizer_adafactor_decay_type = "adam"
[ "def", "mimic_adam_with_adafactor", "(", "hparams", ")", ":", "assert", "\"adam\"", "in", "hparams", ".", "optimizer", "hparams", ".", "optimizer", "=", "\"adafactor\"", "hparams", ".", "optimizer_adafactor_beta1", "=", "hparams", ".", "optimizer_adam_beta1", "hparams", ".", "optimizer_adafactor_beta2", "=", "hparams", ".", "optimizer_adam_beta2", "hparams", ".", "optimizer_adafactor_multiply_by_parameter_scale", "=", "False", "hparams", ".", "optimizer_adafactor_factored", "=", "False", "hparams", ".", "optimizer_adafactor_clipping_threshold", "=", "None", "hparams", ".", "optimizer_adafactor_decay_type", "=", "\"adam\"" ]
Switch from Adam to Adafactor, approximating the behavior of Adam. Some minor things may be different, like epsilon and beta1 correction. Args: hparams: model hyperparameters where "adam" in hparams.optimizer
[ "Switch", "from", "Adam", "to", "Adafactor", "approximating", "the", "behavior", "of", "Adam", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/adafactor_experiments.py#L27-L42
22,812
tensorflow/tensor2tensor
tensor2tensor/models/research/adafactor_experiments.py
afx_adam
def afx_adam(): """Old version - Adam.""" hparams = transformer.transformer_base_v2() hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.999 hparams.symbol_modality_num_shards = 1 hparams.batch_size = 2048 hparams.optimizer = "adam" hparams.learning_rate_schedule = ( "constant*rsqrt_decay*linear_warmup*rsqrt_hidden_size") hparams.learning_rate_constant = 2.0 return hparams
python
def afx_adam(): """Old version - Adam.""" hparams = transformer.transformer_base_v2() hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.999 hparams.symbol_modality_num_shards = 1 hparams.batch_size = 2048 hparams.optimizer = "adam" hparams.learning_rate_schedule = ( "constant*rsqrt_decay*linear_warmup*rsqrt_hidden_size") hparams.learning_rate_constant = 2.0 return hparams
[ "def", "afx_adam", "(", ")", ":", "hparams", "=", "transformer", ".", "transformer_base_v2", "(", ")", "hparams", ".", "optimizer_adam_beta1", "=", "0.9", "hparams", ".", "optimizer_adam_beta2", "=", "0.999", "hparams", ".", "symbol_modality_num_shards", "=", "1", "hparams", ".", "batch_size", "=", "2048", "hparams", ".", "optimizer", "=", "\"adam\"", "hparams", ".", "learning_rate_schedule", "=", "(", "\"constant*rsqrt_decay*linear_warmup*rsqrt_hidden_size\"", ")", "hparams", ".", "learning_rate_constant", "=", "2.0", "return", "hparams" ]
Old version - Adam.
[ "Old", "version", "-", "Adam", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/adafactor_experiments.py#L46-L57
22,813
tensorflow/tensor2tensor
tensor2tensor/models/research/adafactor_experiments.py
afx_adafactor
def afx_adafactor(): """Adafactor with recommended learning rate schedule.""" hparams = afx_adam() hparams.optimizer = "Adafactor" hparams.learning_rate_schedule = "rsqrt_decay" hparams.learning_rate_warmup_steps = 10000 return hparams
python
def afx_adafactor(): """Adafactor with recommended learning rate schedule.""" hparams = afx_adam() hparams.optimizer = "Adafactor" hparams.learning_rate_schedule = "rsqrt_decay" hparams.learning_rate_warmup_steps = 10000 return hparams
[ "def", "afx_adafactor", "(", ")", ":", "hparams", "=", "afx_adam", "(", ")", "hparams", ".", "optimizer", "=", "\"Adafactor\"", "hparams", ".", "learning_rate_schedule", "=", "\"rsqrt_decay\"", "hparams", ".", "learning_rate_warmup_steps", "=", "10000", "return", "hparams" ]
Adafactor with recommended learning rate schedule.
[ "Adafactor", "with", "recommended", "learning", "rate", "schedule", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/adafactor_experiments.py#L167-L173
22,814
tensorflow/tensor2tensor
tensor2tensor/models/research/adafactor_experiments.py
afx_small
def afx_small(): """Small transformer model with small batch size for fast step times.""" hparams = transformer.transformer_tpu() hparams.filter_size = 1024 hparams.num_heads = 4 hparams.num_hidden_layers = 3 hparams.batch_size = 512 return hparams
python
def afx_small(): """Small transformer model with small batch size for fast step times.""" hparams = transformer.transformer_tpu() hparams.filter_size = 1024 hparams.num_heads = 4 hparams.num_hidden_layers = 3 hparams.batch_size = 512 return hparams
[ "def", "afx_small", "(", ")", ":", "hparams", "=", "transformer", ".", "transformer_tpu", "(", ")", "hparams", ".", "filter_size", "=", "1024", "hparams", ".", "num_heads", "=", "4", "hparams", ".", "num_hidden_layers", "=", "3", "hparams", ".", "batch_size", "=", "512", "return", "hparams" ]
Small transformer model with small batch size for fast step times.
[ "Small", "transformer", "model", "with", "small", "batch", "size", "for", "fast", "step", "times", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/adafactor_experiments.py#L177-L184
22,815
tensorflow/tensor2tensor
tensor2tensor/models/video/emily.py
next_frame_emily
def next_frame_emily(): """Emily's model hparams.""" hparams = sv2p_params.next_frame_sv2p() hparams.video_num_input_frames = 2 hparams.video_num_target_frames = 10 hparams.learning_rate_constant = 1e-4 seq_length = hparams.video_num_input_frames + hparams.video_num_target_frames # The latent_loss_multiplier is divided by the number of frames because # the image sequence loss in t2t is averaged instead of added through # time as they do in the SVG-LP paper hparams.latent_loss_multiplier = 1e-4 / seq_length hparams.reward_prediction = False hparams.num_iterations_1st_stage = -1 hparams.num_iterations_2nd_stage = -1 hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.999 hparams.optimizer_adam_epsilon = 1e-08 hparams.anneal_end = -1 hparams.clip_grad_norm = 5.0 hparams.add_hparam("learned_prior", True) hparams.add_hparam("z_dim", 64) hparams.add_hparam("g_dim", 128) hparams.add_hparam("rnn_size", 256) hparams.add_hparam("prior_rnn_layers", 1) hparams.add_hparam("posterior_rnn_layers", 1) hparams.add_hparam("predictor_rnn_layers", 2) hparams.add_hparam("has_skips", True) hparams.add_hparam("has_batchnorm", True) return hparams
python
def next_frame_emily(): """Emily's model hparams.""" hparams = sv2p_params.next_frame_sv2p() hparams.video_num_input_frames = 2 hparams.video_num_target_frames = 10 hparams.learning_rate_constant = 1e-4 seq_length = hparams.video_num_input_frames + hparams.video_num_target_frames # The latent_loss_multiplier is divided by the number of frames because # the image sequence loss in t2t is averaged instead of added through # time as they do in the SVG-LP paper hparams.latent_loss_multiplier = 1e-4 / seq_length hparams.reward_prediction = False hparams.num_iterations_1st_stage = -1 hparams.num_iterations_2nd_stage = -1 hparams.optimizer_adam_beta1 = 0.9 hparams.optimizer_adam_beta2 = 0.999 hparams.optimizer_adam_epsilon = 1e-08 hparams.anneal_end = -1 hparams.clip_grad_norm = 5.0 hparams.add_hparam("learned_prior", True) hparams.add_hparam("z_dim", 64) hparams.add_hparam("g_dim", 128) hparams.add_hparam("rnn_size", 256) hparams.add_hparam("prior_rnn_layers", 1) hparams.add_hparam("posterior_rnn_layers", 1) hparams.add_hparam("predictor_rnn_layers", 2) hparams.add_hparam("has_skips", True) hparams.add_hparam("has_batchnorm", True) return hparams
[ "def", "next_frame_emily", "(", ")", ":", "hparams", "=", "sv2p_params", ".", "next_frame_sv2p", "(", ")", "hparams", ".", "video_num_input_frames", "=", "2", "hparams", ".", "video_num_target_frames", "=", "10", "hparams", ".", "learning_rate_constant", "=", "1e-4", "seq_length", "=", "hparams", ".", "video_num_input_frames", "+", "hparams", ".", "video_num_target_frames", "# The latent_loss_multiplier is divided by the number of frames because", "# the image sequence loss in t2t is averaged instead of added through", "# time as they do in the SVG-LP paper", "hparams", ".", "latent_loss_multiplier", "=", "1e-4", "/", "seq_length", "hparams", ".", "reward_prediction", "=", "False", "hparams", ".", "num_iterations_1st_stage", "=", "-", "1", "hparams", ".", "num_iterations_2nd_stage", "=", "-", "1", "hparams", ".", "optimizer_adam_beta1", "=", "0.9", "hparams", ".", "optimizer_adam_beta2", "=", "0.999", "hparams", ".", "optimizer_adam_epsilon", "=", "1e-08", "hparams", ".", "anneal_end", "=", "-", "1", "hparams", ".", "clip_grad_norm", "=", "5.0", "hparams", ".", "add_hparam", "(", "\"learned_prior\"", ",", "True", ")", "hparams", ".", "add_hparam", "(", "\"z_dim\"", ",", "64", ")", "hparams", ".", "add_hparam", "(", "\"g_dim\"", ",", "128", ")", "hparams", ".", "add_hparam", "(", "\"rnn_size\"", ",", "256", ")", "hparams", ".", "add_hparam", "(", "\"prior_rnn_layers\"", ",", "1", ")", "hparams", ".", "add_hparam", "(", "\"posterior_rnn_layers\"", ",", "1", ")", "hparams", ".", "add_hparam", "(", "\"predictor_rnn_layers\"", ",", "2", ")", "hparams", ".", "add_hparam", "(", "\"has_skips\"", ",", "True", ")", "hparams", ".", "add_hparam", "(", "\"has_batchnorm\"", ",", "True", ")", "return", "hparams" ]
Emily's model hparams.
[ "Emily", "s", "model", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/emily.py#L447-L475
22,816
tensorflow/tensor2tensor
tensor2tensor/data_generators/inspect_tfrecord.py
main
def main(_): """Convert a file to examples.""" if FLAGS.subword_text_encoder_filename: encoder = text_encoder.SubwordTextEncoder( FLAGS.subword_text_encoder_filename) elif FLAGS.token_text_encoder_filename: encoder = text_encoder.TokenTextEncoder(FLAGS.token_text_encoder_filename) elif FLAGS.byte_text_encoder: encoder = text_encoder.ByteTextEncoder() else: encoder = None reader = tf.python_io.tf_record_iterator(FLAGS.input_filename) total_sequences = 0 total_input_tokens = 0 total_target_tokens = 0 nonpadding_input_tokens = 0 nonpadding_target_tokens = 0 max_input_length = 0 max_target_length = 0 for record in reader: x = tf.train.Example() x.ParseFromString(record) inputs = [int(i) for i in x.features.feature["inputs"].int64_list.value] targets = [int(i) for i in x.features.feature["targets"].int64_list.value] if FLAGS.print_inputs: print("INPUTS:\n" + encoder.decode(inputs) if encoder else inputs) if FLAGS.print_targets: print("TARGETS:\n" + encoder.decode(targets) if encoder else targets) nonpadding_input_tokens += len(inputs) - inputs.count(0) nonpadding_target_tokens += len(targets) - targets.count(0) total_input_tokens += len(inputs) total_target_tokens += len(targets) total_sequences += 1 max_input_length = max(max_input_length, len(inputs)) max_target_length = max(max_target_length, len(targets)) if FLAGS.print_all: for k, v in six.iteritems(x.features.feature): print("%s: %s" % (k, v.int64_list.value)) print("total_sequences: %d" % total_sequences) print("total_input_tokens: %d" % total_input_tokens) print("total_target_tokens: %d" % total_target_tokens) print("nonpadding_input_tokens: %d" % nonpadding_input_tokens) print("nonpadding_target_tokens: %d" % nonpadding_target_tokens) print("max_input_length: %d" % max_input_length) print("max_target_length: %d" % max_target_length)
python
def main(_): """Convert a file to examples.""" if FLAGS.subword_text_encoder_filename: encoder = text_encoder.SubwordTextEncoder( FLAGS.subword_text_encoder_filename) elif FLAGS.token_text_encoder_filename: encoder = text_encoder.TokenTextEncoder(FLAGS.token_text_encoder_filename) elif FLAGS.byte_text_encoder: encoder = text_encoder.ByteTextEncoder() else: encoder = None reader = tf.python_io.tf_record_iterator(FLAGS.input_filename) total_sequences = 0 total_input_tokens = 0 total_target_tokens = 0 nonpadding_input_tokens = 0 nonpadding_target_tokens = 0 max_input_length = 0 max_target_length = 0 for record in reader: x = tf.train.Example() x.ParseFromString(record) inputs = [int(i) for i in x.features.feature["inputs"].int64_list.value] targets = [int(i) for i in x.features.feature["targets"].int64_list.value] if FLAGS.print_inputs: print("INPUTS:\n" + encoder.decode(inputs) if encoder else inputs) if FLAGS.print_targets: print("TARGETS:\n" + encoder.decode(targets) if encoder else targets) nonpadding_input_tokens += len(inputs) - inputs.count(0) nonpadding_target_tokens += len(targets) - targets.count(0) total_input_tokens += len(inputs) total_target_tokens += len(targets) total_sequences += 1 max_input_length = max(max_input_length, len(inputs)) max_target_length = max(max_target_length, len(targets)) if FLAGS.print_all: for k, v in six.iteritems(x.features.feature): print("%s: %s" % (k, v.int64_list.value)) print("total_sequences: %d" % total_sequences) print("total_input_tokens: %d" % total_input_tokens) print("total_target_tokens: %d" % total_target_tokens) print("nonpadding_input_tokens: %d" % nonpadding_input_tokens) print("nonpadding_target_tokens: %d" % nonpadding_target_tokens) print("max_input_length: %d" % max_input_length) print("max_target_length: %d" % max_target_length)
[ "def", "main", "(", "_", ")", ":", "if", "FLAGS", ".", "subword_text_encoder_filename", ":", "encoder", "=", "text_encoder", ".", "SubwordTextEncoder", "(", "FLAGS", ".", "subword_text_encoder_filename", ")", "elif", "FLAGS", ".", "token_text_encoder_filename", ":", "encoder", "=", "text_encoder", ".", "TokenTextEncoder", "(", "FLAGS", ".", "token_text_encoder_filename", ")", "elif", "FLAGS", ".", "byte_text_encoder", ":", "encoder", "=", "text_encoder", ".", "ByteTextEncoder", "(", ")", "else", ":", "encoder", "=", "None", "reader", "=", "tf", ".", "python_io", ".", "tf_record_iterator", "(", "FLAGS", ".", "input_filename", ")", "total_sequences", "=", "0", "total_input_tokens", "=", "0", "total_target_tokens", "=", "0", "nonpadding_input_tokens", "=", "0", "nonpadding_target_tokens", "=", "0", "max_input_length", "=", "0", "max_target_length", "=", "0", "for", "record", "in", "reader", ":", "x", "=", "tf", ".", "train", ".", "Example", "(", ")", "x", ".", "ParseFromString", "(", "record", ")", "inputs", "=", "[", "int", "(", "i", ")", "for", "i", "in", "x", ".", "features", ".", "feature", "[", "\"inputs\"", "]", ".", "int64_list", ".", "value", "]", "targets", "=", "[", "int", "(", "i", ")", "for", "i", "in", "x", ".", "features", ".", "feature", "[", "\"targets\"", "]", ".", "int64_list", ".", "value", "]", "if", "FLAGS", ".", "print_inputs", ":", "print", "(", "\"INPUTS:\\n\"", "+", "encoder", ".", "decode", "(", "inputs", ")", "if", "encoder", "else", "inputs", ")", "if", "FLAGS", ".", "print_targets", ":", "print", "(", "\"TARGETS:\\n\"", "+", "encoder", ".", "decode", "(", "targets", ")", "if", "encoder", "else", "targets", ")", "nonpadding_input_tokens", "+=", "len", "(", "inputs", ")", "-", "inputs", ".", "count", "(", "0", ")", "nonpadding_target_tokens", "+=", "len", "(", "targets", ")", "-", "targets", ".", "count", "(", "0", ")", "total_input_tokens", "+=", "len", "(", "inputs", ")", "total_target_tokens", "+=", "len", "(", "targets", ")", "total_sequences", "+=", "1", "max_input_length", "=", "max", "(", "max_input_length", ",", "len", "(", "inputs", ")", ")", "max_target_length", "=", "max", "(", "max_target_length", ",", "len", "(", "targets", ")", ")", "if", "FLAGS", ".", "print_all", ":", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "x", ".", "features", ".", "feature", ")", ":", "print", "(", "\"%s: %s\"", "%", "(", "k", ",", "v", ".", "int64_list", ".", "value", ")", ")", "print", "(", "\"total_sequences: %d\"", "%", "total_sequences", ")", "print", "(", "\"total_input_tokens: %d\"", "%", "total_input_tokens", ")", "print", "(", "\"total_target_tokens: %d\"", "%", "total_target_tokens", ")", "print", "(", "\"nonpadding_input_tokens: %d\"", "%", "nonpadding_input_tokens", ")", "print", "(", "\"nonpadding_target_tokens: %d\"", "%", "nonpadding_target_tokens", ")", "print", "(", "\"max_input_length: %d\"", "%", "max_input_length", ")", "print", "(", "\"max_target_length: %d\"", "%", "max_target_length", ")" ]
Convert a file to examples.
[ "Convert", "a", "file", "to", "examples", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/inspect_tfrecord.py#L48-L93
22,817
tensorflow/tensor2tensor
tensor2tensor/envs/rendered_env_problem.py
RenderedEnvProblem.example_reading_spec
def example_reading_spec(self): """Return a mix of env and video data fields and decoders.""" video_fields, video_decoders = ( video_utils.VideoProblem.example_reading_spec(self)) env_fields, env_decoders = env_problem.EnvProblem.example_reading_spec(self) # Remove raw observations field since we want to capture them as videos. env_fields.pop(env_problem.OBSERVATION_FIELD) env_decoders.pop(env_problem.OBSERVATION_FIELD) # Add frame number spec and decoder. env_fields[_FRAME_NUMBER_FIELD] = tf.FixedLenFeature((1,), tf.int64) env_decoders[ _FRAME_NUMBER_FIELD] = tf.contrib.slim.tfexample_decoder.Tensor( _FRAME_NUMBER_FIELD) # Add video fields and decoders env_fields.update(video_fields) env_decoders.update(video_decoders) return env_fields, env_decoders
python
def example_reading_spec(self): """Return a mix of env and video data fields and decoders.""" video_fields, video_decoders = ( video_utils.VideoProblem.example_reading_spec(self)) env_fields, env_decoders = env_problem.EnvProblem.example_reading_spec(self) # Remove raw observations field since we want to capture them as videos. env_fields.pop(env_problem.OBSERVATION_FIELD) env_decoders.pop(env_problem.OBSERVATION_FIELD) # Add frame number spec and decoder. env_fields[_FRAME_NUMBER_FIELD] = tf.FixedLenFeature((1,), tf.int64) env_decoders[ _FRAME_NUMBER_FIELD] = tf.contrib.slim.tfexample_decoder.Tensor( _FRAME_NUMBER_FIELD) # Add video fields and decoders env_fields.update(video_fields) env_decoders.update(video_decoders) return env_fields, env_decoders
[ "def", "example_reading_spec", "(", "self", ")", ":", "video_fields", ",", "video_decoders", "=", "(", "video_utils", ".", "VideoProblem", ".", "example_reading_spec", "(", "self", ")", ")", "env_fields", ",", "env_decoders", "=", "env_problem", ".", "EnvProblem", ".", "example_reading_spec", "(", "self", ")", "# Remove raw observations field since we want to capture them as videos.", "env_fields", ".", "pop", "(", "env_problem", ".", "OBSERVATION_FIELD", ")", "env_decoders", ".", "pop", "(", "env_problem", ".", "OBSERVATION_FIELD", ")", "# Add frame number spec and decoder.", "env_fields", "[", "_FRAME_NUMBER_FIELD", "]", "=", "tf", ".", "FixedLenFeature", "(", "(", "1", ",", ")", ",", "tf", ".", "int64", ")", "env_decoders", "[", "_FRAME_NUMBER_FIELD", "]", "=", "tf", ".", "contrib", ".", "slim", ".", "tfexample_decoder", ".", "Tensor", "(", "_FRAME_NUMBER_FIELD", ")", "# Add video fields and decoders", "env_fields", ".", "update", "(", "video_fields", ")", "env_decoders", ".", "update", "(", "video_decoders", ")", "return", "env_fields", ",", "env_decoders" ]
Return a mix of env and video data fields and decoders.
[ "Return", "a", "mix", "of", "env", "and", "video", "data", "fields", "and", "decoders", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/rendered_env_problem.py#L66-L85
22,818
tensorflow/tensor2tensor
tensor2tensor/envs/rendered_env_problem.py
RenderedEnvProblem._generate_time_steps
def _generate_time_steps(self, trajectory_list): """Transforms time step observations to frames of a video.""" for time_step in env_problem.EnvProblem._generate_time_steps( self, trajectory_list): # Convert the rendered observations from numpy to png format. frame_np = np.array(time_step.pop(env_problem.OBSERVATION_FIELD)) frame_np = frame_np.reshape( [self.frame_height, self.frame_width, self.num_channels]) # TODO(msaffar) Add support for non RGB rendered environments frame = png.from_array(frame_np, "RGB", info={"bitdepth": 8}) frame_buffer = six.BytesIO() frame.save(frame_buffer) # Put the encoded frame back. time_step[_IMAGE_ENCODED_FIELD] = [frame_buffer.getvalue()] time_step[_IMAGE_FORMAT_FIELD] = [_FORMAT] time_step[_IMAGE_HEIGHT_FIELD] = [self.frame_height] time_step[_IMAGE_WIDTH_FIELD] = [self.frame_width] # Add the frame number time_step[_FRAME_NUMBER_FIELD] = time_step[env_problem.TIMESTEP_FIELD] yield time_step
python
def _generate_time_steps(self, trajectory_list): """Transforms time step observations to frames of a video.""" for time_step in env_problem.EnvProblem._generate_time_steps( self, trajectory_list): # Convert the rendered observations from numpy to png format. frame_np = np.array(time_step.pop(env_problem.OBSERVATION_FIELD)) frame_np = frame_np.reshape( [self.frame_height, self.frame_width, self.num_channels]) # TODO(msaffar) Add support for non RGB rendered environments frame = png.from_array(frame_np, "RGB", info={"bitdepth": 8}) frame_buffer = six.BytesIO() frame.save(frame_buffer) # Put the encoded frame back. time_step[_IMAGE_ENCODED_FIELD] = [frame_buffer.getvalue()] time_step[_IMAGE_FORMAT_FIELD] = [_FORMAT] time_step[_IMAGE_HEIGHT_FIELD] = [self.frame_height] time_step[_IMAGE_WIDTH_FIELD] = [self.frame_width] # Add the frame number time_step[_FRAME_NUMBER_FIELD] = time_step[env_problem.TIMESTEP_FIELD] yield time_step
[ "def", "_generate_time_steps", "(", "self", ",", "trajectory_list", ")", ":", "for", "time_step", "in", "env_problem", ".", "EnvProblem", ".", "_generate_time_steps", "(", "self", ",", "trajectory_list", ")", ":", "# Convert the rendered observations from numpy to png format.", "frame_np", "=", "np", ".", "array", "(", "time_step", ".", "pop", "(", "env_problem", ".", "OBSERVATION_FIELD", ")", ")", "frame_np", "=", "frame_np", ".", "reshape", "(", "[", "self", ".", "frame_height", ",", "self", ".", "frame_width", ",", "self", ".", "num_channels", "]", ")", "# TODO(msaffar) Add support for non RGB rendered environments", "frame", "=", "png", ".", "from_array", "(", "frame_np", ",", "\"RGB\"", ",", "info", "=", "{", "\"bitdepth\"", ":", "8", "}", ")", "frame_buffer", "=", "six", ".", "BytesIO", "(", ")", "frame", ".", "save", "(", "frame_buffer", ")", "# Put the encoded frame back.", "time_step", "[", "_IMAGE_ENCODED_FIELD", "]", "=", "[", "frame_buffer", ".", "getvalue", "(", ")", "]", "time_step", "[", "_IMAGE_FORMAT_FIELD", "]", "=", "[", "_FORMAT", "]", "time_step", "[", "_IMAGE_HEIGHT_FIELD", "]", "=", "[", "self", ".", "frame_height", "]", "time_step", "[", "_IMAGE_WIDTH_FIELD", "]", "=", "[", "self", ".", "frame_width", "]", "# Add the frame number", "time_step", "[", "_FRAME_NUMBER_FIELD", "]", "=", "time_step", "[", "env_problem", ".", "TIMESTEP_FIELD", "]", "yield", "time_step" ]
Transforms time step observations to frames of a video.
[ "Transforms", "time", "step", "observations", "to", "frames", "of", "a", "video", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/envs/rendered_env_problem.py#L87-L108
22,819
tensorflow/tensor2tensor
tensor2tensor/data_generators/text_problems.py
text2class_txt_iterator
def text2class_txt_iterator(source_txt_path, label_txt_path, class_strs=None): """Yield dicts for Text2ClassProblem.generate_samples from lines of files. Args: source_txt_path: txt file with record per line. label_txt_path: txt file with label per line, either as int or str. If string, must provide class_strs. class_strs: list<str> of class label names. Must be in correct order (i.e. ["a", "b", "c"] means that "a" will get class ID 0, "b" ID 1, etc.). Yields: {"inputs": inputs, "label": label} """ if class_strs: class_strs = dict([(s, i) for i, s in enumerate(class_strs)]) for inputs, label in zip( txt_line_iterator(source_txt_path), txt_line_iterator(label_txt_path)): label = label.strip() if class_strs: label = class_strs[label] else: label = int(label) yield {"inputs": inputs, "label": label}
python
def text2class_txt_iterator(source_txt_path, label_txt_path, class_strs=None): """Yield dicts for Text2ClassProblem.generate_samples from lines of files. Args: source_txt_path: txt file with record per line. label_txt_path: txt file with label per line, either as int or str. If string, must provide class_strs. class_strs: list<str> of class label names. Must be in correct order (i.e. ["a", "b", "c"] means that "a" will get class ID 0, "b" ID 1, etc.). Yields: {"inputs": inputs, "label": label} """ if class_strs: class_strs = dict([(s, i) for i, s in enumerate(class_strs)]) for inputs, label in zip( txt_line_iterator(source_txt_path), txt_line_iterator(label_txt_path)): label = label.strip() if class_strs: label = class_strs[label] else: label = int(label) yield {"inputs": inputs, "label": label}
[ "def", "text2class_txt_iterator", "(", "source_txt_path", ",", "label_txt_path", ",", "class_strs", "=", "None", ")", ":", "if", "class_strs", ":", "class_strs", "=", "dict", "(", "[", "(", "s", ",", "i", ")", "for", "i", ",", "s", "in", "enumerate", "(", "class_strs", ")", "]", ")", "for", "inputs", ",", "label", "in", "zip", "(", "txt_line_iterator", "(", "source_txt_path", ")", ",", "txt_line_iterator", "(", "label_txt_path", ")", ")", ":", "label", "=", "label", ".", "strip", "(", ")", "if", "class_strs", ":", "label", "=", "class_strs", "[", "label", "]", "else", ":", "label", "=", "int", "(", "label", ")", "yield", "{", "\"inputs\"", ":", "inputs", ",", "\"label\"", ":", "label", "}" ]
Yield dicts for Text2ClassProblem.generate_samples from lines of files. Args: source_txt_path: txt file with record per line. label_txt_path: txt file with label per line, either as int or str. If string, must provide class_strs. class_strs: list<str> of class label names. Must be in correct order (i.e. ["a", "b", "c"] means that "a" will get class ID 0, "b" ID 1, etc.). Yields: {"inputs": inputs, "label": label}
[ "Yield", "dicts", "for", "Text2ClassProblem", ".", "generate_samples", "from", "lines", "of", "files", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_problems.py#L635-L657
22,820
tensorflow/tensor2tensor
tensor2tensor/data_generators/text_problems.py
text2text_txt_tab_iterator
def text2text_txt_tab_iterator(txt_path): """Yield dicts for Text2TextProblem.generate_samples from lines of txt_path. Args: txt_path: path to txt file with a record per line, source and target are tab-separated. Yields: {"inputs": inputs, "targets": targets} """ for line in txt_line_iterator(txt_path): if line and "\t" in line: parts = line.split("\t", 1) inputs, targets = parts[:2] yield {"inputs": inputs.strip(), "targets": targets.strip()}
python
def text2text_txt_tab_iterator(txt_path): """Yield dicts for Text2TextProblem.generate_samples from lines of txt_path. Args: txt_path: path to txt file with a record per line, source and target are tab-separated. Yields: {"inputs": inputs, "targets": targets} """ for line in txt_line_iterator(txt_path): if line and "\t" in line: parts = line.split("\t", 1) inputs, targets = parts[:2] yield {"inputs": inputs.strip(), "targets": targets.strip()}
[ "def", "text2text_txt_tab_iterator", "(", "txt_path", ")", ":", "for", "line", "in", "txt_line_iterator", "(", "txt_path", ")", ":", "if", "line", "and", "\"\\t\"", "in", "line", ":", "parts", "=", "line", ".", "split", "(", "\"\\t\"", ",", "1", ")", "inputs", ",", "targets", "=", "parts", "[", ":", "2", "]", "yield", "{", "\"inputs\"", ":", "inputs", ".", "strip", "(", ")", ",", "\"targets\"", ":", "targets", ".", "strip", "(", ")", "}" ]
Yield dicts for Text2TextProblem.generate_samples from lines of txt_path. Args: txt_path: path to txt file with a record per line, source and target are tab-separated. Yields: {"inputs": inputs, "targets": targets}
[ "Yield", "dicts", "for", "Text2TextProblem", ".", "generate_samples", "from", "lines", "of", "txt_path", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_problems.py#L660-L674
22,821
tensorflow/tensor2tensor
tensor2tensor/data_generators/text_problems.py
text2text_generate_encoded
def text2text_generate_encoded(sample_generator, vocab, targets_vocab=None, has_inputs=True, inputs_prefix="", targets_prefix=""): """Encode Text2Text samples from the generator with the vocab.""" targets_vocab = targets_vocab or vocab for sample in sample_generator: if has_inputs: sample["inputs"] = vocab.encode(inputs_prefix + sample["inputs"]) sample["inputs"].append(text_encoder.EOS_ID) sample["targets"] = targets_vocab.encode(targets_prefix + sample["targets"]) sample["targets"].append(text_encoder.EOS_ID) yield sample
python
def text2text_generate_encoded(sample_generator, vocab, targets_vocab=None, has_inputs=True, inputs_prefix="", targets_prefix=""): """Encode Text2Text samples from the generator with the vocab.""" targets_vocab = targets_vocab or vocab for sample in sample_generator: if has_inputs: sample["inputs"] = vocab.encode(inputs_prefix + sample["inputs"]) sample["inputs"].append(text_encoder.EOS_ID) sample["targets"] = targets_vocab.encode(targets_prefix + sample["targets"]) sample["targets"].append(text_encoder.EOS_ID) yield sample
[ "def", "text2text_generate_encoded", "(", "sample_generator", ",", "vocab", ",", "targets_vocab", "=", "None", ",", "has_inputs", "=", "True", ",", "inputs_prefix", "=", "\"\"", ",", "targets_prefix", "=", "\"\"", ")", ":", "targets_vocab", "=", "targets_vocab", "or", "vocab", "for", "sample", "in", "sample_generator", ":", "if", "has_inputs", ":", "sample", "[", "\"inputs\"", "]", "=", "vocab", ".", "encode", "(", "inputs_prefix", "+", "sample", "[", "\"inputs\"", "]", ")", "sample", "[", "\"inputs\"", "]", ".", "append", "(", "text_encoder", ".", "EOS_ID", ")", "sample", "[", "\"targets\"", "]", "=", "targets_vocab", ".", "encode", "(", "targets_prefix", "+", "sample", "[", "\"targets\"", "]", ")", "sample", "[", "\"targets\"", "]", ".", "append", "(", "text_encoder", ".", "EOS_ID", ")", "yield", "sample" ]
Encode Text2Text samples from the generator with the vocab.
[ "Encode", "Text2Text", "samples", "from", "the", "generator", "with", "the", "vocab", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_problems.py#L677-L691
22,822
tensorflow/tensor2tensor
tensor2tensor/data_generators/text_problems.py
Text2TextProblem._pack_fn
def _pack_fn(self): """For packed datasets, returns a function to pack examples. Returns: None or a function from list of TFRecords to list of TFRecords """ if not self.packed_length: return None def my_fn(records): """Function from list of TFRecords to list of TFRecords.""" examples = [] for record in records: x = tf.train.Example() x.ParseFromString(record) example_dict = {} if self.has_inputs: example_dict["inputs"] = [ int(i) for i in x.features.feature["inputs"].int64_list.value] example_dict["targets"] = [ int(i) for i in x.features.feature["targets"].int64_list.value] examples.append(example_dict) examples = list(self._maybe_pack_examples(examples)) return [ generator_utils.to_example(x).SerializeToString() for x in examples] return my_fn
python
def _pack_fn(self): """For packed datasets, returns a function to pack examples. Returns: None or a function from list of TFRecords to list of TFRecords """ if not self.packed_length: return None def my_fn(records): """Function from list of TFRecords to list of TFRecords.""" examples = [] for record in records: x = tf.train.Example() x.ParseFromString(record) example_dict = {} if self.has_inputs: example_dict["inputs"] = [ int(i) for i in x.features.feature["inputs"].int64_list.value] example_dict["targets"] = [ int(i) for i in x.features.feature["targets"].int64_list.value] examples.append(example_dict) examples = list(self._maybe_pack_examples(examples)) return [ generator_utils.to_example(x).SerializeToString() for x in examples] return my_fn
[ "def", "_pack_fn", "(", "self", ")", ":", "if", "not", "self", ".", "packed_length", ":", "return", "None", "def", "my_fn", "(", "records", ")", ":", "\"\"\"Function from list of TFRecords to list of TFRecords.\"\"\"", "examples", "=", "[", "]", "for", "record", "in", "records", ":", "x", "=", "tf", ".", "train", ".", "Example", "(", ")", "x", ".", "ParseFromString", "(", "record", ")", "example_dict", "=", "{", "}", "if", "self", ".", "has_inputs", ":", "example_dict", "[", "\"inputs\"", "]", "=", "[", "int", "(", "i", ")", "for", "i", "in", "x", ".", "features", ".", "feature", "[", "\"inputs\"", "]", ".", "int64_list", ".", "value", "]", "example_dict", "[", "\"targets\"", "]", "=", "[", "int", "(", "i", ")", "for", "i", "in", "x", ".", "features", ".", "feature", "[", "\"targets\"", "]", ".", "int64_list", ".", "value", "]", "examples", ".", "append", "(", "example_dict", ")", "examples", "=", "list", "(", "self", ".", "_maybe_pack_examples", "(", "examples", ")", ")", "return", "[", "generator_utils", ".", "to_example", "(", "x", ")", ".", "SerializeToString", "(", ")", "for", "x", "in", "examples", "]", "return", "my_fn" ]
For packed datasets, returns a function to pack examples. Returns: None or a function from list of TFRecords to list of TFRecords
[ "For", "packed", "datasets", "returns", "a", "function", "to", "pack", "examples", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_problems.py#L263-L287
22,823
tensorflow/tensor2tensor
tensor2tensor/data_generators/text_problems.py
Text2TextProblem._maybe_pack_examples
def _maybe_pack_examples(self, generator): """Wraps generator with packer if self.packed_length.""" if not self.packed_length: return generator return generator_utils.pack_examples( generator, self.has_inputs, self.packed_length, spacing=self.packed_spacing, chop_long_sequences=not self.has_inputs)
python
def _maybe_pack_examples(self, generator): """Wraps generator with packer if self.packed_length.""" if not self.packed_length: return generator return generator_utils.pack_examples( generator, self.has_inputs, self.packed_length, spacing=self.packed_spacing, chop_long_sequences=not self.has_inputs)
[ "def", "_maybe_pack_examples", "(", "self", ",", "generator", ")", ":", "if", "not", "self", ".", "packed_length", ":", "return", "generator", "return", "generator_utils", ".", "pack_examples", "(", "generator", ",", "self", ".", "has_inputs", ",", "self", ".", "packed_length", ",", "spacing", "=", "self", ".", "packed_spacing", ",", "chop_long_sequences", "=", "not", "self", ".", "has_inputs", ")" ]
Wraps generator with packer if self.packed_length.
[ "Wraps", "generator", "with", "packer", "if", "self", ".", "packed_length", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_problems.py#L289-L298
22,824
tensorflow/tensor2tensor
tensor2tensor/data_generators/text_problems.py
ChoppedTextProblem.text_filepaths_for_task
def text_filepaths_for_task(self, tmp_dir, task_id): """List of input filepaths for a particular training or dev shard. Args: tmp_dir: a string task_id: an integer less than self.num_shards Returns: a list of tuples (filepath, start_pos, num_bytes) """ assert task_id >= 0 assert task_id < self.num_train_shards + self.num_dev_shards if task_id < self.num_train_shards: return [ f for i, f in enumerate(self.train_text_filepaths(tmp_dir)) if i % self.num_train_shards == task_id ] else: return [ f for i, f in enumerate(self.dev_text_filepaths(tmp_dir)) if i % self.num_dev_shards == task_id - self.num_train_shards ]
python
def text_filepaths_for_task(self, tmp_dir, task_id): """List of input filepaths for a particular training or dev shard. Args: tmp_dir: a string task_id: an integer less than self.num_shards Returns: a list of tuples (filepath, start_pos, num_bytes) """ assert task_id >= 0 assert task_id < self.num_train_shards + self.num_dev_shards if task_id < self.num_train_shards: return [ f for i, f in enumerate(self.train_text_filepaths(tmp_dir)) if i % self.num_train_shards == task_id ] else: return [ f for i, f in enumerate(self.dev_text_filepaths(tmp_dir)) if i % self.num_dev_shards == task_id - self.num_train_shards ]
[ "def", "text_filepaths_for_task", "(", "self", ",", "tmp_dir", ",", "task_id", ")", ":", "assert", "task_id", ">=", "0", "assert", "task_id", "<", "self", ".", "num_train_shards", "+", "self", ".", "num_dev_shards", "if", "task_id", "<", "self", ".", "num_train_shards", ":", "return", "[", "f", "for", "i", ",", "f", "in", "enumerate", "(", "self", ".", "train_text_filepaths", "(", "tmp_dir", ")", ")", "if", "i", "%", "self", ".", "num_train_shards", "==", "task_id", "]", "else", ":", "return", "[", "f", "for", "i", ",", "f", "in", "enumerate", "(", "self", ".", "dev_text_filepaths", "(", "tmp_dir", ")", ")", "if", "i", "%", "self", ".", "num_dev_shards", "==", "task_id", "-", "self", ".", "num_train_shards", "]" ]
List of input filepaths for a particular training or dev shard. Args: tmp_dir: a string task_id: an integer less than self.num_shards Returns: a list of tuples (filepath, start_pos, num_bytes)
[ "List", "of", "input", "filepaths", "for", "a", "particular", "training", "or", "dev", "shard", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_problems.py#L831-L851
22,825
tensorflow/tensor2tensor
tensor2tensor/data_generators/text_problems.py
ChoppedTextProblem.filepath_to_unicode_strings
def filepath_to_unicode_strings(self, filepath): """Read text out of an input file. The default just reads the text, converts to unicode and yields one unicode string. Subclasses can override this function in order to preprocess, and can yield any number of strings. Args: filepath: a string Yields: unicode strings. """ f = tf.gfile.Open(filepath) b = f.read() yield text_encoder.to_unicode_ignore_errors(b)
python
def filepath_to_unicode_strings(self, filepath): """Read text out of an input file. The default just reads the text, converts to unicode and yields one unicode string. Subclasses can override this function in order to preprocess, and can yield any number of strings. Args: filepath: a string Yields: unicode strings. """ f = tf.gfile.Open(filepath) b = f.read() yield text_encoder.to_unicode_ignore_errors(b)
[ "def", "filepath_to_unicode_strings", "(", "self", ",", "filepath", ")", ":", "f", "=", "tf", ".", "gfile", ".", "Open", "(", "filepath", ")", "b", "=", "f", ".", "read", "(", ")", "yield", "text_encoder", ".", "to_unicode_ignore_errors", "(", "b", ")" ]
Read text out of an input file. The default just reads the text, converts to unicode and yields one unicode string. Subclasses can override this function in order to preprocess, and can yield any number of strings. Args: filepath: a string Yields: unicode strings.
[ "Read", "text", "out", "of", "an", "input", "file", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_problems.py#L853-L869
22,826
tensorflow/tensor2tensor
tensor2tensor/data_generators/text_problems.py
ChoppedTextProblem.file_generator
def file_generator(self, filepaths, max_chars_per_file=None, max_chars_total=None): """Read complete text of input files and yield unicode strings. By default, one unicode string is produced per file, but this is not guaranteed, since subclasses can override filepath_to_unicode_strings(). max_chars_per_file and max_chars_total can also be specified, in which case some strings may be truncated or dropped to limit the total amount of output. Args: filepaths: a list of strings max_chars_per_file: an optional integer max_chars_total: an optional integer Yields: unicode strings """ chars_total = 0 for fname in filepaths: chars_this_file = 0 tf.logging.info("reading file %s" % fname) for text in self.filepath_to_unicode_strings(fname): if (max_chars_per_file and chars_this_file + len(text) > max_chars_per_file): text = text[:max_chars_per_file - chars_this_file] if max_chars_total and chars_total + len(text) > max_chars_total: text = text[:max_chars_total - chars_total] chars_total += len(text) chars_this_file += len(text) if text: yield text if max_chars_total and chars_total >= max_chars_total: return if max_chars_per_file and chars_this_file >= max_chars_per_file: break
python
def file_generator(self, filepaths, max_chars_per_file=None, max_chars_total=None): """Read complete text of input files and yield unicode strings. By default, one unicode string is produced per file, but this is not guaranteed, since subclasses can override filepath_to_unicode_strings(). max_chars_per_file and max_chars_total can also be specified, in which case some strings may be truncated or dropped to limit the total amount of output. Args: filepaths: a list of strings max_chars_per_file: an optional integer max_chars_total: an optional integer Yields: unicode strings """ chars_total = 0 for fname in filepaths: chars_this_file = 0 tf.logging.info("reading file %s" % fname) for text in self.filepath_to_unicode_strings(fname): if (max_chars_per_file and chars_this_file + len(text) > max_chars_per_file): text = text[:max_chars_per_file - chars_this_file] if max_chars_total and chars_total + len(text) > max_chars_total: text = text[:max_chars_total - chars_total] chars_total += len(text) chars_this_file += len(text) if text: yield text if max_chars_total and chars_total >= max_chars_total: return if max_chars_per_file and chars_this_file >= max_chars_per_file: break
[ "def", "file_generator", "(", "self", ",", "filepaths", ",", "max_chars_per_file", "=", "None", ",", "max_chars_total", "=", "None", ")", ":", "chars_total", "=", "0", "for", "fname", "in", "filepaths", ":", "chars_this_file", "=", "0", "tf", ".", "logging", ".", "info", "(", "\"reading file %s\"", "%", "fname", ")", "for", "text", "in", "self", ".", "filepath_to_unicode_strings", "(", "fname", ")", ":", "if", "(", "max_chars_per_file", "and", "chars_this_file", "+", "len", "(", "text", ")", ">", "max_chars_per_file", ")", ":", "text", "=", "text", "[", ":", "max_chars_per_file", "-", "chars_this_file", "]", "if", "max_chars_total", "and", "chars_total", "+", "len", "(", "text", ")", ">", "max_chars_total", ":", "text", "=", "text", "[", ":", "max_chars_total", "-", "chars_total", "]", "chars_total", "+=", "len", "(", "text", ")", "chars_this_file", "+=", "len", "(", "text", ")", "if", "text", ":", "yield", "text", "if", "max_chars_total", "and", "chars_total", ">=", "max_chars_total", ":", "return", "if", "max_chars_per_file", "and", "chars_this_file", ">=", "max_chars_per_file", ":", "break" ]
Read complete text of input files and yield unicode strings. By default, one unicode string is produced per file, but this is not guaranteed, since subclasses can override filepath_to_unicode_strings(). max_chars_per_file and max_chars_total can also be specified, in which case some strings may be truncated or dropped to limit the total amount of output. Args: filepaths: a list of strings max_chars_per_file: an optional integer max_chars_total: an optional integer Yields: unicode strings
[ "Read", "complete", "text", "of", "input", "files", "and", "yield", "unicode", "strings", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_problems.py#L871-L909
22,827
tensorflow/tensor2tensor
tensor2tensor/data_generators/text_problems.py
ChoppedTextProblem.example_generator
def example_generator(self, encoder, tmp_dir, task_id): """Generator for examples. Args: encoder: a TextEncoder tmp_dir: a string task_id: an integer Yields: feature dictionaries """ filepaths = self.text_filepaths_for_task(tmp_dir, task_id) if task_id >= self.num_train_shards: # this is dev data - limit the total length. max_chars_per_file = self.max_dev_chars // ( self.num_dev_shards * len(filepaths)) else: max_chars_per_file = None tokens = [] for ftext in self.file_generator( filepaths, max_chars_per_file=max_chars_per_file): tokens.extend(encoder.encode(ftext)) pos = 0 while pos + self.sequence_length <= len(tokens): yield {"targets": tokens[pos:pos + self.sequence_length]} pos += self.sequence_length if pos > 0: tokens = tokens[pos:] if self.remainder_policy == "pad": if tokens: targets = tokens + [0] * (self.sequence_length - len(tokens)) yield {"targets": targets} else: assert self.remainder_policy == "drop"
python
def example_generator(self, encoder, tmp_dir, task_id): """Generator for examples. Args: encoder: a TextEncoder tmp_dir: a string task_id: an integer Yields: feature dictionaries """ filepaths = self.text_filepaths_for_task(tmp_dir, task_id) if task_id >= self.num_train_shards: # this is dev data - limit the total length. max_chars_per_file = self.max_dev_chars // ( self.num_dev_shards * len(filepaths)) else: max_chars_per_file = None tokens = [] for ftext in self.file_generator( filepaths, max_chars_per_file=max_chars_per_file): tokens.extend(encoder.encode(ftext)) pos = 0 while pos + self.sequence_length <= len(tokens): yield {"targets": tokens[pos:pos + self.sequence_length]} pos += self.sequence_length if pos > 0: tokens = tokens[pos:] if self.remainder_policy == "pad": if tokens: targets = tokens + [0] * (self.sequence_length - len(tokens)) yield {"targets": targets} else: assert self.remainder_policy == "drop"
[ "def", "example_generator", "(", "self", ",", "encoder", ",", "tmp_dir", ",", "task_id", ")", ":", "filepaths", "=", "self", ".", "text_filepaths_for_task", "(", "tmp_dir", ",", "task_id", ")", "if", "task_id", ">=", "self", ".", "num_train_shards", ":", "# this is dev data - limit the total length.", "max_chars_per_file", "=", "self", ".", "max_dev_chars", "//", "(", "self", ".", "num_dev_shards", "*", "len", "(", "filepaths", ")", ")", "else", ":", "max_chars_per_file", "=", "None", "tokens", "=", "[", "]", "for", "ftext", "in", "self", ".", "file_generator", "(", "filepaths", ",", "max_chars_per_file", "=", "max_chars_per_file", ")", ":", "tokens", ".", "extend", "(", "encoder", ".", "encode", "(", "ftext", ")", ")", "pos", "=", "0", "while", "pos", "+", "self", ".", "sequence_length", "<=", "len", "(", "tokens", ")", ":", "yield", "{", "\"targets\"", ":", "tokens", "[", "pos", ":", "pos", "+", "self", ".", "sequence_length", "]", "}", "pos", "+=", "self", ".", "sequence_length", "if", "pos", ">", "0", ":", "tokens", "=", "tokens", "[", "pos", ":", "]", "if", "self", ".", "remainder_policy", "==", "\"pad\"", ":", "if", "tokens", ":", "targets", "=", "tokens", "+", "[", "0", "]", "*", "(", "self", ".", "sequence_length", "-", "len", "(", "tokens", ")", ")", "yield", "{", "\"targets\"", ":", "targets", "}", "else", ":", "assert", "self", ".", "remainder_policy", "==", "\"drop\"" ]
Generator for examples. Args: encoder: a TextEncoder tmp_dir: a string task_id: an integer Yields: feature dictionaries
[ "Generator", "for", "examples", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_problems.py#L911-L943
22,828
tensorflow/tensor2tensor
tensor2tensor/data_generators/text_problems.py
ChoppedTextProblem.prepare_to_generate
def prepare_to_generate(self, data_dir, tmp_dir): """Make sure that the data is prepared and the vocab is generated.""" self.get_or_create_vocab(data_dir, tmp_dir) self.train_text_filepaths(tmp_dir) self.dev_text_filepaths(tmp_dir)
python
def prepare_to_generate(self, data_dir, tmp_dir): """Make sure that the data is prepared and the vocab is generated.""" self.get_or_create_vocab(data_dir, tmp_dir) self.train_text_filepaths(tmp_dir) self.dev_text_filepaths(tmp_dir)
[ "def", "prepare_to_generate", "(", "self", ",", "data_dir", ",", "tmp_dir", ")", ":", "self", ".", "get_or_create_vocab", "(", "data_dir", ",", "tmp_dir", ")", "self", ".", "train_text_filepaths", "(", "tmp_dir", ")", "self", ".", "dev_text_filepaths", "(", "tmp_dir", ")" ]
Make sure that the data is prepared and the vocab is generated.
[ "Make", "sure", "that", "the", "data", "is", "prepared", "and", "the", "vocab", "is", "generated", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/text_problems.py#L954-L958
22,829
tensorflow/tensor2tensor
tensor2tensor/trax/models/resnet.py
ConvBlock
def ConvBlock(kernel_size, filters, strides): """ResNet convolutional striding block.""" ks = kernel_size filters1, filters2, filters3 = filters main = layers.Serial( layers.Conv(filters1, (1, 1), strides), layers.BatchNorm(), layers.Relu(), layers.Conv(filters2, (ks, ks), padding='SAME'), layers.BatchNorm(), layers.Relu(), layers.Conv(filters3, (1, 1)), layers.BatchNorm() ) shortcut = layers.Serial( layers.Conv(filters3, (1, 1), strides), layers.BatchNorm() ) return layers.Serial( layers.Branch(), layers.Parallel(main, shortcut), layers.SumBranches(), layers.Relu() )
python
def ConvBlock(kernel_size, filters, strides): """ResNet convolutional striding block.""" ks = kernel_size filters1, filters2, filters3 = filters main = layers.Serial( layers.Conv(filters1, (1, 1), strides), layers.BatchNorm(), layers.Relu(), layers.Conv(filters2, (ks, ks), padding='SAME'), layers.BatchNorm(), layers.Relu(), layers.Conv(filters3, (1, 1)), layers.BatchNorm() ) shortcut = layers.Serial( layers.Conv(filters3, (1, 1), strides), layers.BatchNorm() ) return layers.Serial( layers.Branch(), layers.Parallel(main, shortcut), layers.SumBranches(), layers.Relu() )
[ "def", "ConvBlock", "(", "kernel_size", ",", "filters", ",", "strides", ")", ":", "ks", "=", "kernel_size", "filters1", ",", "filters2", ",", "filters3", "=", "filters", "main", "=", "layers", ".", "Serial", "(", "layers", ".", "Conv", "(", "filters1", ",", "(", "1", ",", "1", ")", ",", "strides", ")", ",", "layers", ".", "BatchNorm", "(", ")", ",", "layers", ".", "Relu", "(", ")", ",", "layers", ".", "Conv", "(", "filters2", ",", "(", "ks", ",", "ks", ")", ",", "padding", "=", "'SAME'", ")", ",", "layers", ".", "BatchNorm", "(", ")", ",", "layers", ".", "Relu", "(", ")", ",", "layers", ".", "Conv", "(", "filters3", ",", "(", "1", ",", "1", ")", ")", ",", "layers", ".", "BatchNorm", "(", ")", ")", "shortcut", "=", "layers", ".", "Serial", "(", "layers", ".", "Conv", "(", "filters3", ",", "(", "1", ",", "1", ")", ",", "strides", ")", ",", "layers", ".", "BatchNorm", "(", ")", ")", "return", "layers", ".", "Serial", "(", "layers", ".", "Branch", "(", ")", ",", "layers", ".", "Parallel", "(", "main", ",", "shortcut", ")", ",", "layers", ".", "SumBranches", "(", ")", ",", "layers", ".", "Relu", "(", ")", ")" ]
ResNet convolutional striding block.
[ "ResNet", "convolutional", "striding", "block", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/models/resnet.py#L25-L48
22,830
tensorflow/tensor2tensor
tensor2tensor/trax/models/resnet.py
IdentityBlock
def IdentityBlock(kernel_size, filters): """ResNet identical size block.""" ks = kernel_size filters1, filters2, filters3 = filters main = layers.Serial( layers.Conv(filters1, (1, 1)), layers.BatchNorm(), layers.Relu(), layers.Conv(filters2, (ks, ks), padding='SAME'), layers.BatchNorm(), layers.Relu(), layers.Conv(filters3, (1, 1)), layers.BatchNorm() ) return layers.Serial( layers.Branch(), layers.Parallel(main, layers.Identity()), layers.SumBranches(), layers.Relu() )
python
def IdentityBlock(kernel_size, filters): """ResNet identical size block.""" ks = kernel_size filters1, filters2, filters3 = filters main = layers.Serial( layers.Conv(filters1, (1, 1)), layers.BatchNorm(), layers.Relu(), layers.Conv(filters2, (ks, ks), padding='SAME'), layers.BatchNorm(), layers.Relu(), layers.Conv(filters3, (1, 1)), layers.BatchNorm() ) return layers.Serial( layers.Branch(), layers.Parallel(main, layers.Identity()), layers.SumBranches(), layers.Relu() )
[ "def", "IdentityBlock", "(", "kernel_size", ",", "filters", ")", ":", "ks", "=", "kernel_size", "filters1", ",", "filters2", ",", "filters3", "=", "filters", "main", "=", "layers", ".", "Serial", "(", "layers", ".", "Conv", "(", "filters1", ",", "(", "1", ",", "1", ")", ")", ",", "layers", ".", "BatchNorm", "(", ")", ",", "layers", ".", "Relu", "(", ")", ",", "layers", ".", "Conv", "(", "filters2", ",", "(", "ks", ",", "ks", ")", ",", "padding", "=", "'SAME'", ")", ",", "layers", ".", "BatchNorm", "(", ")", ",", "layers", ".", "Relu", "(", ")", ",", "layers", ".", "Conv", "(", "filters3", ",", "(", "1", ",", "1", ")", ")", ",", "layers", ".", "BatchNorm", "(", ")", ")", "return", "layers", ".", "Serial", "(", "layers", ".", "Branch", "(", ")", ",", "layers", ".", "Parallel", "(", "main", ",", "layers", ".", "Identity", "(", ")", ")", ",", "layers", ".", "SumBranches", "(", ")", ",", "layers", ".", "Relu", "(", ")", ")" ]
ResNet identical size block.
[ "ResNet", "identical", "size", "block", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/models/resnet.py#L51-L70
22,831
tensorflow/tensor2tensor
tensor2tensor/trax/models/resnet.py
WideResnetBlock
def WideResnetBlock(channels, strides=(1, 1), channel_mismatch=False): """WideResnet convolutational block.""" main = layers.Serial(layers.BatchNorm(), layers.Relu(), layers.Conv(channels, (3, 3), strides, padding='SAME'), layers.BatchNorm(), layers.Relu(), layers.Conv(channels, (3, 3), padding='SAME')) shortcut = layers.Identity() if not channel_mismatch else layers.Conv( channels, (3, 3), strides, padding='SAME') return layers.Serial( layers.Branch(), layers.Parallel(main, shortcut), layers.SumBranches())
python
def WideResnetBlock(channels, strides=(1, 1), channel_mismatch=False): """WideResnet convolutational block.""" main = layers.Serial(layers.BatchNorm(), layers.Relu(), layers.Conv(channels, (3, 3), strides, padding='SAME'), layers.BatchNorm(), layers.Relu(), layers.Conv(channels, (3, 3), padding='SAME')) shortcut = layers.Identity() if not channel_mismatch else layers.Conv( channels, (3, 3), strides, padding='SAME') return layers.Serial( layers.Branch(), layers.Parallel(main, shortcut), layers.SumBranches())
[ "def", "WideResnetBlock", "(", "channels", ",", "strides", "=", "(", "1", ",", "1", ")", ",", "channel_mismatch", "=", "False", ")", ":", "main", "=", "layers", ".", "Serial", "(", "layers", ".", "BatchNorm", "(", ")", ",", "layers", ".", "Relu", "(", ")", ",", "layers", ".", "Conv", "(", "channels", ",", "(", "3", ",", "3", ")", ",", "strides", ",", "padding", "=", "'SAME'", ")", ",", "layers", ".", "BatchNorm", "(", ")", ",", "layers", ".", "Relu", "(", ")", ",", "layers", ".", "Conv", "(", "channels", ",", "(", "3", ",", "3", ")", ",", "padding", "=", "'SAME'", ")", ")", "shortcut", "=", "layers", ".", "Identity", "(", ")", "if", "not", "channel_mismatch", "else", "layers", ".", "Conv", "(", "channels", ",", "(", "3", ",", "3", ")", ",", "strides", ",", "padding", "=", "'SAME'", ")", "return", "layers", ".", "Serial", "(", "layers", ".", "Branch", "(", ")", ",", "layers", ".", "Parallel", "(", "main", ",", "shortcut", ")", ",", "layers", ".", "SumBranches", "(", ")", ")" ]
WideResnet convolutational block.
[ "WideResnet", "convolutational", "block", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/models/resnet.py#L109-L118
22,832
tensorflow/tensor2tensor
tensor2tensor/trax/layers/rnn.py
GRUCell
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_transform=lambda: core.Dense(units=units), memory_transform=combinators.Identity, gate_nonlinearity=core.Sigmoid, candidate_nonlinearity=core.Tanh)
python
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_transform=lambda: core.Dense(units=units), memory_transform=combinators.Identity, gate_nonlinearity=core.Sigmoid, candidate_nonlinearity=core.Tanh)
[ "def", "GRUCell", "(", "units", ")", ":", "return", "GeneralGRUCell", "(", "candidate_transform", "=", "lambda", ":", "core", ".", "Dense", "(", "units", "=", "units", ")", ",", "memory_transform", "=", "combinators", ".", "Identity", ",", "gate_nonlinearity", "=", "core", ".", "Sigmoid", ",", "candidate_nonlinearity", "=", "core", ".", "Tanh", ")" ]
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.
[ "Builds", "a", "traditional", "GRU", "cell", "with", "dense", "internal", "transformations", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/rnn.py#L28-L44
22,833
tensorflow/tensor2tensor
tensor2tensor/trax/layers/rnn.py
ConvGRUCell
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(): return core.Conv(filters=units, kernel_size=kernel_size, padding='SAME') return GeneralGRUCell( candidate_transform=BuildConv, memory_transform=combinators.Identity, gate_nonlinearity=core.Sigmoid, candidate_nonlinearity=core.Tanh)
python
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(): return core.Conv(filters=units, kernel_size=kernel_size, padding='SAME') return GeneralGRUCell( candidate_transform=BuildConv, memory_transform=combinators.Identity, gate_nonlinearity=core.Sigmoid, candidate_nonlinearity=core.Tanh)
[ "def", "ConvGRUCell", "(", "units", ",", "kernel_size", "=", "(", "3", ",", "3", ")", ")", ":", "def", "BuildConv", "(", ")", ":", "return", "core", ".", "Conv", "(", "filters", "=", "units", ",", "kernel_size", "=", "kernel_size", ",", "padding", "=", "'SAME'", ")", "return", "GeneralGRUCell", "(", "candidate_transform", "=", "BuildConv", ",", "memory_transform", "=", "combinators", ".", "Identity", ",", "gate_nonlinearity", "=", "core", ".", "Sigmoid", ",", "candidate_nonlinearity", "=", "core", ".", "Tanh", ")" ]
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.
[ "Builds", "a", "convolutional", "GRU", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/rnn.py#L47-L67
22,834
tensorflow/tensor2tensor
tensor2tensor/trax/layers/attention.py
MakeTargetMask
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=0) target_mask = target_mask & causal_mask return np.expand_dims(target_mask, axis=1)
python
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=0) target_mask = target_mask & causal_mask return np.expand_dims(target_mask, axis=1)
[ "def", "MakeTargetMask", "(", "target", ",", "pad", "=", "0", ")", ":", "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", "=", "0", ")", "target_mask", "=", "target_mask", "&", "causal_mask", "return", "np", ".", "expand_dims", "(", "target_mask", ",", "axis", "=", "1", ")" ]
Create an attention mask to hide padding and future words.
[ "Create", "an", "attention", "mask", "to", "hide", "padding", "and", "future", "words", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L43-L50
22,835
tensorflow/tensor2tensor
tensor2tensor/trax/layers/attention.py
PreparePairedSequenceBatch
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: Prepared batch of tuple of arrays: source, input-target, shifted-target, source mask, target mask, source-target "memory" mask, minibatch token count """ target = target_in[:, :-1] target_y = target_in[:, 1:] source_mask = np.reshape(source != pad, (source.shape[0], 1, 1, source.shape[-1])) target_mask = MakeTargetMask(target, pad) memory_mask = ( np.reshape(np.arange(target.shape[-1]) < source.shape[-1], [-1, 1])) ntokens = np.sum(target_y != pad) return (source, target, target_y, source_mask, target_mask, memory_mask, ntokens)
python
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: Prepared batch of tuple of arrays: source, input-target, shifted-target, source mask, target mask, source-target "memory" mask, minibatch token count """ target = target_in[:, :-1] target_y = target_in[:, 1:] source_mask = np.reshape(source != pad, (source.shape[0], 1, 1, source.shape[-1])) target_mask = MakeTargetMask(target, pad) memory_mask = ( np.reshape(np.arange(target.shape[-1]) < source.shape[-1], [-1, 1])) ntokens = np.sum(target_y != pad) return (source, target, target_y, source_mask, target_mask, memory_mask, ntokens)
[ "def", "PreparePairedSequenceBatch", "(", "source", ",", "target_in", ",", "pad", "=", "0", ")", ":", "target", "=", "target_in", "[", ":", ",", ":", "-", "1", "]", "target_y", "=", "target_in", "[", ":", ",", "1", ":", "]", "source_mask", "=", "np", ".", "reshape", "(", "source", "!=", "pad", ",", "(", "source", ".", "shape", "[", "0", "]", ",", "1", ",", "1", ",", "source", ".", "shape", "[", "-", "1", "]", ")", ")", "target_mask", "=", "MakeTargetMask", "(", "target", ",", "pad", ")", "memory_mask", "=", "(", "np", ".", "reshape", "(", "np", ".", "arange", "(", "target", ".", "shape", "[", "-", "1", "]", ")", "<", "source", ".", "shape", "[", "-", "1", "]", ",", "[", "-", "1", ",", "1", "]", ")", ")", "ntokens", "=", "np", ".", "sum", "(", "target_y", "!=", "pad", ")", "return", "(", "source", ",", "target", ",", "target_y", ",", "source_mask", ",", "target_mask", ",", "memory_mask", ",", "ntokens", ")" ]
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, shifted-target, source mask, target mask, source-target "memory" mask, minibatch token count
[ "Build", "masks", "for", "this", "batch", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L53-L74
22,836
tensorflow/tensor2tensor
tensor2tensor/trax/layers/attention.py
PositionalEncoding
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 results = [] for chunk in x: symbol_size = np.shape(chunk)[1] results.append(chunk + params[:, offset:offset + symbol_size, :]) offset += symbol_size return results
python
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 results = [] for chunk in x: symbol_size = np.shape(chunk)[1] results.append(chunk + params[:, offset:offset + symbol_size, :]) offset += symbol_size return results
[ "def", "PositionalEncoding", "(", "x", ",", "params", ",", "*", "*", "unused_kwargs", ")", ":", "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", "results", "=", "[", "]", "for", "chunk", "in", "x", ":", "symbol_size", "=", "np", ".", "shape", "(", "chunk", ")", "[", "1", "]", "results", ".", "append", "(", "chunk", "+", "params", "[", ":", ",", "offset", ":", "offset", "+", "symbol_size", ",", ":", "]", ")", "offset", "+=", "symbol_size", "return", "results" ]
Implements bare positional encoding.
[ "Implements", "bare", "positional", "encoding", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L115-L127
22,837
tensorflow/tensor2tensor
tensor2tensor/trax/layers/attention.py
DotProductAttention
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 'train': whether to use dropout rng: JAX PRNGKey: subkey for disposable use Returns: Self attention for q, k, v arrays. """ depth = np.shape(query)[-1] dots = np.matmul(query, np.swapaxes(key, -1, -2)) / np.sqrt(depth) if mask is not None: dots = np.where(mask, dots, -1e9) # Softmax. dots = np.exp(dots - backend.logsumexp(dots, axis=-1, keepdims=True)) if dropout >= 1.0: raise ValueError('Dropout rates must be lower than 1.') if dropout is not None and dropout > 0.0 and mode == 'train': keep = backend.random.bernoulli(rng, 1.0 - dropout, dots.shape) dots = np.where(keep, dots / (1.0 - dropout), 0) out = np.matmul(dots, value) return out
python
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 'train': whether to use dropout rng: JAX PRNGKey: subkey for disposable use Returns: Self attention for q, k, v arrays. """ depth = np.shape(query)[-1] dots = np.matmul(query, np.swapaxes(key, -1, -2)) / np.sqrt(depth) if mask is not None: dots = np.where(mask, dots, -1e9) # Softmax. dots = np.exp(dots - backend.logsumexp(dots, axis=-1, keepdims=True)) if dropout >= 1.0: raise ValueError('Dropout rates must be lower than 1.') if dropout is not None and dropout > 0.0 and mode == 'train': keep = backend.random.bernoulli(rng, 1.0 - dropout, dots.shape) dots = np.where(keep, dots / (1.0 - dropout), 0) out = np.matmul(dots, value) return out
[ "def", "DotProductAttention", "(", "query", ",", "key", ",", "value", ",", "mask", ",", "dropout", ",", "mode", ",", "rng", ")", ":", "depth", "=", "np", ".", "shape", "(", "query", ")", "[", "-", "1", "]", "dots", "=", "np", ".", "matmul", "(", "query", ",", "np", ".", "swapaxes", "(", "key", ",", "-", "1", ",", "-", "2", ")", ")", "/", "np", ".", "sqrt", "(", "depth", ")", "if", "mask", "is", "not", "None", ":", "dots", "=", "np", ".", "where", "(", "mask", ",", "dots", ",", "-", "1e9", ")", "# Softmax.", "dots", "=", "np", ".", "exp", "(", "dots", "-", "backend", ".", "logsumexp", "(", "dots", ",", "axis", "=", "-", "1", ",", "keepdims", "=", "True", ")", ")", "if", "dropout", ">=", "1.0", ":", "raise", "ValueError", "(", "'Dropout rates must be lower than 1.'", ")", "if", "dropout", "is", "not", "None", "and", "dropout", ">", "0.0", "and", "mode", "==", "'train'", ":", "keep", "=", "backend", ".", "random", ".", "bernoulli", "(", "rng", ",", "1.0", "-", "dropout", ",", "dots", ".", "shape", ")", "dots", "=", "np", ".", "where", "(", "keep", ",", "dots", "/", "(", "1.0", "-", "dropout", ")", ",", "0", ")", "out", "=", "np", ".", "matmul", "(", "dots", ",", "value", ")", "return", "out" ]
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 use Returns: Self attention for q, k, v arrays.
[ "Core", "dot", "product", "self", "-", "attention", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L130-L157
22,838
tensorflow/tensor2tensor
tensor2tensor/trax/layers/attention.py
PureDotProductAttention
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-name q_shape, _, v_shape, _ = input_shapes output_shape = q_shape[:-1] + (v_shape[-1],) return output_shape, () def apply_fun(params, inputs, **kwargs): # pylint: disable=invalid-name del params q, k, v, mask = inputs rng = kwargs.get('rng', None) return DotProductAttention(q, k, v, mask, dropout=dropout, mode=mode, rng=rng) return init_fun, apply_fun
python
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-name q_shape, _, v_shape, _ = input_shapes output_shape = q_shape[:-1] + (v_shape[-1],) return output_shape, () def apply_fun(params, inputs, **kwargs): # pylint: disable=invalid-name del params q, k, v, mask = inputs rng = kwargs.get('rng', None) return DotProductAttention(q, k, v, mask, dropout=dropout, mode=mode, rng=rng) return init_fun, apply_fun
[ "def", "PureDotProductAttention", "(", "dropout", "=", "0.0", ",", "mode", "=", "'train'", ")", ":", "def", "init_fun", "(", "_", ",", "input_shapes", ")", ":", "# pylint: disable=invalid-name", "q_shape", ",", "_", ",", "v_shape", ",", "_", "=", "input_shapes", "output_shape", "=", "q_shape", "[", ":", "-", "1", "]", "+", "(", "v_shape", "[", "-", "1", "]", ",", ")", "return", "output_shape", ",", "(", ")", "def", "apply_fun", "(", "params", ",", "inputs", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=invalid-name", "del", "params", "q", ",", "k", ",", "v", ",", "mask", "=", "inputs", "rng", "=", "kwargs", ".", "get", "(", "'rng'", ",", "None", ")", "return", "DotProductAttention", "(", "q", ",", "k", ",", "v", ",", "mask", ",", "dropout", "=", "dropout", ",", "mode", "=", "mode", ",", "rng", "=", "rng", ")", "return", "init_fun", ",", "apply_fun" ]
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.)
[ "Pure", "single", "-", "headed", "self", "-", "attention", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L161-L181
22,839
tensorflow/tensor2tensor
tensor2tensor/trax/layers/attention.py
PureMultiHeadedAttention
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 rate mode: str: 'train' or 'eval' **kwargs: other arguments including the rng Returns: Pure Multi-headed attention layer (no Dense transforms on input). """ del params rng = kwargs.get('rng', None) (q, k, v), mask = x feature_depth = q.shape[-1] assert feature_depth % num_heads == 0 head_depth = feature_depth // num_heads nbatch = np.shape(q)[0] # nbatch, seqlen, feature_depth --> nbatch, num_heads, seqlen, head_depth def SplitHeads(x): return np.transpose( np.reshape(x, (nbatch, -1, num_heads, head_depth)), (0, 2, 1, 3)) # nbatch, num_heads, seqlen, head_depth --> nbatch, seqlen, feature_depth def JoinHeads(x): # pylint: disable=invalid-name return np.reshape( np.transpose(x, (0, 2, 1, 3)), (nbatch, -1, num_heads*head_depth)) # Split heads, dot-product attention, rejoin heads. return JoinHeads( DotProductAttention( SplitHeads(q), SplitHeads(k), SplitHeads(v), mask, dropout=dropout, mode=mode, rng=rng))
python
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 rate mode: str: 'train' or 'eval' **kwargs: other arguments including the rng Returns: Pure Multi-headed attention layer (no Dense transforms on input). """ del params rng = kwargs.get('rng', None) (q, k, v), mask = x feature_depth = q.shape[-1] assert feature_depth % num_heads == 0 head_depth = feature_depth // num_heads nbatch = np.shape(q)[0] # nbatch, seqlen, feature_depth --> nbatch, num_heads, seqlen, head_depth def SplitHeads(x): return np.transpose( np.reshape(x, (nbatch, -1, num_heads, head_depth)), (0, 2, 1, 3)) # nbatch, num_heads, seqlen, head_depth --> nbatch, seqlen, feature_depth def JoinHeads(x): # pylint: disable=invalid-name return np.reshape( np.transpose(x, (0, 2, 1, 3)), (nbatch, -1, num_heads*head_depth)) # Split heads, dot-product attention, rejoin heads. return JoinHeads( DotProductAttention( SplitHeads(q), SplitHeads(k), SplitHeads(v), mask, dropout=dropout, mode=mode, rng=rng))
[ "def", "PureMultiHeadedAttention", "(", "x", ",", "params", ",", "num_heads", "=", "8", ",", "dropout", "=", "0.0", ",", "mode", "=", "'train'", ",", "*", "*", "kwargs", ")", ":", "del", "params", "rng", "=", "kwargs", ".", "get", "(", "'rng'", ",", "None", ")", "(", "q", ",", "k", ",", "v", ")", ",", "mask", "=", "x", "feature_depth", "=", "q", ".", "shape", "[", "-", "1", "]", "assert", "feature_depth", "%", "num_heads", "==", "0", "head_depth", "=", "feature_depth", "//", "num_heads", "nbatch", "=", "np", ".", "shape", "(", "q", ")", "[", "0", "]", "# nbatch, seqlen, feature_depth --> nbatch, num_heads, seqlen, head_depth", "def", "SplitHeads", "(", "x", ")", ":", "return", "np", ".", "transpose", "(", "np", ".", "reshape", "(", "x", ",", "(", "nbatch", ",", "-", "1", ",", "num_heads", ",", "head_depth", ")", ")", ",", "(", "0", ",", "2", ",", "1", ",", "3", ")", ")", "# nbatch, num_heads, seqlen, head_depth --> nbatch, seqlen, feature_depth", "def", "JoinHeads", "(", "x", ")", ":", "# pylint: disable=invalid-name", "return", "np", ".", "reshape", "(", "np", ".", "transpose", "(", "x", ",", "(", "0", ",", "2", ",", "1", ",", "3", ")", ")", ",", "(", "nbatch", ",", "-", "1", ",", "num_heads", "*", "head_depth", ")", ")", "# Split heads, dot-product attention, rejoin heads.", "return", "JoinHeads", "(", "DotProductAttention", "(", "SplitHeads", "(", "q", ")", ",", "SplitHeads", "(", "k", ")", ",", "SplitHeads", "(", "v", ")", ",", "mask", ",", "dropout", "=", "dropout", ",", "mode", "=", "mode", ",", "rng", "=", "rng", ")", ")" ]
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 attention layer (no Dense transforms on input).
[ "Pure", "transformer", "-", "style", "multi", "-", "headed", "attention", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L192-L226
22,840
tensorflow/tensor2tensor
tensor2tensor/trax/layers/attention.py
ChunkedAttentionSelector
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 says which other chunks should be appended to the given one (previous if None). **kwargs: unused other arguments. Returns: a list of elements of the form (q, k', v'), mask' where k', v' and mask' are concatenations of k, v and identity-extended masks from selected chunks. """ del params, kwargs selector = selector or (lambda x: [] if x < 1 else [x-1]) triples, masks = zip(*x) (queries, keys, values) = zip(*triples) result = [] for i in range(len(x)): selected = selector(i) # Since keys and values are [batch, length, depth] we concatenate on axis=1. # We also always include the current key or value at the end. new_key_list = [keys[j] for j in selected] new_key = np.concatenate(new_key_list + [keys[i]], axis=1) new_value = np.concatenate( [values[j] for j in selected] + [values[i]], axis=1) # Masks are (1, query-len, key-len) so we concatenate on axis=2. new_mask_shapes = [(1, queries[i].shape[1], key.shape[1]) for key in new_key_list] cur_mask = masks[i] # Masks are all-1 for the added chunks (no masking). new_mask_list = [np.ones(s, dtype=cur_mask.dtype) for s in new_mask_shapes] # We still use the current (often causal) mask for the final chunk. new_mask = np.concatenate(new_mask_list + [cur_mask], axis=2) result.append(((queries[i], new_key, new_value), new_mask)) return tuple(result)
python
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 says which other chunks should be appended to the given one (previous if None). **kwargs: unused other arguments. Returns: a list of elements of the form (q, k', v'), mask' where k', v' and mask' are concatenations of k, v and identity-extended masks from selected chunks. """ del params, kwargs selector = selector or (lambda x: [] if x < 1 else [x-1]) triples, masks = zip(*x) (queries, keys, values) = zip(*triples) result = [] for i in range(len(x)): selected = selector(i) # Since keys and values are [batch, length, depth] we concatenate on axis=1. # We also always include the current key or value at the end. new_key_list = [keys[j] for j in selected] new_key = np.concatenate(new_key_list + [keys[i]], axis=1) new_value = np.concatenate( [values[j] for j in selected] + [values[i]], axis=1) # Masks are (1, query-len, key-len) so we concatenate on axis=2. new_mask_shapes = [(1, queries[i].shape[1], key.shape[1]) for key in new_key_list] cur_mask = masks[i] # Masks are all-1 for the added chunks (no masking). new_mask_list = [np.ones(s, dtype=cur_mask.dtype) for s in new_mask_shapes] # We still use the current (often causal) mask for the final chunk. new_mask = np.concatenate(new_mask_list + [cur_mask], axis=2) result.append(((queries[i], new_key, new_value), new_mask)) return tuple(result)
[ "def", "ChunkedAttentionSelector", "(", "x", ",", "params", ",", "selector", "=", "None", ",", "*", "*", "kwargs", ")", ":", "del", "params", ",", "kwargs", "selector", "=", "selector", "or", "(", "lambda", "x", ":", "[", "]", "if", "x", "<", "1", "else", "[", "x", "-", "1", "]", ")", "triples", ",", "masks", "=", "zip", "(", "*", "x", ")", "(", "queries", ",", "keys", ",", "values", ")", "=", "zip", "(", "*", "triples", ")", "result", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "x", ")", ")", ":", "selected", "=", "selector", "(", "i", ")", "# Since keys and values are [batch, length, depth] we concatenate on axis=1.", "# We also always include the current key or value at the end.", "new_key_list", "=", "[", "keys", "[", "j", "]", "for", "j", "in", "selected", "]", "new_key", "=", "np", ".", "concatenate", "(", "new_key_list", "+", "[", "keys", "[", "i", "]", "]", ",", "axis", "=", "1", ")", "new_value", "=", "np", ".", "concatenate", "(", "[", "values", "[", "j", "]", "for", "j", "in", "selected", "]", "+", "[", "values", "[", "i", "]", "]", ",", "axis", "=", "1", ")", "# Masks are (1, query-len, key-len) so we concatenate on axis=2.", "new_mask_shapes", "=", "[", "(", "1", ",", "queries", "[", "i", "]", ".", "shape", "[", "1", "]", ",", "key", ".", "shape", "[", "1", "]", ")", "for", "key", "in", "new_key_list", "]", "cur_mask", "=", "masks", "[", "i", "]", "# Masks are all-1 for the added chunks (no masking).", "new_mask_list", "=", "[", "np", ".", "ones", "(", "s", ",", "dtype", "=", "cur_mask", ".", "dtype", ")", "for", "s", "in", "new_mask_shapes", "]", "# We still use the current (often causal) mask for the final chunk.", "new_mask", "=", "np", ".", "concatenate", "(", "new_mask_list", "+", "[", "cur_mask", "]", ",", "axis", "=", "2", ")", "result", ".", "append", "(", "(", "(", "queries", "[", "i", "]", ",", "new_key", ",", "new_value", ")", ",", "new_mask", ")", ")", "return", "tuple", "(", "result", ")" ]
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 (previous if None). **kwargs: unused other arguments. Returns: a list of elements of the form (q, k', v'), mask' where k', v' and mask' are concatenations of k, v and identity-extended masks from selected chunks.
[ "Select", "which", "chunks", "to", "attend", "to", "in", "chunked", "attention", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L312-L348
22,841
tensorflow/tensor2tensor
tensor2tensor/trax/layers/attention.py
ChunkedCausalMultiHeadedAttention
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 num_heads: int: number of attention heads dropout: float: dropout rate chunk_selector: a function from chunk number to list of chunks to attend. mode: str: 'train' or 'eval' Returns: Multi-headed self-attention layer. """ prepare_attention_input = combinators.Serial( combinators.Branch(), combinators.Parallel( combinators.Branch(num_branches=3), # q = k = v = first input CausalMask(axis=-2), # pylint: disable=no-value-for-parameter ), combinators.Parallel( combinators.Parallel( core.Dense(feature_depth), core.Dense(feature_depth), core.Dense(feature_depth), ), combinators.Identity() ) ) return combinators.Serial( combinators.Map(prepare_attention_input), ChunkedAttentionSelector(selector=chunk_selector), # pylint: disable=no-value-for-parameter combinators.Map(PureMultiHeadedAttention( # pylint: disable=no-value-for-parameter feature_depth=feature_depth, num_heads=num_heads, dropout=dropout, mode=mode), check_shapes=False), combinators.Map(core.Dense(feature_depth)) )
python
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 num_heads: int: number of attention heads dropout: float: dropout rate chunk_selector: a function from chunk number to list of chunks to attend. mode: str: 'train' or 'eval' Returns: Multi-headed self-attention layer. """ prepare_attention_input = combinators.Serial( combinators.Branch(), combinators.Parallel( combinators.Branch(num_branches=3), # q = k = v = first input CausalMask(axis=-2), # pylint: disable=no-value-for-parameter ), combinators.Parallel( combinators.Parallel( core.Dense(feature_depth), core.Dense(feature_depth), core.Dense(feature_depth), ), combinators.Identity() ) ) return combinators.Serial( combinators.Map(prepare_attention_input), ChunkedAttentionSelector(selector=chunk_selector), # pylint: disable=no-value-for-parameter combinators.Map(PureMultiHeadedAttention( # pylint: disable=no-value-for-parameter feature_depth=feature_depth, num_heads=num_heads, dropout=dropout, mode=mode), check_shapes=False), combinators.Map(core.Dense(feature_depth)) )
[ "def", "ChunkedCausalMultiHeadedAttention", "(", "feature_depth", ",", "num_heads", "=", "8", ",", "dropout", "=", "0.0", ",", "chunk_selector", "=", "None", ",", "mode", "=", "'train'", ")", ":", "prepare_attention_input", "=", "combinators", ".", "Serial", "(", "combinators", ".", "Branch", "(", ")", ",", "combinators", ".", "Parallel", "(", "combinators", ".", "Branch", "(", "num_branches", "=", "3", ")", ",", "# q = k = v = first input", "CausalMask", "(", "axis", "=", "-", "2", ")", ",", "# pylint: disable=no-value-for-parameter", ")", ",", "combinators", ".", "Parallel", "(", "combinators", ".", "Parallel", "(", "core", ".", "Dense", "(", "feature_depth", ")", ",", "core", ".", "Dense", "(", "feature_depth", ")", ",", "core", ".", "Dense", "(", "feature_depth", ")", ",", ")", ",", "combinators", ".", "Identity", "(", ")", ")", ")", "return", "combinators", ".", "Serial", "(", "combinators", ".", "Map", "(", "prepare_attention_input", ")", ",", "ChunkedAttentionSelector", "(", "selector", "=", "chunk_selector", ")", ",", "# pylint: disable=no-value-for-parameter", "combinators", ".", "Map", "(", "PureMultiHeadedAttention", "(", "# pylint: disable=no-value-for-parameter", "feature_depth", "=", "feature_depth", ",", "num_heads", "=", "num_heads", ",", "dropout", "=", "dropout", ",", "mode", "=", "mode", ")", ",", "check_shapes", "=", "False", ")", ",", "combinators", ".", "Map", "(", "core", ".", "Dense", "(", "feature_depth", ")", ")", ")" ]
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 number to list of chunks to attend. mode: str: 'train' or 'eval' Returns: Multi-headed self-attention layer.
[ "Transformer", "-", "style", "causal", "multi", "-", "headed", "attention", "operating", "on", "chunks", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L351-L389
22,842
tensorflow/tensor2tensor
tensor2tensor/trax/layers/attention.py
ShiftRight
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 the list of chunks represents a big # sequence (the concatenation of the chunks). We want to shift that sequence, # so we put a 0 in the beginning of the first chunk and the last element of # that chunk is used as the new first element of the next chunk, and so on. padded = [] last_value = np.zeros_like(x[0][:, -1]) for chunk in x: padded_chunk = np.concatenate([last_value[:, np.newaxis], chunk], axis=1) last_value = chunk[:, -1] padded.append(padded_chunk[:, :-1]) return padded
python
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 the list of chunks represents a big # sequence (the concatenation of the chunks). We want to shift that sequence, # so we put a 0 in the beginning of the first chunk and the last element of # that chunk is used as the new first element of the next chunk, and so on. padded = [] last_value = np.zeros_like(x[0][:, -1]) for chunk in x: padded_chunk = np.concatenate([last_value[:, np.newaxis], chunk], axis=1) last_value = chunk[:, -1] padded.append(padded_chunk[:, :-1]) return padded
[ "def", "ShiftRight", "(", "x", ",", "*", "*", "unused_kwargs", ")", ":", "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 the list of chunks represents a big", "# sequence (the concatenation of the chunks). We want to shift that sequence,", "# so we put a 0 in the beginning of the first chunk and the last element of", "# that chunk is used as the new first element of the next chunk, and so on.", "padded", "=", "[", "]", "last_value", "=", "np", ".", "zeros_like", "(", "x", "[", "0", "]", "[", ":", ",", "-", "1", "]", ")", "for", "chunk", "in", "x", ":", "padded_chunk", "=", "np", ".", "concatenate", "(", "[", "last_value", "[", ":", ",", "np", ".", "newaxis", "]", ",", "chunk", "]", ",", "axis", "=", "1", ")", "last_value", "=", "chunk", "[", ":", ",", "-", "1", "]", "padded", ".", "append", "(", "padded_chunk", "[", ":", ",", ":", "-", "1", "]", ")", "return", "padded" ]
Layer to shift the tensor to the right by padding on axis 1.
[ "Layer", "to", "shift", "the", "tensor", "to", "the", "right", "by", "padding", "on", "axis", "1", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/trax/layers/attention.py#L393-L409
22,843
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic.py
reverse_generator_nlplike
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 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 produced. Args: nbr_symbols: integer, number of symbols. max_length: integer, maximum length of sequences to generate. nbr_cases: the number of cases to generate. scale_std_dev: float, Normal distribution's standard deviation scale factor used to draw the length of sequence. Default = 1% of the max_length. alpha: float, Zipf's Law Distribution parameter. Default = 1.5. Usually for modelling natural text distribution is in the range [1.1-1.6]. Yields: A dictionary {"inputs": input-list, "targets": target-list} where target-list is input-list reversed. """ std_dev = max_length / scale_std_dev distr_map = zipf_distribution(nbr_symbols, alpha) for _ in range(nbr_cases): l = int(abs(np.random.normal(loc=max_length / 2, scale=std_dev)) + 1) inputs = zipf_random_sample(distr_map, l) yield {"inputs": inputs, "targets": list(reversed(inputs))}
python
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 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 produced. Args: nbr_symbols: integer, number of symbols. max_length: integer, maximum length of sequences to generate. nbr_cases: the number of cases to generate. scale_std_dev: float, Normal distribution's standard deviation scale factor used to draw the length of sequence. Default = 1% of the max_length. alpha: float, Zipf's Law Distribution parameter. Default = 1.5. Usually for modelling natural text distribution is in the range [1.1-1.6]. Yields: A dictionary {"inputs": input-list, "targets": target-list} where target-list is input-list reversed. """ std_dev = max_length / scale_std_dev distr_map = zipf_distribution(nbr_symbols, alpha) for _ in range(nbr_cases): l = int(abs(np.random.normal(loc=max_length / 2, scale=std_dev)) + 1) inputs = zipf_random_sample(distr_map, l) yield {"inputs": inputs, "targets": list(reversed(inputs))}
[ "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", "(", "nbr_symbols", ",", "alpha", ")", "for", "_", "in", "range", "(", "nbr_cases", ")", ":", "l", "=", "int", "(", "abs", "(", "np", ".", "random", ".", "normal", "(", "loc", "=", "max_length", "/", "2", ",", "scale", "=", "std_dev", ")", ")", "+", "1", ")", "inputs", "=", "zipf_random_sample", "(", "distr_map", ",", "l", ")", "yield", "{", "\"inputs\"", ":", "inputs", ",", "\"targets\"", ":", "list", "(", "reversed", "(", "inputs", ")", ")", "}" ]
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 produced. Args: nbr_symbols: integer, number of symbols. max_length: integer, maximum length of sequences to generate. nbr_cases: the number of cases to generate. scale_std_dev: float, Normal distribution's standard deviation scale factor used to draw the length of sequence. Default = 1% of the max_length. alpha: float, Zipf's Law Distribution parameter. Default = 1.5. Usually for modelling natural text distribution is in the range [1.1-1.6]. Yields: A dictionary {"inputs": input-list, "targets": target-list} where target-list is input-list reversed.
[ "Generator", "for", "the", "reversing", "nlp", "-", "like", "task", "on", "sequences", "of", "symbols", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic.py#L243-L274
22,844
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikisum/parallel_launch.py
remote_run
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.info("Retry %d for %s", i, args) return sp.check_call(args) except sp.CalledProcessError as e: if i == retries: raise e
python
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.info("Retry %d for %s", i, args) return sp.check_call(args) except sp.CalledProcessError as e: if i == retries: raise e
[ "def", "remote_run", "(", "cmd", ",", "instance_name", ",", "detach", "=", "False", ",", "retries", "=", "1", ")", ":", "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", ".", "info", "(", "\"Retry %d for %s\"", ",", "i", ",", "args", ")", "return", "sp", ".", "check_call", "(", "args", ")", "except", "sp", ".", "CalledProcessError", "as", "e", ":", "if", "i", "==", "retries", ":", "raise", "e" ]
Run command on GCS instance, optionally detached.
[ "Run", "command", "on", "GCS", "instance", "optionally", "detached", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/parallel_launch.py#L98-L111
22,845
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikisum/parallel_launch.py
wait_for_ssh
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
python
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", ")", ":", "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.
[ "Wait", "for", "SSH", "to", "be", "available", "at", "given", "IP", "address", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/parallel_launch.py#L128-L138
22,846
tensorflow/tensor2tensor
tensor2tensor/data_generators/wikisum/parallel_launch.py
launch_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(instance_name, cpu=cpu, mem=mem) tf.logging.info("Waiting for SSH %s", instance_name) ready = wait_for_ssh(ip) if not ready: raise ValueError("Instance %s never ready for SSH" % instance_name) # Copy code if code_dir: shell_run_with_retry(COPY_CODE, retries=2, local_dir=code_dir, instance_name=instance_name) # Run setup if setup_command: tf.logging.info("Running setup on %s", instance_name) remote_run(setup_command, instance_name) # Run command tf.logging.info("Running command on %s", instance_name) remote_run(command, instance_name, detach=True)
python
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(instance_name, cpu=cpu, mem=mem) tf.logging.info("Waiting for SSH %s", instance_name) ready = wait_for_ssh(ip) if not ready: raise ValueError("Instance %s never ready for SSH" % instance_name) # Copy code if code_dir: shell_run_with_retry(COPY_CODE, retries=2, local_dir=code_dir, instance_name=instance_name) # Run setup if setup_command: tf.logging.info("Running setup on %s", instance_name) remote_run(setup_command, instance_name) # Run command tf.logging.info("Running command on %s", instance_name) remote_run(command, instance_name, detach=True)
[ "def", "launch_instance", "(", "instance_name", ",", "command", ",", "existing_ip", "=", "None", ",", "cpu", "=", "1", ",", "mem", "=", "4", ",", "code_dir", "=", "None", ",", "setup_command", "=", "None", ")", ":", "# Create instance", "ip", "=", "existing_ip", "or", "create_instance", "(", "instance_name", ",", "cpu", "=", "cpu", ",", "mem", "=", "mem", ")", "tf", ".", "logging", ".", "info", "(", "\"Waiting for SSH %s\"", ",", "instance_name", ")", "ready", "=", "wait_for_ssh", "(", "ip", ")", "if", "not", "ready", ":", "raise", "ValueError", "(", "\"Instance %s never ready for SSH\"", "%", "instance_name", ")", "# Copy code", "if", "code_dir", ":", "shell_run_with_retry", "(", "COPY_CODE", ",", "retries", "=", "2", ",", "local_dir", "=", "code_dir", ",", "instance_name", "=", "instance_name", ")", "# Run setup", "if", "setup_command", ":", "tf", ".", "logging", ".", "info", "(", "\"Running setup on %s\"", ",", "instance_name", ")", "remote_run", "(", "setup_command", ",", "instance_name", ")", "# Run command", "tf", ".", "logging", ".", "info", "(", "\"Running command on %s\"", ",", "instance_name", ")", "remote_run", "(", "command", ",", "instance_name", ",", "detach", "=", "True", ")" ]
Launch a GCE instance.
[ "Launch", "a", "GCE", "instance", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/wikisum/parallel_launch.py#L171-L198
22,847
tensorflow/tensor2tensor
tensor2tensor/models/evolved_transformer.py
_add_attend_to_encoder_cache
def _add_attend_to_encoder_cache(cache, attention_name, hparams, num_layers, key_channels, value_channels, vars_3d_num_heads, scope_prefix, encoder_output): """Add attend-to-encoder layers to cache.""" for layer in range(num_layers): layer_name = "layer_%d" % layer with tf.variable_scope("%sdecoder/%s/%s/multihead_attention" % (scope_prefix, layer_name, attention_name)): k_encdec = common_attention.compute_attention_component( encoder_output, key_channels, name="k", vars_3d_num_heads=vars_3d_num_heads) k_encdec = common_attention.split_heads(k_encdec, hparams.num_heads) v_encdec = common_attention.compute_attention_component( encoder_output, value_channels, name="v", vars_3d_num_heads=vars_3d_num_heads) v_encdec = common_attention.split_heads(v_encdec, hparams.num_heads) cache[layer_name][attention_name] = { "k_encdec": k_encdec, "v_encdec": v_encdec } return cache
python
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 range(num_layers): layer_name = "layer_%d" % layer with tf.variable_scope("%sdecoder/%s/%s/multihead_attention" % (scope_prefix, layer_name, attention_name)): k_encdec = common_attention.compute_attention_component( encoder_output, key_channels, name="k", vars_3d_num_heads=vars_3d_num_heads) k_encdec = common_attention.split_heads(k_encdec, hparams.num_heads) v_encdec = common_attention.compute_attention_component( encoder_output, value_channels, name="v", vars_3d_num_heads=vars_3d_num_heads) v_encdec = common_attention.split_heads(v_encdec, hparams.num_heads) cache[layer_name][attention_name] = { "k_encdec": k_encdec, "v_encdec": v_encdec } return cache
[ "def", "_add_attend_to_encoder_cache", "(", "cache", ",", "attention_name", ",", "hparams", ",", "num_layers", ",", "key_channels", ",", "value_channels", ",", "vars_3d_num_heads", ",", "scope_prefix", ",", "encoder_output", ")", ":", "for", "layer", "in", "range", "(", "num_layers", ")", ":", "layer_name", "=", "\"layer_%d\"", "%", "layer", "with", "tf", ".", "variable_scope", "(", "\"%sdecoder/%s/%s/multihead_attention\"", "%", "(", "scope_prefix", ",", "layer_name", ",", "attention_name", ")", ")", ":", "k_encdec", "=", "common_attention", ".", "compute_attention_component", "(", "encoder_output", ",", "key_channels", ",", "name", "=", "\"k\"", ",", "vars_3d_num_heads", "=", "vars_3d_num_heads", ")", "k_encdec", "=", "common_attention", ".", "split_heads", "(", "k_encdec", ",", "hparams", ".", "num_heads", ")", "v_encdec", "=", "common_attention", ".", "compute_attention_component", "(", "encoder_output", ",", "value_channels", ",", "name", "=", "\"v\"", ",", "vars_3d_num_heads", "=", "vars_3d_num_heads", ")", "v_encdec", "=", "common_attention", ".", "split_heads", "(", "v_encdec", ",", "hparams", ".", "num_heads", ")", "cache", "[", "layer_name", "]", "[", "attention_name", "]", "=", "{", "\"k_encdec\"", ":", "k_encdec", ",", "\"v_encdec\"", ":", "v_encdec", "}", "return", "cache" ]
Add attend-to-encoder layers to cache.
[ "Add", "attend", "-", "to", "-", "encoder", "layers", "to", "cache", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/evolved_transformer.py#L592-L617
22,848
tensorflow/tensor2tensor
tensor2tensor/models/evolved_transformer.py
_init_evolved_transformer_cache
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 decoding.""" key_channels = hparams.attention_key_channels or hparams.hidden_size value_channels = hparams.attention_value_channels or hparams.hidden_size num_layers = hparams.num_decoder_layers or hparams.num_hidden_layers vars_3d_num_heads = ( hparams.num_heads if hparams.get("attention_variables_3d") else 0) # Add self-attentions. if cache is None: cache = {} cache.update({ "layer_%d" % layer: { # pylint: disable=g-complex-comprehension _SIXTEEN_HEAD_ATTENTION_NAME: { "k": common_attention.split_heads( tf.zeros( [batch_size, attention_init_length, key_channels]), _capped_double_heads(hparams.num_heads)), "v": common_attention.split_heads( tf.zeros( [batch_size, attention_init_length, value_channels]), _capped_double_heads(hparams.num_heads)), }, _VANILLA_ATTENTION_NAME: { "k": common_attention.split_heads( tf.zeros( [batch_size, attention_init_length, key_channels]), hparams.num_heads), "v": common_attention.split_heads( tf.zeros( [batch_size, attention_init_length, value_channels]), hparams.num_heads), } } for layer in range(num_layers) }) # Add branched layers. Pad with additional zeros for causal convolution. for layer in range(num_layers): cache["layer_%d" % layer][_CONV_BRANCHES_FIRST_LAYER_NAME] = tf.zeros([ batch_size, attention_init_length + _DECODER_LEFT_CONV_PADDING, hparams.hidden_size ]) cache["layer_%d" % layer][_CONV_BRANCHES_SECOND_LAYER_NAME] = tf.zeros([ batch_size, attention_init_length + _DECODER_FINAL_CONV_PADDING, hparams.hidden_size * 2 ]) # Add encoder embedding attentions. if encoder_output is not None: cache = _add_attend_to_encoder_cache( cache=cache, attention_name=_FIRST_ATTEND_TO_ENCODER_NAME, hparams=hparams, num_layers=num_layers, key_channels=key_channels, value_channels=value_channels, vars_3d_num_heads=vars_3d_num_heads, scope_prefix=scope_prefix, encoder_output=encoder_output) cache = _add_attend_to_encoder_cache( cache=cache, attention_name=_SECOND_ATTEND_TO_ENCODER_NAME, hparams=hparams, num_layers=num_layers, key_channels=key_channels, value_channels=value_channels, vars_3d_num_heads=vars_3d_num_heads, scope_prefix=scope_prefix, encoder_output=encoder_output) cache["encoder_output"] = encoder_output cache["encoder_decoder_attention_bias"] = encoder_decoder_attention_bias return cache
python
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 decoding.""" key_channels = hparams.attention_key_channels or hparams.hidden_size value_channels = hparams.attention_value_channels or hparams.hidden_size num_layers = hparams.num_decoder_layers or hparams.num_hidden_layers vars_3d_num_heads = ( hparams.num_heads if hparams.get("attention_variables_3d") else 0) # Add self-attentions. if cache is None: cache = {} cache.update({ "layer_%d" % layer: { # pylint: disable=g-complex-comprehension _SIXTEEN_HEAD_ATTENTION_NAME: { "k": common_attention.split_heads( tf.zeros( [batch_size, attention_init_length, key_channels]), _capped_double_heads(hparams.num_heads)), "v": common_attention.split_heads( tf.zeros( [batch_size, attention_init_length, value_channels]), _capped_double_heads(hparams.num_heads)), }, _VANILLA_ATTENTION_NAME: { "k": common_attention.split_heads( tf.zeros( [batch_size, attention_init_length, key_channels]), hparams.num_heads), "v": common_attention.split_heads( tf.zeros( [batch_size, attention_init_length, value_channels]), hparams.num_heads), } } for layer in range(num_layers) }) # Add branched layers. Pad with additional zeros for causal convolution. for layer in range(num_layers): cache["layer_%d" % layer][_CONV_BRANCHES_FIRST_LAYER_NAME] = tf.zeros([ batch_size, attention_init_length + _DECODER_LEFT_CONV_PADDING, hparams.hidden_size ]) cache["layer_%d" % layer][_CONV_BRANCHES_SECOND_LAYER_NAME] = tf.zeros([ batch_size, attention_init_length + _DECODER_FINAL_CONV_PADDING, hparams.hidden_size * 2 ]) # Add encoder embedding attentions. if encoder_output is not None: cache = _add_attend_to_encoder_cache( cache=cache, attention_name=_FIRST_ATTEND_TO_ENCODER_NAME, hparams=hparams, num_layers=num_layers, key_channels=key_channels, value_channels=value_channels, vars_3d_num_heads=vars_3d_num_heads, scope_prefix=scope_prefix, encoder_output=encoder_output) cache = _add_attend_to_encoder_cache( cache=cache, attention_name=_SECOND_ATTEND_TO_ENCODER_NAME, hparams=hparams, num_layers=num_layers, key_channels=key_channels, value_channels=value_channels, vars_3d_num_heads=vars_3d_num_heads, scope_prefix=scope_prefix, encoder_output=encoder_output) cache["encoder_output"] = encoder_output cache["encoder_decoder_attention_bias"] = encoder_decoder_attention_bias return cache
[ "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_channels", "or", "hparams", ".", "hidden_size", "value_channels", "=", "hparams", ".", "attention_value_channels", "or", "hparams", ".", "hidden_size", "num_layers", "=", "hparams", ".", "num_decoder_layers", "or", "hparams", ".", "num_hidden_layers", "vars_3d_num_heads", "=", "(", "hparams", ".", "num_heads", "if", "hparams", ".", "get", "(", "\"attention_variables_3d\"", ")", "else", "0", ")", "# Add self-attentions.", "if", "cache", "is", "None", ":", "cache", "=", "{", "}", "cache", ".", "update", "(", "{", "\"layer_%d\"", "%", "layer", ":", "{", "# pylint: disable=g-complex-comprehension", "_SIXTEEN_HEAD_ATTENTION_NAME", ":", "{", "\"k\"", ":", "common_attention", ".", "split_heads", "(", "tf", ".", "zeros", "(", "[", "batch_size", ",", "attention_init_length", ",", "key_channels", "]", ")", ",", "_capped_double_heads", "(", "hparams", ".", "num_heads", ")", ")", ",", "\"v\"", ":", "common_attention", ".", "split_heads", "(", "tf", ".", "zeros", "(", "[", "batch_size", ",", "attention_init_length", ",", "value_channels", "]", ")", ",", "_capped_double_heads", "(", "hparams", ".", "num_heads", ")", ")", ",", "}", ",", "_VANILLA_ATTENTION_NAME", ":", "{", "\"k\"", ":", "common_attention", ".", "split_heads", "(", "tf", ".", "zeros", "(", "[", "batch_size", ",", "attention_init_length", ",", "key_channels", "]", ")", ",", "hparams", ".", "num_heads", ")", ",", "\"v\"", ":", "common_attention", ".", "split_heads", "(", "tf", ".", "zeros", "(", "[", "batch_size", ",", "attention_init_length", ",", "value_channels", "]", ")", ",", "hparams", ".", "num_heads", ")", ",", "}", "}", "for", "layer", "in", "range", "(", "num_layers", ")", "}", ")", "# Add branched layers. Pad with additional zeros for causal convolution.", "for", "layer", "in", "range", "(", "num_layers", ")", ":", "cache", "[", "\"layer_%d\"", "%", "layer", "]", "[", "_CONV_BRANCHES_FIRST_LAYER_NAME", "]", "=", "tf", ".", "zeros", "(", "[", "batch_size", ",", "attention_init_length", "+", "_DECODER_LEFT_CONV_PADDING", ",", "hparams", ".", "hidden_size", "]", ")", "cache", "[", "\"layer_%d\"", "%", "layer", "]", "[", "_CONV_BRANCHES_SECOND_LAYER_NAME", "]", "=", "tf", ".", "zeros", "(", "[", "batch_size", ",", "attention_init_length", "+", "_DECODER_FINAL_CONV_PADDING", ",", "hparams", ".", "hidden_size", "*", "2", "]", ")", "# Add encoder embedding attentions.", "if", "encoder_output", "is", "not", "None", ":", "cache", "=", "_add_attend_to_encoder_cache", "(", "cache", "=", "cache", ",", "attention_name", "=", "_FIRST_ATTEND_TO_ENCODER_NAME", ",", "hparams", "=", "hparams", ",", "num_layers", "=", "num_layers", ",", "key_channels", "=", "key_channels", ",", "value_channels", "=", "value_channels", ",", "vars_3d_num_heads", "=", "vars_3d_num_heads", ",", "scope_prefix", "=", "scope_prefix", ",", "encoder_output", "=", "encoder_output", ")", "cache", "=", "_add_attend_to_encoder_cache", "(", "cache", "=", "cache", ",", "attention_name", "=", "_SECOND_ATTEND_TO_ENCODER_NAME", ",", "hparams", "=", "hparams", ",", "num_layers", "=", "num_layers", ",", "key_channels", "=", "key_channels", ",", "value_channels", "=", "value_channels", ",", "vars_3d_num_heads", "=", "vars_3d_num_heads", ",", "scope_prefix", "=", "scope_prefix", ",", "encoder_output", "=", "encoder_output", ")", "cache", "[", "\"encoder_output\"", "]", "=", "encoder_output", "cache", "[", "\"encoder_decoder_attention_bias\"", "]", "=", "encoder_decoder_attention_bias", "return", "cache" ]
Create the initial cache for Evolved Transformer fast decoding.
[ "Create", "the", "initial", "cache", "for", "Evolved", "Transformer", "fast", "decoding", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/evolved_transformer.py#L620-L700
22,849
tensorflow/tensor2tensor
tensor2tensor/models/evolved_transformer.py
add_evolved_transformer_hparams
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" 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 hparams.num_decoder_layers = 4 # Learning rate and decay scheme that mimics the transformer Adam config, # but with cosine decay instead of rsqrt. hparams.learning_rate_constant /= hparams.learning_rate_warmup_steps ** 0.5 hparams.learning_rate_schedule = ( "constant*linear_warmup*single_cycle_cos_decay*rsqrt_hidden_size") # The current infrastructure does not support exposing # `train_steps` to the decay functions, and so we are hard coding the decay # steps here to match the default number of train steps used in `t2t_trainer`. # TODO(davidso): Thread `train_steps` through to decay functions so we do not # have to worry about a `learning_rate_decay_steps` mismatch. hparams.learning_rate_decay_steps = 250000 return hparams
python
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" 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 hparams.num_decoder_layers = 4 # Learning rate and decay scheme that mimics the transformer Adam config, # but with cosine decay instead of rsqrt. hparams.learning_rate_constant /= hparams.learning_rate_warmup_steps ** 0.5 hparams.learning_rate_schedule = ( "constant*linear_warmup*single_cycle_cos_decay*rsqrt_hidden_size") # The current infrastructure does not support exposing # `train_steps` to the decay functions, and so we are hard coding the decay # steps here to match the default number of train steps used in `t2t_trainer`. # TODO(davidso): Thread `train_steps` through to decay functions so we do not # have to worry about a `learning_rate_decay_steps` mismatch. hparams.learning_rate_decay_steps = 250000 return hparams
[ "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", "hparams", ".", "num_decoder_layers", "=", "4", "# Learning rate and decay scheme that mimics the transformer Adam config,", "# but with cosine decay instead of rsqrt.", "hparams", ".", "learning_rate_constant", "/=", "hparams", ".", "learning_rate_warmup_steps", "**", "0.5", "hparams", ".", "learning_rate_schedule", "=", "(", "\"constant*linear_warmup*single_cycle_cos_decay*rsqrt_hidden_size\"", ")", "# The current infrastructure does not support exposing", "# `train_steps` to the decay functions, and so we are hard coding the decay", "# steps here to match the default number of train steps used in `t2t_trainer`.", "# TODO(davidso): Thread `train_steps` through to decay functions so we do not", "# have to worry about a `learning_rate_decay_steps` mismatch.", "hparams", ".", "learning_rate_decay_steps", "=", "250000", "return", "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.
[ "Add", "Evolved", "Transformer", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/evolved_transformer.py#L704-L733
22,850
tensorflow/tensor2tensor
tensor2tensor/models/evolved_transformer.py
evolved_transformer_base_tpu
def evolved_transformer_base_tpu(): """Base parameters for Evolved Transformer model on TPU.""" hparams = add_evolved_transformer_hparams(transformer.transformer_tpu()) hparams.learning_rate_constant = 1 / hparams.learning_rate_warmup_steps ** 0.5 hparams.learning_rate_schedule = ( "constant*single_cycle_cos_decay") return hparams
python
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_cos_decay") return hparams
[ "def", "evolved_transformer_base_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_cos_decay\"", ")", "return", "hparams" ]
Base parameters for Evolved Transformer model on TPU.
[ "Base", "parameters", "for", "Evolved", "Transformer", "model", "on", "TPU", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/evolved_transformer.py#L749-L755
22,851
tensorflow/tensor2tensor
tensor2tensor/models/evolved_transformer.py
evolved_transformer_big_tpu
def evolved_transformer_big_tpu(): """Big parameters for Evolved Transformer model on TPU.""" hparams = add_evolved_transformer_hparams(transformer.transformer_big_tpu()) hparams.learning_rate_constant = 1 / hparams.learning_rate_warmup_steps ** 0.5 hparams.learning_rate_schedule = ( "constant*single_cycle_cos_decay") return hparams
python
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_cycle_cos_decay") return hparams
[ "def", "evolved_transformer_big_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_cycle_cos_decay\"", ")", "return", "hparams" ]
Big parameters for Evolved Transformer model on TPU.
[ "Big", "parameters", "for", "Evolved", "Transformer", "model", "on", "TPU", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/evolved_transformer.py#L759-L765
22,852
tensorflow/tensor2tensor
tensor2tensor/models/research/moe.py
set_default_moe_hparams
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 balanced. # moe_capacity_factor_* should be set to a value >=1. hparams.add_hparam("moe_capacity_factor_train", 1.25) hparams.add_hparam("moe_capacity_factor_eval", 2.0) hparams.add_hparam("moe_capacity_factor_second_level", 1.0) # Each expert has a hidden layer with this size. hparams.add_hparam("moe_hidden_size", 4096) # For gating, divide inputs into groups of this size before gating. # Each group sends the same number of inputs to each expert. # Ideally, the group size would be the whole batch, but this is expensive # due to our use of matrix multiplication for reordering. hparams.add_hparam("moe_group_size", 1024) # For top_2 gating, whether to impose an additional loss in order to make # the experts equally used as the second-place expert. hparams.add_hparam("moe_use_second_place_loss", 0) # In top_2 gating, policy for whether to use a second-place expert. # Legal values are: # "all": always # "none": never # "threshold": if gate value > the given threshold # "random": if gate value > threshold*random_uniform(0,1) hparams.add_hparam("moe_second_policy_train", "random") hparams.add_hparam("moe_second_policy_eval", "random") hparams.add_hparam("moe_second_threshold_train", 0.2) hparams.add_hparam("moe_second_threshold_eval", 0.2)
python
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 balanced. # moe_capacity_factor_* should be set to a value >=1. hparams.add_hparam("moe_capacity_factor_train", 1.25) hparams.add_hparam("moe_capacity_factor_eval", 2.0) hparams.add_hparam("moe_capacity_factor_second_level", 1.0) # Each expert has a hidden layer with this size. hparams.add_hparam("moe_hidden_size", 4096) # For gating, divide inputs into groups of this size before gating. # Each group sends the same number of inputs to each expert. # Ideally, the group size would be the whole batch, but this is expensive # due to our use of matrix multiplication for reordering. hparams.add_hparam("moe_group_size", 1024) # For top_2 gating, whether to impose an additional loss in order to make # the experts equally used as the second-place expert. hparams.add_hparam("moe_use_second_place_loss", 0) # In top_2 gating, policy for whether to use a second-place expert. # Legal values are: # "all": always # "none": never # "threshold": if gate value > the given threshold # "random": if gate value > threshold*random_uniform(0,1) hparams.add_hparam("moe_second_policy_train", "random") hparams.add_hparam("moe_second_policy_eval", "random") hparams.add_hparam("moe_second_threshold_train", 0.2) hparams.add_hparam("moe_second_threshold_eval", 0.2)
[ "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. We need some extra capacity", "# in case gating is not perfectly balanced.", "# moe_capacity_factor_* should be set to a value >=1.", "hparams", ".", "add_hparam", "(", "\"moe_capacity_factor_train\"", ",", "1.25", ")", "hparams", ".", "add_hparam", "(", "\"moe_capacity_factor_eval\"", ",", "2.0", ")", "hparams", ".", "add_hparam", "(", "\"moe_capacity_factor_second_level\"", ",", "1.0", ")", "# Each expert has a hidden layer with this size.", "hparams", ".", "add_hparam", "(", "\"moe_hidden_size\"", ",", "4096", ")", "# For gating, divide inputs into groups of this size before gating.", "# Each group sends the same number of inputs to each expert.", "# Ideally, the group size would be the whole batch, but this is expensive", "# due to our use of matrix multiplication for reordering.", "hparams", ".", "add_hparam", "(", "\"moe_group_size\"", ",", "1024", ")", "# For top_2 gating, whether to impose an additional loss in order to make", "# the experts equally used as the second-place expert.", "hparams", ".", "add_hparam", "(", "\"moe_use_second_place_loss\"", ",", "0", ")", "# In top_2 gating, policy for whether to use a second-place expert.", "# Legal values are:", "# \"all\": always", "# \"none\": never", "# \"threshold\": if gate value > the given threshold", "# \"random\": if gate value > threshold*random_uniform(0,1)", "hparams", ".", "add_hparam", "(", "\"moe_second_policy_train\"", ",", "\"random\"", ")", "hparams", ".", "add_hparam", "(", "\"moe_second_policy_eval\"", ",", "\"random\"", ")", "hparams", ".", "add_hparam", "(", "\"moe_second_threshold_train\"", ",", "0.2", ")", "hparams", ".", "add_hparam", "(", "\"moe_second_threshold_eval\"", ",", "0.2", ")" ]
Add necessary hyperparameters for mixture-of-experts.
[ "Add", "necessary", "hyperparameters", "for", "mixture", "-", "of", "-", "experts", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe.py#L613-L643
22,853
tensorflow/tensor2tensor
tensor2tensor/models/research/moe.py
_split_into_groups
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: group_size <= max_group_size (num_groups = n/group_size) is a multiple of mesh_dim_size Args: n: an integer max_group_size: an integer mesh_dim_size: an integer Returns: num_groups: an integer group_size: an integer Raises: ValueError: if n is not a multiple of 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)) num_groups = max(1, n // max_group_size) while (num_groups % mesh_dim_size != 0 or n % num_groups != 0): num_groups += 1 group_size = n // num_groups tf.logging.info( "_split_into_groups(n=%d, max_group_size=%d, mesh_dim_size=%d)" " = (num_groups=%d group_size=%d)" % (n, max_group_size, mesh_dim_size, num_groups, group_size)) return num_groups, group_size
python
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: group_size <= max_group_size (num_groups = n/group_size) is a multiple of mesh_dim_size Args: n: an integer max_group_size: an integer mesh_dim_size: an integer Returns: num_groups: an integer group_size: an integer Raises: ValueError: if n is not a multiple of 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)) num_groups = max(1, n // max_group_size) while (num_groups % mesh_dim_size != 0 or n % num_groups != 0): num_groups += 1 group_size = n // num_groups tf.logging.info( "_split_into_groups(n=%d, max_group_size=%d, mesh_dim_size=%d)" " = (num_groups=%d group_size=%d)" % (n, max_group_size, mesh_dim_size, num_groups, group_size)) return num_groups, group_size
[ "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", ")", ")", "num_groups", "=", "max", "(", "1", ",", "n", "//", "max_group_size", ")", "while", "(", "num_groups", "%", "mesh_dim_size", "!=", "0", "or", "n", "%", "num_groups", "!=", "0", ")", ":", "num_groups", "+=", "1", "group_size", "=", "n", "//", "num_groups", "tf", ".", "logging", ".", "info", "(", "\"_split_into_groups(n=%d, max_group_size=%d, mesh_dim_size=%d)\"", "\" = (num_groups=%d group_size=%d)\"", "%", "(", "n", ",", "max_group_size", ",", "mesh_dim_size", ",", "num_groups", ",", "group_size", ")", ")", "return", "num_groups", ",", "group_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: group_size <= max_group_size (num_groups = n/group_size) is a multiple of mesh_dim_size Args: n: an integer max_group_size: an integer mesh_dim_size: an integer Returns: num_groups: an integer group_size: an integer Raises: ValueError: if n is not a multiple of mesh_dim_size
[ "Helper", "function", "for", "figuring", "out", "how", "to", "split", "a", "dimensino", "into", "groups", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/moe.py#L646-L679
22,854
tensorflow/tensor2tensor
tensor2tensor/utils/registry.py
_nargs_validator
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.varargs is not None or spec.varkw is not None): raise ValueError(message) return f
python
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.varargs is not None or spec.varkw is not None): raise ValueError(message) return f
[ "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", "=", "inspect", ".", "getfullargspec", "(", "value", ")", "if", "(", "len", "(", "spec", ".", "args", ")", "!=", "nargs", "or", "spec", ".", "varargs", "is", "not", "None", "or", "spec", ".", "varkw", "is", "not", "None", ")", ":", "raise", "ValueError", "(", "message", ")", "return", "f" ]
Makes validator for function to ensure it takes nargs args.
[ "Makes", "validator", "for", "function", "to", "ensure", "it", "takes", "nargs", "args", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/registry.py#L287-L299
22,855
tensorflow/tensor2tensor
tensor2tensor/utils/registry.py
optimizer
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, though others supported for legacy reasons. Returns: optimizer """ warn_msg = ("Please update `registry.optimizer` callsite " "(likely due to a `HParams.optimizer` value)") if name == "SGD": name = "sgd" tf.logging.warning("'SGD' optimizer now keyed by 'sgd'. %s" % warn_msg) elif name == "RMSProp": name = "rms_prop" tf.logging.warning( "'RMSProp' optimizer now keyed by 'rms_prop'. %s" % warn_msg) else: snake_name = misc_utils.camelcase_to_snakecase(name) if name != snake_name: tf.logging.warning( "optimizer names now keyed by snake_case names. %s" % warn_msg) name = snake_name return Registries.optimizers[name]
python
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, though others supported for legacy reasons. Returns: optimizer """ warn_msg = ("Please update `registry.optimizer` callsite " "(likely due to a `HParams.optimizer` value)") if name == "SGD": name = "sgd" tf.logging.warning("'SGD' optimizer now keyed by 'sgd'. %s" % warn_msg) elif name == "RMSProp": name = "rms_prop" tf.logging.warning( "'RMSProp' optimizer now keyed by 'rms_prop'. %s" % warn_msg) else: snake_name = misc_utils.camelcase_to_snakecase(name) if name != snake_name: tf.logging.warning( "optimizer names now keyed by snake_case names. %s" % warn_msg) name = snake_name return Registries.optimizers[name]
[ "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", "(", "\"'SGD' optimizer now keyed by 'sgd'. %s\"", "%", "warn_msg", ")", "elif", "name", "==", "\"RMSProp\"", ":", "name", "=", "\"rms_prop\"", "tf", ".", "logging", ".", "warning", "(", "\"'RMSProp' optimizer now keyed by 'rms_prop'. %s\"", "%", "warn_msg", ")", "else", ":", "snake_name", "=", "misc_utils", ".", "camelcase_to_snakecase", "(", "name", ")", "if", "name", "!=", "snake_name", ":", "tf", ".", "logging", ".", "warning", "(", "\"optimizer names now keyed by snake_case names. %s\"", "%", "warn_msg", ")", "name", "=", "snake_name", "return", "Registries", ".", "optimizers", "[", "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, though others supported for legacy reasons. Returns: optimizer
[ "Get", "pre", "-", "registered", "optimizer", "keyed", "by", "name", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/registry.py#L435-L463
22,856
tensorflow/tensor2tensor
tensor2tensor/utils/registry.py
env_problem
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 size. """ ep_cls = Registries.env_problems[env_problem_name] ep = ep_cls() ep.initialize(**kwargs) return ep
python
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 size. """ ep_cls = Registries.env_problems[env_problem_name] ep = ep_cls() ep.initialize(**kwargs) return ep
[ "def", "env_problem", "(", "env_problem_name", ",", "*", "*", "kwargs", ")", ":", "ep_cls", "=", "Registries", ".", "env_problems", "[", "env_problem_name", "]", "ep", "=", "ep_cls", "(", ")", "ep", ".", "initialize", "(", "*", "*", "kwargs", ")", "return", "ep" ]
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.
[ "Get", "and", "initialize", "the", "EnvProblem", "with", "the", "given", "name", "and", "batch", "size", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/registry.py#L516-L530
22,857
tensorflow/tensor2tensor
tensor2tensor/utils/registry.py
display_list_by_prefix
def display_list_by_prefix(names_list, starting_spaces=0): """Creates a help string for names_list grouped by prefix.""" cur_prefix, result_lines = None, [] space = " " * starting_spaces for name in sorted(names_list): split = name.split("_", 1) prefix = split[0] if cur_prefix != prefix: result_lines.append(space + prefix + ":") cur_prefix = prefix result_lines.append(space + " * " + name) return "\n".join(result_lines)
python
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: result_lines.append(space + prefix + ":") cur_prefix = prefix result_lines.append(space + " * " + name) return "\n".join(result_lines)
[ "def", "display_list_by_prefix", "(", "names_list", ",", "starting_spaces", "=", "0", ")", ":", "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", ":", "result_lines", ".", "append", "(", "space", "+", "prefix", "+", "\":\"", ")", "cur_prefix", "=", "prefix", "result_lines", ".", "append", "(", "space", "+", "\" * \"", "+", "name", ")", "return", "\"\\n\"", ".", "join", "(", "result_lines", ")" ]
Creates a help string for names_list grouped by prefix.
[ "Creates", "a", "help", "string", "for", "names_list", "grouped", "by", "prefix", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/registry.py#L557-L568
22,858
tensorflow/tensor2tensor
tensor2tensor/utils/registry.py
help_string
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 """ lists = tuple( display_list_by_prefix(entries, starting_spaces=4) for entries in [ # pylint: disable=g-complex-comprehension list_models(), list_hparams(), list_ranged_hparams(), list_base_problems(), list_optimizers(), list_attacks(), list_attack_params(), list_pruning_params(), list_pruning_strategies(), list_env_problems(), ]) return help_str % lists
python
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 """ lists = tuple( display_list_by_prefix(entries, starting_spaces=4) for entries in [ # pylint: disable=g-complex-comprehension list_models(), list_hparams(), list_ranged_hparams(), list_base_problems(), list_optimizers(), list_attacks(), list_attack_params(), list_pruning_params(), list_pruning_strategies(), list_env_problems(), ]) return help_str % lists
[ "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 Env Problems:\n%s\n\"\"\"", "lists", "=", "tuple", "(", "display_list_by_prefix", "(", "entries", ",", "starting_spaces", "=", "4", ")", "for", "entries", "in", "[", "# pylint: disable=g-complex-comprehension", "list_models", "(", ")", ",", "list_hparams", "(", ")", ",", "list_ranged_hparams", "(", ")", ",", "list_base_problems", "(", ")", ",", "list_optimizers", "(", ")", ",", "list_attacks", "(", ")", ",", "list_attack_params", "(", ")", ",", "list_pruning_params", "(", ")", ",", "list_pruning_strategies", "(", ")", ",", "list_env_problems", "(", ")", ",", "]", ")", "return", "help_str", "%", "lists" ]
Generate help string with contents of registry.
[ "Generate", "help", "string", "with", "contents", "of", "registry", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/registry.py#L571-L620
22,859
tensorflow/tensor2tensor
tensor2tensor/utils/registry.py
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() def another_fn(x, y): pass @my_registry.register def third_func(): pass ``` Note if key_or_value is provided as a non-callable, registration only occurs once the returned callback is called with a callable as its only argument. ```python callback = my_registry.register('different_key') 'different_key' in my_registry # False callback(lambda (x, y): x + y) 'different_key' in my_registry # True ``` Args: key_or_value (optional): key to access the registered value with, or the function itself. If `None` (default), `self.default_key` will be called on `value` once the returned callback is called with `value` as the only arg. If `key_or_value` is itself callable, it is assumed to be the value and the key is given by `self.default_key(key)`. Returns: decorated callback, or callback generated a decorated function. """ def decorator(value, key): self[key] = value return value # Handle if decorator was used without parens if callable(key_or_value): return decorator(value=key_or_value, key=None) else: return lambda value: decorator(value, key=key_or_value)
python
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 another_fn(x, y): pass @my_registry.register def third_func(): pass ``` Note if key_or_value is provided as a non-callable, registration only occurs once the returned callback is called with a callable as its only argument. ```python callback = my_registry.register('different_key') 'different_key' in my_registry # False callback(lambda (x, y): x + y) 'different_key' in my_registry # True ``` Args: key_or_value (optional): key to access the registered value with, or the function itself. If `None` (default), `self.default_key` will be called on `value` once the returned callback is called with `value` as the only arg. If `key_or_value` is itself callable, it is assumed to be the value and the key is given by `self.default_key(key)`. Returns: decorated callback, or callback generated a decorated function. """ def decorator(value, key): self[key] = value return value # Handle if decorator was used without parens if callable(key_or_value): return decorator(value=key_or_value, key=None) else: return lambda value: decorator(value, key=key_or_value)
[ "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", "(", "key_or_value", ")", ":", "return", "decorator", "(", "value", "=", "key_or_value", ",", "key", "=", "None", ")", "else", ":", "return", "lambda", "value", ":", "decorator", "(", "value", ",", "key", "=", "key_or_value", ")" ]
Decorator to register a function, or registration itself. This is primarily intended for use as a decorator, either with or without a key/parentheses. ```python @my_registry.register('key1') def value_fn(x, y, z): pass @my_registry.register() def another_fn(x, y): pass @my_registry.register def third_func(): pass ``` Note if key_or_value is provided as a non-callable, registration only occurs once the returned callback is called with a callable as its only argument. ```python callback = my_registry.register('different_key') 'different_key' in my_registry # False callback(lambda (x, y): x + y) 'different_key' in my_registry # True ``` Args: key_or_value (optional): key to access the registered value with, or the function itself. If `None` (default), `self.default_key` will be called on `value` once the returned callback is called with `value` as the only arg. If `key_or_value` is itself callable, it is assumed to be the value and the key is given by `self.default_key(key)`. Returns: decorated callback, or callback generated a decorated function.
[ "Decorator", "to", "register", "a", "function", "or", "registration", "itself", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/registry.py#L201-L249
22,860
Microsoft/LightGBM
helpers/check_dynamic_dependencies.py
check_dependicies
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]+') versions = GLIBC_version.findall(objdump_string) assert len(versions) > 1 for major, minor in versions: assert int(major) <= 2 assert int(minor) <= 14 GLIBCXX_version = re.compile(r'0{16}[ \t]+GLIBCXX_(\d{1,2})[.](\d{1,2})[.]?(\d{,3})[ \t]+') versions = GLIBCXX_version.findall(objdump_string) assert len(versions) > 1 for major, minor, patch in versions: assert int(major) == 3 assert int(minor) == 4 assert patch == '' or int(patch) <= 19 GOMP_version = re.compile(r'0{16}[ \t]+G?OMP_(\d{1,2})[.](\d{1,2})[.]?\d{,3}[ \t]+') versions = GOMP_version.findall(objdump_string) assert len(versions) > 1 for major, minor in versions: assert int(major) == 1 assert int(minor) == 0
python
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]+') versions = GLIBC_version.findall(objdump_string) assert len(versions) > 1 for major, minor in versions: assert int(major) <= 2 assert int(minor) <= 14 GLIBCXX_version = re.compile(r'0{16}[ \t]+GLIBCXX_(\d{1,2})[.](\d{1,2})[.]?(\d{,3})[ \t]+') versions = GLIBCXX_version.findall(objdump_string) assert len(versions) > 1 for major, minor, patch in versions: assert int(major) == 3 assert int(minor) == 4 assert patch == '' or int(patch) <= 19 GOMP_version = re.compile(r'0{16}[ \t]+G?OMP_(\d{1,2})[.](\d{1,2})[.]?\d{,3}[ \t]+') versions = GOMP_version.findall(objdump_string) assert len(versions) > 1 for major, minor in versions: assert int(major) == 1 assert int(minor) == 0
[ "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", "len", "(", "versions", ")", ">", "1", "for", "major", ",", "minor", "in", "versions", ":", "assert", "int", "(", "major", ")", "<=", "2", "assert", "int", "(", "minor", ")", "<=", "14", "GLIBCXX_version", "=", "re", ".", "compile", "(", "r'0{16}[ \\t]+GLIBCXX_(\\d{1,2})[.](\\d{1,2})[.]?(\\d{,3})[ \\t]+'", ")", "versions", "=", "GLIBCXX_version", ".", "findall", "(", "objdump_string", ")", "assert", "len", "(", "versions", ")", ">", "1", "for", "major", ",", "minor", ",", "patch", "in", "versions", ":", "assert", "int", "(", "major", ")", "==", "3", "assert", "int", "(", "minor", ")", "==", "4", "assert", "patch", "==", "''", "or", "int", "(", "patch", ")", "<=", "19", "GOMP_version", "=", "re", ".", "compile", "(", "r'0{16}[ \\t]+G?OMP_(\\d{1,2})[.](\\d{1,2})[.]?\\d{,3}[ \\t]+'", ")", "versions", "=", "GOMP_version", ".", "findall", "(", "objdump_string", ")", "assert", "len", "(", "versions", ")", ">", "1", "for", "major", ",", "minor", "in", "versions", ":", "assert", "int", "(", "major", ")", "==", "1", "assert", "int", "(", "minor", ")", "==", "0" ]
Check the dynamic symbol versions. Parameters ---------- objdump_string : string The dynamic symbol table entries of the file (result of `objdump -T` command).
[ "Check", "the", "dynamic", "symbol", "versions", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/helpers/check_dynamic_dependencies.py#L10-L38
22,861
Microsoft/LightGBM
python-package/lightgbm/sklearn.py
_objective_function_wrapper
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 in this way as well. Parameters ---------- func : callable Expects a callable with signature ``func(y_true, y_pred)`` or ``func(y_true, y_pred, group): y_true : array-like of shape = [n_samples] The target values. y_pred : array-like of shape = [n_samples] or shape = [n_samples * n_classes] (for multi-class task) The predicted values. group : array-like Group/query data, used for ranking task. Returns ------- new_func : callable The new objective function as expected by ``lightgbm.engine.train``. The signature is ``new_func(preds, dataset)``: preds : array-like of shape = [n_samples] or shape = [n_samples * n_classes] (for multi-class task) The predicted values. dataset : Dataset The training set from which the labels will be extracted using ``dataset.get_label()``. """ def inner(preds, dataset): """Call passed function with appropriate arguments.""" labels = dataset.get_label() argc = argc_(func) if argc == 2: grad, hess = func(labels, preds) elif argc == 3: grad, hess = func(labels, preds, dataset.get_group()) else: raise TypeError("Self-defined objective function should have 2 or 3 arguments, got %d" % argc) """weighted for objective""" weight = dataset.get_weight() if weight is not None: """only one class""" if len(weight) == len(grad): grad = np.multiply(grad, weight) hess = np.multiply(hess, weight) else: num_data = len(weight) num_class = len(grad) // num_data if num_class * num_data != len(grad): raise ValueError("Length of grad and hess should equal to num_class * num_data") for k in range_(num_class): for i in range_(num_data): idx = k * num_data + i grad[idx] *= weight[i] hess[idx] *= weight[i] return grad, hess return inner
python
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 in this way as well. Parameters ---------- func : callable Expects a callable with signature ``func(y_true, y_pred)`` or ``func(y_true, y_pred, group): y_true : array-like of shape = [n_samples] The target values. y_pred : array-like of shape = [n_samples] or shape = [n_samples * n_classes] (for multi-class task) The predicted values. group : array-like Group/query data, used for ranking task. Returns ------- new_func : callable The new objective function as expected by ``lightgbm.engine.train``. The signature is ``new_func(preds, dataset)``: preds : array-like of shape = [n_samples] or shape = [n_samples * n_classes] (for multi-class task) The predicted values. dataset : Dataset The training set from which the labels will be extracted using ``dataset.get_label()``. """ def inner(preds, dataset): """Call passed function with appropriate arguments.""" labels = dataset.get_label() argc = argc_(func) if argc == 2: grad, hess = func(labels, preds) elif argc == 3: grad, hess = func(labels, preds, dataset.get_group()) else: raise TypeError("Self-defined objective function should have 2 or 3 arguments, got %d" % argc) """weighted for objective""" weight = dataset.get_weight() if weight is not None: """only one class""" if len(weight) == len(grad): grad = np.multiply(grad, weight) hess = np.multiply(hess, weight) else: num_data = len(weight) num_class = len(grad) // num_data if num_class * num_data != len(grad): raise ValueError("Length of grad and hess should equal to num_class * num_data") for k in range_(num_class): for i in range_(num_data): idx = k * num_data + i grad[idx] *= weight[i] hess[idx] *= weight[i] return grad, hess return inner
[ "def", "_objective_function_wrapper", "(", "func", ")", ":", "def", "inner", "(", "preds", ",", "dataset", ")", ":", "\"\"\"Call passed function with appropriate arguments.\"\"\"", "labels", "=", "dataset", ".", "get_label", "(", ")", "argc", "=", "argc_", "(", "func", ")", "if", "argc", "==", "2", ":", "grad", ",", "hess", "=", "func", "(", "labels", ",", "preds", ")", "elif", "argc", "==", "3", ":", "grad", ",", "hess", "=", "func", "(", "labels", ",", "preds", ",", "dataset", ".", "get_group", "(", ")", ")", "else", ":", "raise", "TypeError", "(", "\"Self-defined objective function should have 2 or 3 arguments, got %d\"", "%", "argc", ")", "\"\"\"weighted for objective\"\"\"", "weight", "=", "dataset", ".", "get_weight", "(", ")", "if", "weight", "is", "not", "None", ":", "\"\"\"only one class\"\"\"", "if", "len", "(", "weight", ")", "==", "len", "(", "grad", ")", ":", "grad", "=", "np", ".", "multiply", "(", "grad", ",", "weight", ")", "hess", "=", "np", ".", "multiply", "(", "hess", ",", "weight", ")", "else", ":", "num_data", "=", "len", "(", "weight", ")", "num_class", "=", "len", "(", "grad", ")", "//", "num_data", "if", "num_class", "*", "num_data", "!=", "len", "(", "grad", ")", ":", "raise", "ValueError", "(", "\"Length of grad and hess should equal to num_class * num_data\"", ")", "for", "k", "in", "range_", "(", "num_class", ")", ":", "for", "i", "in", "range_", "(", "num_data", ")", ":", "idx", "=", "k", "*", "num_data", "+", "i", "grad", "[", "idx", "]", "*=", "weight", "[", "i", "]", "hess", "[", "idx", "]", "*=", "weight", "[", "i", "]", "return", "grad", ",", "hess", "return", "inner" ]
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 ---------- func : callable Expects a callable with signature ``func(y_true, y_pred)`` or ``func(y_true, y_pred, group): y_true : array-like of shape = [n_samples] The target values. y_pred : array-like of shape = [n_samples] or shape = [n_samples * n_classes] (for multi-class task) The predicted values. group : array-like Group/query data, used for ranking task. Returns ------- new_func : callable The new objective function as expected by ``lightgbm.engine.train``. The signature is ``new_func(preds, dataset)``: preds : array-like of shape = [n_samples] or shape = [n_samples * n_classes] (for multi-class task) The predicted values. dataset : Dataset The training set from which the labels will be extracted using ``dataset.get_label()``.
[ "Decorate", "an", "objective", "function", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/sklearn.py#L18-L78
22,862
Microsoft/LightGBM
python-package/lightgbm/sklearn.py
_eval_function_wrapper
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 : callable Expects a callable with following signatures: ``func(y_true, y_pred)``, ``func(y_true, y_pred, weight)`` or ``func(y_true, y_pred, weight, group)`` and returns (eval_name->string, eval_result->float, is_bigger_better->bool): y_true : array-like of shape = [n_samples] The target values. y_pred : array-like of shape = [n_samples] or shape = [n_samples * n_classes] (for multi-class task) The predicted values. weight : array-like of shape = [n_samples] The weight of samples. group : array-like Group/query data, used for ranking task. Returns ------- new_func : callable The new eval function as expected by ``lightgbm.engine.train``. The signature is ``new_func(preds, dataset)``: preds : array-like of shape = [n_samples] or shape = [n_samples * n_classes] (for multi-class task) The predicted values. dataset : Dataset The training set from which the labels will be extracted using ``dataset.get_label()``. """ def inner(preds, dataset): """Call passed function with appropriate arguments.""" labels = dataset.get_label() argc = argc_(func) if argc == 2: return func(labels, preds) elif argc == 3: return func(labels, preds, dataset.get_weight()) elif argc == 4: return func(labels, preds, dataset.get_weight(), dataset.get_group()) else: raise TypeError("Self-defined eval function should have 2, 3 or 4 arguments, got %d" % argc) return inner
python
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 : callable Expects a callable with following signatures: ``func(y_true, y_pred)``, ``func(y_true, y_pred, weight)`` or ``func(y_true, y_pred, weight, group)`` and returns (eval_name->string, eval_result->float, is_bigger_better->bool): y_true : array-like of shape = [n_samples] The target values. y_pred : array-like of shape = [n_samples] or shape = [n_samples * n_classes] (for multi-class task) The predicted values. weight : array-like of shape = [n_samples] The weight of samples. group : array-like Group/query data, used for ranking task. Returns ------- new_func : callable The new eval function as expected by ``lightgbm.engine.train``. The signature is ``new_func(preds, dataset)``: preds : array-like of shape = [n_samples] or shape = [n_samples * n_classes] (for multi-class task) The predicted values. dataset : Dataset The training set from which the labels will be extracted using ``dataset.get_label()``. """ def inner(preds, dataset): """Call passed function with appropriate arguments.""" labels = dataset.get_label() argc = argc_(func) if argc == 2: return func(labels, preds) elif argc == 3: return func(labels, preds, dataset.get_weight()) elif argc == 4: return func(labels, preds, dataset.get_weight(), dataset.get_group()) else: raise TypeError("Self-defined eval function should have 2, 3 or 4 arguments, got %d" % argc) return inner
[ "def", "_eval_function_wrapper", "(", "func", ")", ":", "def", "inner", "(", "preds", ",", "dataset", ")", ":", "\"\"\"Call passed function with appropriate arguments.\"\"\"", "labels", "=", "dataset", ".", "get_label", "(", ")", "argc", "=", "argc_", "(", "func", ")", "if", "argc", "==", "2", ":", "return", "func", "(", "labels", ",", "preds", ")", "elif", "argc", "==", "3", ":", "return", "func", "(", "labels", ",", "preds", ",", "dataset", ".", "get_weight", "(", ")", ")", "elif", "argc", "==", "4", ":", "return", "func", "(", "labels", ",", "preds", ",", "dataset", ".", "get_weight", "(", ")", ",", "dataset", ".", "get_group", "(", ")", ")", "else", ":", "raise", "TypeError", "(", "\"Self-defined eval function should have 2, 3 or 4 arguments, got %d\"", "%", "argc", ")", "return", "inner" ]
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 following signatures: ``func(y_true, y_pred)``, ``func(y_true, y_pred, weight)`` or ``func(y_true, y_pred, weight, group)`` and returns (eval_name->string, eval_result->float, is_bigger_better->bool): y_true : array-like of shape = [n_samples] The target values. y_pred : array-like of shape = [n_samples] or shape = [n_samples * n_classes] (for multi-class task) The predicted values. weight : array-like of shape = [n_samples] The weight of samples. group : array-like Group/query data, used for ranking task. Returns ------- new_func : callable The new eval function as expected by ``lightgbm.engine.train``. The signature is ``new_func(preds, dataset)``: preds : array-like of shape = [n_samples] or shape = [n_samples * n_classes] (for multi-class task) The predicted values. dataset : Dataset The training set from which the labels will be extracted using ``dataset.get_label()``.
[ "Decorate", "an", "eval", "function", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/sklearn.py#L81-L130
22,863
Microsoft/LightGBM
python-package/lightgbm/sklearn.py
LGBMModel.predict
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 matrix. raw_score : bool, optional (default=False) Whether to predict raw scores. num_iteration : int or None, optional (default=None) Limit number of iterations in the prediction. If None, if the best iteration exists, it is used; otherwise, all trees are used. If <= 0, all trees are used (no limits). pred_leaf : bool, optional (default=False) Whether to predict leaf index. pred_contrib : bool, optional (default=False) Whether to predict feature contributions. Note ---- If you want to get more explanations for your model's predictions using SHAP values, like SHAP interaction values, you can install the shap package (https://github.com/slundberg/shap). Note that unlike the shap package, with ``pred_contrib`` we return a matrix with an extra column, where the last column is the expected value. **kwargs Other parameters for the prediction. Returns ------- predicted_result : array-like of shape = [n_samples] or shape = [n_samples, n_classes] The predicted values. X_leaves : array-like of shape = [n_samples, n_trees] or shape = [n_samples, n_trees * n_classes] If ``pred_leaf=True``, the predicted leaf of every tree for each sample. X_SHAP_values : array-like of shape = [n_samples, n_features + 1] or shape = [n_samples, (n_features + 1) * n_classes] If ``pred_contrib=True``, the feature contributions for each sample. """ if self._n_features is None: raise LGBMNotFittedError("Estimator not fitted, call `fit` before exploiting the model.") if not isinstance(X, (DataFrame, DataTable)): X = _LGBMCheckArray(X, accept_sparse=True, force_all_finite=False) n_features = X.shape[1] if self._n_features != n_features: raise ValueError("Number of features of the model must " "match the input. Model n_features_ is %s and " "input n_features is %s " % (self._n_features, n_features)) return self.booster_.predict(X, raw_score=raw_score, num_iteration=num_iteration, pred_leaf=pred_leaf, pred_contrib=pred_contrib, **kwargs)
python
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 matrix. raw_score : bool, optional (default=False) Whether to predict raw scores. num_iteration : int or None, optional (default=None) Limit number of iterations in the prediction. If None, if the best iteration exists, it is used; otherwise, all trees are used. If <= 0, all trees are used (no limits). pred_leaf : bool, optional (default=False) Whether to predict leaf index. pred_contrib : bool, optional (default=False) Whether to predict feature contributions. Note ---- If you want to get more explanations for your model's predictions using SHAP values, like SHAP interaction values, you can install the shap package (https://github.com/slundberg/shap). Note that unlike the shap package, with ``pred_contrib`` we return a matrix with an extra column, where the last column is the expected value. **kwargs Other parameters for the prediction. Returns ------- predicted_result : array-like of shape = [n_samples] or shape = [n_samples, n_classes] The predicted values. X_leaves : array-like of shape = [n_samples, n_trees] or shape = [n_samples, n_trees * n_classes] If ``pred_leaf=True``, the predicted leaf of every tree for each sample. X_SHAP_values : array-like of shape = [n_samples, n_features + 1] or shape = [n_samples, (n_features + 1) * n_classes] If ``pred_contrib=True``, the feature contributions for each sample. """ if self._n_features is None: raise LGBMNotFittedError("Estimator not fitted, call `fit` before exploiting the model.") if not isinstance(X, (DataFrame, DataTable)): X = _LGBMCheckArray(X, accept_sparse=True, force_all_finite=False) n_features = X.shape[1] if self._n_features != n_features: raise ValueError("Number of features of the model must " "match the input. Model n_features_ is %s and " "input n_features is %s " % (self._n_features, n_features)) return self.booster_.predict(X, raw_score=raw_score, num_iteration=num_iteration, pred_leaf=pred_leaf, pred_contrib=pred_contrib, **kwargs)
[ "def", "predict", "(", "self", ",", "X", ",", "raw_score", "=", "False", ",", "num_iteration", "=", "None", ",", "pred_leaf", "=", "False", ",", "pred_contrib", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_n_features", "is", "None", ":", "raise", "LGBMNotFittedError", "(", "\"Estimator not fitted, call `fit` before exploiting the model.\"", ")", "if", "not", "isinstance", "(", "X", ",", "(", "DataFrame", ",", "DataTable", ")", ")", ":", "X", "=", "_LGBMCheckArray", "(", "X", ",", "accept_sparse", "=", "True", ",", "force_all_finite", "=", "False", ")", "n_features", "=", "X", ".", "shape", "[", "1", "]", "if", "self", ".", "_n_features", "!=", "n_features", ":", "raise", "ValueError", "(", "\"Number of features of the model must \"", "\"match the input. Model n_features_ is %s and \"", "\"input n_features is %s \"", "%", "(", "self", ".", "_n_features", ",", "n_features", ")", ")", "return", "self", ".", "booster_", ".", "predict", "(", "X", ",", "raw_score", "=", "raw_score", ",", "num_iteration", "=", "num_iteration", ",", "pred_leaf", "=", "pred_leaf", ",", "pred_contrib", "=", "pred_contrib", ",", "*", "*", "kwargs", ")" ]
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 None, optional (default=None) Limit number of iterations in the prediction. If None, if the best iteration exists, it is used; otherwise, all trees are used. If <= 0, all trees are used (no limits). pred_leaf : bool, optional (default=False) Whether to predict leaf index. pred_contrib : bool, optional (default=False) Whether to predict feature contributions. Note ---- If you want to get more explanations for your model's predictions using SHAP values, like SHAP interaction values, you can install the shap package (https://github.com/slundberg/shap). Note that unlike the shap package, with ``pred_contrib`` we return a matrix with an extra column, where the last column is the expected value. **kwargs Other parameters for the prediction. Returns ------- predicted_result : array-like of shape = [n_samples] or shape = [n_samples, n_classes] The predicted values. X_leaves : array-like of shape = [n_samples, n_trees] or shape = [n_samples, n_trees * n_classes] If ``pred_leaf=True``, the predicted leaf of every tree for each sample. X_SHAP_values : array-like of shape = [n_samples, n_features + 1] or shape = [n_samples, (n_features + 1) * n_classes] If ``pred_contrib=True``, the feature contributions for each sample.
[ "Return", "the", "predicted", "value", "for", "each", "sample", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/sklearn.py#L564-L614
22,864
Microsoft/LightGBM
python-package/lightgbm/sklearn.py
LGBMClassifier.predict_proba
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_features] Input features matrix. raw_score : bool, optional (default=False) Whether to predict raw scores. num_iteration : int or None, optional (default=None) Limit number of iterations in the prediction. If None, if the best iteration exists, it is used; otherwise, all trees are used. If <= 0, all trees are used (no limits). pred_leaf : bool, optional (default=False) Whether to predict leaf index. pred_contrib : bool, optional (default=False) Whether to predict feature contributions. Note ---- If you want to get more explanations for your model's predictions using SHAP values, like SHAP interaction values, you can install the shap package (https://github.com/slundberg/shap). Note that unlike the shap package, with ``pred_contrib`` we return a matrix with an extra column, where the last column is the expected value. **kwargs Other parameters for the prediction. Returns ------- predicted_probability : array-like of shape = [n_samples, n_classes] The predicted probability for each class for each sample. X_leaves : array-like of shape = [n_samples, n_trees * n_classes] If ``pred_leaf=True``, the predicted leaf of every tree for each sample. X_SHAP_values : array-like of shape = [n_samples, (n_features + 1) * n_classes] If ``pred_contrib=True``, the feature contributions for each sample. """ result = super(LGBMClassifier, self).predict(X, raw_score, num_iteration, pred_leaf, pred_contrib, **kwargs) if self._n_classes > 2 or raw_score or pred_leaf or pred_contrib: return result else: return np.vstack((1. - result, result)).transpose()
python
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_features] Input features matrix. raw_score : bool, optional (default=False) Whether to predict raw scores. num_iteration : int or None, optional (default=None) Limit number of iterations in the prediction. If None, if the best iteration exists, it is used; otherwise, all trees are used. If <= 0, all trees are used (no limits). pred_leaf : bool, optional (default=False) Whether to predict leaf index. pred_contrib : bool, optional (default=False) Whether to predict feature contributions. Note ---- If you want to get more explanations for your model's predictions using SHAP values, like SHAP interaction values, you can install the shap package (https://github.com/slundberg/shap). Note that unlike the shap package, with ``pred_contrib`` we return a matrix with an extra column, where the last column is the expected value. **kwargs Other parameters for the prediction. Returns ------- predicted_probability : array-like of shape = [n_samples, n_classes] The predicted probability for each class for each sample. X_leaves : array-like of shape = [n_samples, n_trees * n_classes] If ``pred_leaf=True``, the predicted leaf of every tree for each sample. X_SHAP_values : array-like of shape = [n_samples, (n_features + 1) * n_classes] If ``pred_contrib=True``, the feature contributions for each sample. """ result = super(LGBMClassifier, self).predict(X, raw_score, num_iteration, pred_leaf, pred_contrib, **kwargs) if self._n_classes > 2 or raw_score or pred_leaf or pred_contrib: return result else: return np.vstack((1. - result, result)).transpose()
[ "def", "predict_proba", "(", "self", ",", "X", ",", "raw_score", "=", "False", ",", "num_iteration", "=", "None", ",", "pred_leaf", "=", "False", ",", "pred_contrib", "=", "False", ",", "*", "*", "kwargs", ")", ":", "result", "=", "super", "(", "LGBMClassifier", ",", "self", ")", ".", "predict", "(", "X", ",", "raw_score", ",", "num_iteration", ",", "pred_leaf", ",", "pred_contrib", ",", "*", "*", "kwargs", ")", "if", "self", ".", "_n_classes", ">", "2", "or", "raw_score", "or", "pred_leaf", "or", "pred_contrib", ":", "return", "result", "else", ":", "return", "np", ".", "vstack", "(", "(", "1.", "-", "result", ",", "result", ")", ")", ".", "transpose", "(", ")" ]
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_iteration : int or None, optional (default=None) Limit number of iterations in the prediction. If None, if the best iteration exists, it is used; otherwise, all trees are used. If <= 0, all trees are used (no limits). pred_leaf : bool, optional (default=False) Whether to predict leaf index. pred_contrib : bool, optional (default=False) Whether to predict feature contributions. Note ---- If you want to get more explanations for your model's predictions using SHAP values, like SHAP interaction values, you can install the shap package (https://github.com/slundberg/shap). Note that unlike the shap package, with ``pred_contrib`` we return a matrix with an extra column, where the last column is the expected value. **kwargs Other parameters for the prediction. Returns ------- predicted_probability : array-like of shape = [n_samples, n_classes] The predicted probability for each class for each sample. X_leaves : array-like of shape = [n_samples, n_trees * n_classes] If ``pred_leaf=True``, the predicted leaf of every tree for each sample. X_SHAP_values : array-like of shape = [n_samples, (n_features + 1) * n_classes] If ``pred_contrib=True``, the feature contributions for each sample.
[ "Return", "the", "predicted", "probability", "for", "each", "class", "for", "each", "sample", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/sklearn.py#L769-L813
22,865
Microsoft/LightGBM
helpers/parameter_generator.py
get_parameter_infos
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 cur_key = None cur_info = {} keys = [] member_infos = [] with open(config_hpp) as config_hpp_file: for line in config_hpp_file: if "#pragma region Parameters" in line: is_inparameter = True elif "#pragma region" in line and "Parameters" in line: cur_key = line.split("region")[1].strip() keys.append(cur_key) member_infos.append([]) elif '#pragma endregion' in line: if cur_key is not None: cur_key = None elif is_inparameter: is_inparameter = False elif cur_key is not None: line = line.strip() if line.startswith("//"): key, _, val = line[2:].partition("=") key = key.strip() val = val.strip() if key not in cur_info: if key == "descl2" and "desc" not in cur_info: cur_info["desc"] = [] elif key != "descl2": cur_info[key] = [] if key == "desc": cur_info["desc"].append(("l1", val)) elif key == "descl2": cur_info["desc"].append(("l2", val)) else: cur_info[key].append(val) elif line: has_eqsgn = False tokens = line.split("=") if len(tokens) == 2: if "default" not in cur_info: cur_info["default"] = [tokens[1][:-1].strip()] has_eqsgn = True tokens = line.split() cur_info["inner_type"] = [tokens[0].strip()] if "name" not in cur_info: if has_eqsgn: cur_info["name"] = [tokens[1].strip()] else: cur_info["name"] = [tokens[1][:-1].strip()] member_infos[-1].append(cur_info) cur_info = {} return keys, member_infos
python
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 cur_key = None cur_info = {} keys = [] member_infos = [] with open(config_hpp) as config_hpp_file: for line in config_hpp_file: if "#pragma region Parameters" in line: is_inparameter = True elif "#pragma region" in line and "Parameters" in line: cur_key = line.split("region")[1].strip() keys.append(cur_key) member_infos.append([]) elif '#pragma endregion' in line: if cur_key is not None: cur_key = None elif is_inparameter: is_inparameter = False elif cur_key is not None: line = line.strip() if line.startswith("//"): key, _, val = line[2:].partition("=") key = key.strip() val = val.strip() if key not in cur_info: if key == "descl2" and "desc" not in cur_info: cur_info["desc"] = [] elif key != "descl2": cur_info[key] = [] if key == "desc": cur_info["desc"].append(("l1", val)) elif key == "descl2": cur_info["desc"].append(("l2", val)) else: cur_info[key].append(val) elif line: has_eqsgn = False tokens = line.split("=") if len(tokens) == 2: if "default" not in cur_info: cur_info["default"] = [tokens[1][:-1].strip()] has_eqsgn = True tokens = line.split() cur_info["inner_type"] = [tokens[0].strip()] if "name" not in cur_info: if has_eqsgn: cur_info["name"] = [tokens[1].strip()] else: cur_info["name"] = [tokens[1][:-1].strip()] member_infos[-1].append(cur_info) cur_info = {} return keys, member_infos
[ "def", "get_parameter_infos", "(", "config_hpp", ")", ":", "is_inparameter", "=", "False", "parameter_group", "=", "None", "cur_key", "=", "None", "cur_info", "=", "{", "}", "keys", "=", "[", "]", "member_infos", "=", "[", "]", "with", "open", "(", "config_hpp", ")", "as", "config_hpp_file", ":", "for", "line", "in", "config_hpp_file", ":", "if", "\"#pragma region Parameters\"", "in", "line", ":", "is_inparameter", "=", "True", "elif", "\"#pragma region\"", "in", "line", "and", "\"Parameters\"", "in", "line", ":", "cur_key", "=", "line", ".", "split", "(", "\"region\"", ")", "[", "1", "]", ".", "strip", "(", ")", "keys", ".", "append", "(", "cur_key", ")", "member_infos", ".", "append", "(", "[", "]", ")", "elif", "'#pragma endregion'", "in", "line", ":", "if", "cur_key", "is", "not", "None", ":", "cur_key", "=", "None", "elif", "is_inparameter", ":", "is_inparameter", "=", "False", "elif", "cur_key", "is", "not", "None", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", ".", "startswith", "(", "\"//\"", ")", ":", "key", ",", "_", ",", "val", "=", "line", "[", "2", ":", "]", ".", "partition", "(", "\"=\"", ")", "key", "=", "key", ".", "strip", "(", ")", "val", "=", "val", ".", "strip", "(", ")", "if", "key", "not", "in", "cur_info", ":", "if", "key", "==", "\"descl2\"", "and", "\"desc\"", "not", "in", "cur_info", ":", "cur_info", "[", "\"desc\"", "]", "=", "[", "]", "elif", "key", "!=", "\"descl2\"", ":", "cur_info", "[", "key", "]", "=", "[", "]", "if", "key", "==", "\"desc\"", ":", "cur_info", "[", "\"desc\"", "]", ".", "append", "(", "(", "\"l1\"", ",", "val", ")", ")", "elif", "key", "==", "\"descl2\"", ":", "cur_info", "[", "\"desc\"", "]", ".", "append", "(", "(", "\"l2\"", ",", "val", ")", ")", "else", ":", "cur_info", "[", "key", "]", ".", "append", "(", "val", ")", "elif", "line", ":", "has_eqsgn", "=", "False", "tokens", "=", "line", ".", "split", "(", "\"=\"", ")", "if", "len", "(", "tokens", ")", "==", "2", ":", "if", "\"default\"", "not", "in", "cur_info", ":", "cur_info", "[", "\"default\"", "]", "=", "[", "tokens", "[", "1", "]", "[", ":", "-", "1", "]", ".", "strip", "(", ")", "]", "has_eqsgn", "=", "True", "tokens", "=", "line", ".", "split", "(", ")", "cur_info", "[", "\"inner_type\"", "]", "=", "[", "tokens", "[", "0", "]", ".", "strip", "(", ")", "]", "if", "\"name\"", "not", "in", "cur_info", ":", "if", "has_eqsgn", ":", "cur_info", "[", "\"name\"", "]", "=", "[", "tokens", "[", "1", "]", ".", "strip", "(", ")", "]", "else", ":", "cur_info", "[", "\"name\"", "]", "=", "[", "tokens", "[", "1", "]", "[", ":", "-", "1", "]", ".", "strip", "(", ")", "]", "member_infos", "[", "-", "1", "]", ".", "append", "(", "cur_info", ")", "cur_info", "=", "{", "}", "return", "keys", ",", "member_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.
[ "Parse", "config", "header", "file", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/helpers/parameter_generator.py#L12-L77
22,866
Microsoft/LightGBM
helpers/parameter_generator.py
get_names
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"][0]) return names
python
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"][0]) return names
[ "def", "get_names", "(", "infos", ")", ":", "names", "=", "[", "]", "for", "x", "in", "infos", ":", "for", "y", "in", "x", ":", "names", ".", "append", "(", "y", "[", "\"name\"", "]", "[", "0", "]", ")", "return", "names" ]
Get names of all parameters. Parameters ---------- infos : list Content of the config header file. Returns ------- names : list Names of all parameters.
[ "Get", "names", "of", "all", "parameters", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/helpers/parameter_generator.py#L80-L97
22,867
Microsoft/LightGBM
helpers/parameter_generator.py
get_alias
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 "alias" in y: name = y["name"][0] alias = y["alias"][0].split(',') for name2 in alias: pairs.append((name2.strip(), name)) return pairs
python
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 "alias" in y: name = y["name"][0] alias = y["alias"][0].split(',') for name2 in alias: pairs.append((name2.strip(), name)) return pairs
[ "def", "get_alias", "(", "infos", ")", ":", "pairs", "=", "[", "]", "for", "x", "in", "infos", ":", "for", "y", "in", "x", ":", "if", "\"alias\"", "in", "y", ":", "name", "=", "y", "[", "\"name\"", "]", "[", "0", "]", "alias", "=", "y", "[", "\"alias\"", "]", "[", "0", "]", ".", "split", "(", "','", ")", "for", "name2", "in", "alias", ":", "pairs", ".", "append", "(", "(", "name2", ".", "strip", "(", ")", ",", "name", ")", ")", "return", "pairs" ]
Get aliases of all parameters. Parameters ---------- infos : list Content of the config header file. Returns ------- pairs : list List of tuples (param alias, param name).
[ "Get", "aliases", "of", "all", "parameters", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/helpers/parameter_generator.py#L100-L121
22,868
Microsoft/LightGBM
helpers/parameter_generator.py
set_one_var_from_string
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. Returns ------- ret : string Lines of auto config file with getting and checks of one parameter value. """ ret = "" univar_mapper = {"int": "GetInt", "double": "GetDouble", "bool": "GetBool", "std::string": "GetString"} if "vector" not in param_type: ret += " %s(params, \"%s\", &%s);\n" % (univar_mapper[param_type], name, name) if len(checks) > 0: for check in checks: ret += " CHECK(%s %s);\n" % (name, check) ret += "\n" else: ret += " if (GetString(params, \"%s\", &tmp_str)) {\n" % (name) type2 = param_type.split("<")[1][:-1] if type2 == "std::string": ret += " %s = Common::Split(tmp_str.c_str(), ',');\n" % (name) else: ret += " %s = Common::StringToArray<%s>(tmp_str, ',');\n" % (name, type2) ret += " }\n\n" return ret
python
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. Returns ------- ret : string Lines of auto config file with getting and checks of one parameter value. """ ret = "" univar_mapper = {"int": "GetInt", "double": "GetDouble", "bool": "GetBool", "std::string": "GetString"} if "vector" not in param_type: ret += " %s(params, \"%s\", &%s);\n" % (univar_mapper[param_type], name, name) if len(checks) > 0: for check in checks: ret += " CHECK(%s %s);\n" % (name, check) ret += "\n" else: ret += " if (GetString(params, \"%s\", &tmp_str)) {\n" % (name) type2 = param_type.split("<")[1][:-1] if type2 == "std::string": ret += " %s = Common::Split(tmp_str.c_str(), ',');\n" % (name) else: ret += " %s = Common::StringToArray<%s>(tmp_str, ',');\n" % (name, type2) ret += " }\n\n" return ret
[ "def", "set_one_var_from_string", "(", "name", ",", "param_type", ",", "checks", ")", ":", "ret", "=", "\"\"", "univar_mapper", "=", "{", "\"int\"", ":", "\"GetInt\"", ",", "\"double\"", ":", "\"GetDouble\"", ",", "\"bool\"", ":", "\"GetBool\"", ",", "\"std::string\"", ":", "\"GetString\"", "}", "if", "\"vector\"", "not", "in", "param_type", ":", "ret", "+=", "\" %s(params, \\\"%s\\\", &%s);\\n\"", "%", "(", "univar_mapper", "[", "param_type", "]", ",", "name", ",", "name", ")", "if", "len", "(", "checks", ")", ">", "0", ":", "for", "check", "in", "checks", ":", "ret", "+=", "\" CHECK(%s %s);\\n\"", "%", "(", "name", ",", "check", ")", "ret", "+=", "\"\\n\"", "else", ":", "ret", "+=", "\" if (GetString(params, \\\"%s\\\", &tmp_str)) {\\n\"", "%", "(", "name", ")", "type2", "=", "param_type", ".", "split", "(", "\"<\"", ")", "[", "1", "]", "[", ":", "-", "1", "]", "if", "type2", "==", "\"std::string\"", ":", "ret", "+=", "\" %s = Common::Split(tmp_str.c_str(), ',');\\n\"", "%", "(", "name", ")", "else", ":", "ret", "+=", "\" %s = Common::StringToArray<%s>(tmp_str, ',');\\n\"", "%", "(", "name", ",", "type2", ")", "ret", "+=", "\" }\\n\\n\"", "return", "ret" ]
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 file with getting and checks of one parameter value.
[ "Construct", "code", "for", "auto", "config", "file", "for", "one", "param", "value", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/helpers/parameter_generator.py#L124-L157
22,869
Microsoft/LightGBM
helpers/parameter_generator.py
gen_parameter_code
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 content of sections. """ keys, infos = get_parameter_infos(config_hpp) names = get_names(infos) alias = get_alias(infos) str_to_write = r"""/*! * Copyright (c) 2018 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. * * \note * This file is auto generated by LightGBM\helpers\parameter_generator.py from LightGBM\include\LightGBM\config.h file. */ """ str_to_write += "#include<LightGBM/config.h>\nnamespace LightGBM {\n" # alias table str_to_write += "std::unordered_map<std::string, std::string> Config::alias_table({\n" for pair in alias: str_to_write += " {\"%s\", \"%s\"},\n" % (pair[0], pair[1]) str_to_write += "});\n\n" # names str_to_write += "std::unordered_set<std::string> Config::parameter_set({\n" for name in names: str_to_write += " \"%s\",\n" % (name) str_to_write += "});\n\n" # from strings str_to_write += "void Config::GetMembersFromString(const std::unordered_map<std::string, std::string>& params) {\n" str_to_write += " std::string tmp_str = \"\";\n" for x in infos: for y in x: if "[doc-only]" in y: continue param_type = y["inner_type"][0] name = y["name"][0] checks = [] if "check" in y: checks = y["check"] tmp = set_one_var_from_string(name, param_type, checks) str_to_write += tmp # tails str_to_write += "}\n\n" str_to_write += "std::string Config::SaveMembersToString() const {\n" str_to_write += " std::stringstream str_buf;\n" for x in infos: for y in x: if "[doc-only]" in y: continue param_type = y["inner_type"][0] name = y["name"][0] if "vector" in param_type: if "int8" in param_type: str_to_write += " str_buf << \"[%s: \" << Common::Join(Common::ArrayCast<int8_t, int>(%s), \",\") << \"]\\n\";\n" % (name, name) else: str_to_write += " str_buf << \"[%s: \" << Common::Join(%s, \",\") << \"]\\n\";\n" % (name, name) else: str_to_write += " str_buf << \"[%s: \" << %s << \"]\\n\";\n" % (name, name) # tails str_to_write += " return str_buf.str();\n" str_to_write += "}\n\n" str_to_write += "} // namespace LightGBM\n" with open(config_out_cpp, "w") as config_out_cpp_file: config_out_cpp_file.write(str_to_write) return keys, infos
python
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 content of sections. """ keys, infos = get_parameter_infos(config_hpp) names = get_names(infos) alias = get_alias(infos) str_to_write = r"""/*! * Copyright (c) 2018 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. * * \note * This file is auto generated by LightGBM\helpers\parameter_generator.py from LightGBM\include\LightGBM\config.h file. */ """ str_to_write += "#include<LightGBM/config.h>\nnamespace LightGBM {\n" # alias table str_to_write += "std::unordered_map<std::string, std::string> Config::alias_table({\n" for pair in alias: str_to_write += " {\"%s\", \"%s\"},\n" % (pair[0], pair[1]) str_to_write += "});\n\n" # names str_to_write += "std::unordered_set<std::string> Config::parameter_set({\n" for name in names: str_to_write += " \"%s\",\n" % (name) str_to_write += "});\n\n" # from strings str_to_write += "void Config::GetMembersFromString(const std::unordered_map<std::string, std::string>& params) {\n" str_to_write += " std::string tmp_str = \"\";\n" for x in infos: for y in x: if "[doc-only]" in y: continue param_type = y["inner_type"][0] name = y["name"][0] checks = [] if "check" in y: checks = y["check"] tmp = set_one_var_from_string(name, param_type, checks) str_to_write += tmp # tails str_to_write += "}\n\n" str_to_write += "std::string Config::SaveMembersToString() const {\n" str_to_write += " std::stringstream str_buf;\n" for x in infos: for y in x: if "[doc-only]" in y: continue param_type = y["inner_type"][0] name = y["name"][0] if "vector" in param_type: if "int8" in param_type: str_to_write += " str_buf << \"[%s: \" << Common::Join(Common::ArrayCast<int8_t, int>(%s), \",\") << \"]\\n\";\n" % (name, name) else: str_to_write += " str_buf << \"[%s: \" << Common::Join(%s, \",\") << \"]\\n\";\n" % (name, name) else: str_to_write += " str_buf << \"[%s: \" << %s << \"]\\n\";\n" % (name, name) # tails str_to_write += " return str_buf.str();\n" str_to_write += "}\n\n" str_to_write += "} // namespace LightGBM\n" with open(config_out_cpp, "w") as config_out_cpp_file: config_out_cpp_file.write(str_to_write) return keys, infos
[ "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", "=", "r\"\"\"/*!\n * Copyright (c) 2018 Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See LICENSE file in the project root for license information.\n *\n * \\note\n * This file is auto generated by LightGBM\\helpers\\parameter_generator.py from LightGBM\\include\\LightGBM\\config.h file.\n */\n\"\"\"", "str_to_write", "+=", "\"#include<LightGBM/config.h>\\nnamespace LightGBM {\\n\"", "# alias table", "str_to_write", "+=", "\"std::unordered_map<std::string, std::string> Config::alias_table({\\n\"", "for", "pair", "in", "alias", ":", "str_to_write", "+=", "\" {\\\"%s\\\", \\\"%s\\\"},\\n\"", "%", "(", "pair", "[", "0", "]", ",", "pair", "[", "1", "]", ")", "str_to_write", "+=", "\"});\\n\\n\"", "# names", "str_to_write", "+=", "\"std::unordered_set<std::string> Config::parameter_set({\\n\"", "for", "name", "in", "names", ":", "str_to_write", "+=", "\" \\\"%s\\\",\\n\"", "%", "(", "name", ")", "str_to_write", "+=", "\"});\\n\\n\"", "# from strings", "str_to_write", "+=", "\"void Config::GetMembersFromString(const std::unordered_map<std::string, std::string>& params) {\\n\"", "str_to_write", "+=", "\" std::string tmp_str = \\\"\\\";\\n\"", "for", "x", "in", "infos", ":", "for", "y", "in", "x", ":", "if", "\"[doc-only]\"", "in", "y", ":", "continue", "param_type", "=", "y", "[", "\"inner_type\"", "]", "[", "0", "]", "name", "=", "y", "[", "\"name\"", "]", "[", "0", "]", "checks", "=", "[", "]", "if", "\"check\"", "in", "y", ":", "checks", "=", "y", "[", "\"check\"", "]", "tmp", "=", "set_one_var_from_string", "(", "name", ",", "param_type", ",", "checks", ")", "str_to_write", "+=", "tmp", "# tails", "str_to_write", "+=", "\"}\\n\\n\"", "str_to_write", "+=", "\"std::string Config::SaveMembersToString() const {\\n\"", "str_to_write", "+=", "\" std::stringstream str_buf;\\n\"", "for", "x", "in", "infos", ":", "for", "y", "in", "x", ":", "if", "\"[doc-only]\"", "in", "y", ":", "continue", "param_type", "=", "y", "[", "\"inner_type\"", "]", "[", "0", "]", "name", "=", "y", "[", "\"name\"", "]", "[", "0", "]", "if", "\"vector\"", "in", "param_type", ":", "if", "\"int8\"", "in", "param_type", ":", "str_to_write", "+=", "\" str_buf << \\\"[%s: \\\" << Common::Join(Common::ArrayCast<int8_t, int>(%s), \\\",\\\") << \\\"]\\\\n\\\";\\n\"", "%", "(", "name", ",", "name", ")", "else", ":", "str_to_write", "+=", "\" str_buf << \\\"[%s: \\\" << Common::Join(%s, \\\",\\\") << \\\"]\\\\n\\\";\\n\"", "%", "(", "name", ",", "name", ")", "else", ":", "str_to_write", "+=", "\" str_buf << \\\"[%s: \\\" << %s << \\\"]\\\\n\\\";\\n\"", "%", "(", "name", ",", "name", ")", "# tails", "str_to_write", "+=", "\" return str_buf.str();\\n\"", "str_to_write", "+=", "\"}\\n\\n\"", "str_to_write", "+=", "\"} // namespace LightGBM\\n\"", "with", "open", "(", "config_out_cpp", ",", "\"w\"", ")", "as", "config_out_cpp_file", ":", "config_out_cpp_file", ".", "write", "(", "str_to_write", ")", "return", "keys", ",", "infos" ]
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.
[ "Generate", "auto", "config", "file", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/helpers/parameter_generator.py#L245-L320
22,870
Microsoft/LightGBM
python-package/lightgbm/basic.py
_load_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
python
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", "(", ")", ":", "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.
[ "Load", "LightGBM", "library", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L25-L32
22,871
Microsoft/LightGBM
python-package/lightgbm/basic.py
list_to_1d_numpy
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, dtype=dtype, copy=False) elif isinstance(data, Series): return data.values.astype(dtype) else: raise TypeError("Wrong type({0}) for {1}.\n" "It should be list, numpy 1-D array or pandas Series".format(type(data).__name__, name))
python
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, dtype=dtype, copy=False) elif isinstance(data, Series): return data.values.astype(dtype) else: raise TypeError("Wrong type({0}) for {1}.\n" "It should be list, numpy 1-D array or pandas Series".format(type(data).__name__, name))
[ "def", "list_to_1d_numpy", "(", "data", ",", "dtype", "=", "np", ".", "float32", ",", "name", "=", "'list'", ")", ":", "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", ",", "dtype", "=", "dtype", ",", "copy", "=", "False", ")", "elif", "isinstance", "(", "data", ",", "Series", ")", ":", "return", "data", ".", "values", ".", "astype", "(", "dtype", ")", "else", ":", "raise", "TypeError", "(", "\"Wrong type({0}) for {1}.\\n\"", "\"It should be list, numpy 1-D array or pandas Series\"", ".", "format", "(", "type", "(", "data", ")", ".", "__name__", ",", "name", ")", ")" ]
Convert data to 1-D numpy array.
[ "Convert", "data", "to", "1", "-", "D", "numpy", "array", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L71-L84
22,872
Microsoft/LightGBM
python-package/lightgbm/basic.py
cfloat32_array_to_numpy
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')
python
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", ")", ":", "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.
[ "Convert", "a", "ctypes", "float", "pointer", "array", "to", "a", "numpy", "array", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L87-L92
22,873
Microsoft/LightGBM
python-package/lightgbm/basic.py
cfloat64_array_to_numpy
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')
python
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", ")", ":", "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.
[ "Convert", "a", "ctypes", "double", "pointer", "array", "to", "a", "numpy", "array", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L95-L100
22,874
Microsoft/LightGBM
python-package/lightgbm/basic.py
param_dict_to_str
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) + '=' + ','.join(map(str, val))) elif isinstance(val, string_type) or isinstance(val, numeric_types) or is_numeric(val): pairs.append(str(key) + '=' + str(val)) elif val is not None: raise TypeError('Unknown type of parameter:%s, got:%s' % (key, type(val).__name__)) return ' '.join(pairs)
python
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) + '=' + ','.join(map(str, val))) elif isinstance(val, string_type) or isinstance(val, numeric_types) or is_numeric(val): pairs.append(str(key) + '=' + str(val)) elif val is not None: raise TypeError('Unknown type of parameter:%s, got:%s' % (key, type(val).__name__)) return ' '.join(pairs)
[ "def", "param_dict_to_str", "(", "data", ")", ":", "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", ")", "+", "'='", "+", "','", ".", "join", "(", "map", "(", "str", ",", "val", ")", ")", ")", "elif", "isinstance", "(", "val", ",", "string_type", ")", "or", "isinstance", "(", "val", ",", "numeric_types", ")", "or", "is_numeric", "(", "val", ")", ":", "pairs", ".", "append", "(", "str", "(", "key", ")", "+", "'='", "+", "str", "(", "val", ")", ")", "elif", "val", "is", "not", "None", ":", "raise", "TypeError", "(", "'Unknown type of parameter:%s, got:%s'", "%", "(", "key", ",", "type", "(", "val", ")", ".", "__name__", ")", ")", "return", "' '", ".", "join", "(", "pairs", ")" ]
Convert Python dictionary to string, which is passed to C API.
[ "Convert", "Python", "dictionary", "to", "string", "which", "is", "passed", "to", "C", "API", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L129-L142
22,875
Microsoft/LightGBM
python-package/lightgbm/basic.py
convert_from_sliced_object
def convert_from_sliced_object(data): """Fix the memory of multi-dimensional sliced object.""" if data.base is not None and isinstance(data, np.ndarray) and isinstance(data.base, np.ndarray): if not data.flags.c_contiguous: warnings.warn("Usage of np.ndarray subset (sliced data) is not recommended " "due to it will double the peak memory cost in LightGBM.") return np.copy(data) return data
python
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 recommended " "due to it will double the peak memory cost in LightGBM.") return np.copy(data) return data
[ "def", "convert_from_sliced_object", "(", "data", ")", ":", "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 recommended \"", "\"due to it will double the peak memory cost in LightGBM.\"", ")", "return", "np", ".", "copy", "(", "data", ")", "return", "data" ]
Fix the memory of multi-dimensional sliced object.
[ "Fix", "the", "memory", "of", "multi", "-", "dimensional", "sliced", "object", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L203-L210
22,876
Microsoft/LightGBM
python-package/lightgbm/basic.py
_InnerPredictor.predict
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.sparse Data source for prediction. When data type is string, it represents the path of txt file. num_iteration : int, optional (default=-1) Iteration used for prediction. raw_score : bool, optional (default=False) Whether to predict raw scores. pred_leaf : bool, optional (default=False) Whether to predict leaf index. pred_contrib : bool, optional (default=False) Whether to predict feature contributions. data_has_header : bool, optional (default=False) Whether data has header. Used only for txt data. is_reshape : bool, optional (default=True) Whether to reshape to (nrow, ncol). Returns ------- result : numpy array Prediction result. """ if isinstance(data, Dataset): raise TypeError("Cannot use Dataset instance for prediction, please use raw data instead") data = _data_from_pandas(data, None, None, self.pandas_categorical)[0] predict_type = C_API_PREDICT_NORMAL if raw_score: predict_type = C_API_PREDICT_RAW_SCORE if pred_leaf: predict_type = C_API_PREDICT_LEAF_INDEX if pred_contrib: predict_type = C_API_PREDICT_CONTRIB int_data_has_header = 1 if data_has_header else 0 if num_iteration > self.num_total_iteration: num_iteration = self.num_total_iteration if isinstance(data, string_type): with _TempFile() as f: _safe_call(_LIB.LGBM_BoosterPredictForFile( self.handle, c_str(data), ctypes.c_int(int_data_has_header), ctypes.c_int(predict_type), ctypes.c_int(num_iteration), c_str(self.pred_parameter), c_str(f.name))) lines = f.readlines() nrow = len(lines) preds = [float(token) for line in lines for token in line.split('\t')] preds = np.array(preds, dtype=np.float64, copy=False) elif isinstance(data, scipy.sparse.csr_matrix): preds, nrow = self.__pred_for_csr(data, num_iteration, predict_type) elif isinstance(data, scipy.sparse.csc_matrix): preds, nrow = self.__pred_for_csc(data, num_iteration, predict_type) elif isinstance(data, np.ndarray): preds, nrow = self.__pred_for_np2d(data, num_iteration, predict_type) elif isinstance(data, list): try: data = np.array(data) except BaseException: raise ValueError('Cannot convert data list to numpy array.') preds, nrow = self.__pred_for_np2d(data, num_iteration, predict_type) elif isinstance(data, DataTable): preds, nrow = self.__pred_for_np2d(data.to_numpy(), num_iteration, predict_type) else: try: warnings.warn('Converting data to scipy sparse matrix.') csr = scipy.sparse.csr_matrix(data) except BaseException: raise TypeError('Cannot predict data for type {}'.format(type(data).__name__)) preds, nrow = self.__pred_for_csr(csr, num_iteration, predict_type) if pred_leaf: preds = preds.astype(np.int32) if is_reshape and preds.size != nrow: if preds.size % nrow == 0: preds = preds.reshape(nrow, -1) else: raise ValueError('Length of predict result (%d) cannot be divide nrow (%d)' % (preds.size, nrow)) return preds
python
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.sparse Data source for prediction. When data type is string, it represents the path of txt file. num_iteration : int, optional (default=-1) Iteration used for prediction. raw_score : bool, optional (default=False) Whether to predict raw scores. pred_leaf : bool, optional (default=False) Whether to predict leaf index. pred_contrib : bool, optional (default=False) Whether to predict feature contributions. data_has_header : bool, optional (default=False) Whether data has header. Used only for txt data. is_reshape : bool, optional (default=True) Whether to reshape to (nrow, ncol). Returns ------- result : numpy array Prediction result. """ if isinstance(data, Dataset): raise TypeError("Cannot use Dataset instance for prediction, please use raw data instead") data = _data_from_pandas(data, None, None, self.pandas_categorical)[0] predict_type = C_API_PREDICT_NORMAL if raw_score: predict_type = C_API_PREDICT_RAW_SCORE if pred_leaf: predict_type = C_API_PREDICT_LEAF_INDEX if pred_contrib: predict_type = C_API_PREDICT_CONTRIB int_data_has_header = 1 if data_has_header else 0 if num_iteration > self.num_total_iteration: num_iteration = self.num_total_iteration if isinstance(data, string_type): with _TempFile() as f: _safe_call(_LIB.LGBM_BoosterPredictForFile( self.handle, c_str(data), ctypes.c_int(int_data_has_header), ctypes.c_int(predict_type), ctypes.c_int(num_iteration), c_str(self.pred_parameter), c_str(f.name))) lines = f.readlines() nrow = len(lines) preds = [float(token) for line in lines for token in line.split('\t')] preds = np.array(preds, dtype=np.float64, copy=False) elif isinstance(data, scipy.sparse.csr_matrix): preds, nrow = self.__pred_for_csr(data, num_iteration, predict_type) elif isinstance(data, scipy.sparse.csc_matrix): preds, nrow = self.__pred_for_csc(data, num_iteration, predict_type) elif isinstance(data, np.ndarray): preds, nrow = self.__pred_for_np2d(data, num_iteration, predict_type) elif isinstance(data, list): try: data = np.array(data) except BaseException: raise ValueError('Cannot convert data list to numpy array.') preds, nrow = self.__pred_for_np2d(data, num_iteration, predict_type) elif isinstance(data, DataTable): preds, nrow = self.__pred_for_np2d(data.to_numpy(), num_iteration, predict_type) else: try: warnings.warn('Converting data to scipy sparse matrix.') csr = scipy.sparse.csr_matrix(data) except BaseException: raise TypeError('Cannot predict data for type {}'.format(type(data).__name__)) preds, nrow = self.__pred_for_csr(csr, num_iteration, predict_type) if pred_leaf: preds = preds.astype(np.int32) if is_reshape and preds.size != nrow: if preds.size % nrow == 0: preds = preds.reshape(nrow, -1) else: raise ValueError('Length of predict result (%d) cannot be divide nrow (%d)' % (preds.size, nrow)) return preds
[ "def", "predict", "(", "self", ",", "data", ",", "num_iteration", "=", "-", "1", ",", "raw_score", "=", "False", ",", "pred_leaf", "=", "False", ",", "pred_contrib", "=", "False", ",", "data_has_header", "=", "False", ",", "is_reshape", "=", "True", ")", ":", "if", "isinstance", "(", "data", ",", "Dataset", ")", ":", "raise", "TypeError", "(", "\"Cannot use Dataset instance for prediction, please use raw data instead\"", ")", "data", "=", "_data_from_pandas", "(", "data", ",", "None", ",", "None", ",", "self", ".", "pandas_categorical", ")", "[", "0", "]", "predict_type", "=", "C_API_PREDICT_NORMAL", "if", "raw_score", ":", "predict_type", "=", "C_API_PREDICT_RAW_SCORE", "if", "pred_leaf", ":", "predict_type", "=", "C_API_PREDICT_LEAF_INDEX", "if", "pred_contrib", ":", "predict_type", "=", "C_API_PREDICT_CONTRIB", "int_data_has_header", "=", "1", "if", "data_has_header", "else", "0", "if", "num_iteration", ">", "self", ".", "num_total_iteration", ":", "num_iteration", "=", "self", ".", "num_total_iteration", "if", "isinstance", "(", "data", ",", "string_type", ")", ":", "with", "_TempFile", "(", ")", "as", "f", ":", "_safe_call", "(", "_LIB", ".", "LGBM_BoosterPredictForFile", "(", "self", ".", "handle", ",", "c_str", "(", "data", ")", ",", "ctypes", ".", "c_int", "(", "int_data_has_header", ")", ",", "ctypes", ".", "c_int", "(", "predict_type", ")", ",", "ctypes", ".", "c_int", "(", "num_iteration", ")", ",", "c_str", "(", "self", ".", "pred_parameter", ")", ",", "c_str", "(", "f", ".", "name", ")", ")", ")", "lines", "=", "f", ".", "readlines", "(", ")", "nrow", "=", "len", "(", "lines", ")", "preds", "=", "[", "float", "(", "token", ")", "for", "line", "in", "lines", "for", "token", "in", "line", ".", "split", "(", "'\\t'", ")", "]", "preds", "=", "np", ".", "array", "(", "preds", ",", "dtype", "=", "np", ".", "float64", ",", "copy", "=", "False", ")", "elif", "isinstance", "(", "data", ",", "scipy", ".", "sparse", ".", "csr_matrix", ")", ":", "preds", ",", "nrow", "=", "self", ".", "__pred_for_csr", "(", "data", ",", "num_iteration", ",", "predict_type", ")", "elif", "isinstance", "(", "data", ",", "scipy", ".", "sparse", ".", "csc_matrix", ")", ":", "preds", ",", "nrow", "=", "self", ".", "__pred_for_csc", "(", "data", ",", "num_iteration", ",", "predict_type", ")", "elif", "isinstance", "(", "data", ",", "np", ".", "ndarray", ")", ":", "preds", ",", "nrow", "=", "self", ".", "__pred_for_np2d", "(", "data", ",", "num_iteration", ",", "predict_type", ")", "elif", "isinstance", "(", "data", ",", "list", ")", ":", "try", ":", "data", "=", "np", ".", "array", "(", "data", ")", "except", "BaseException", ":", "raise", "ValueError", "(", "'Cannot convert data list to numpy array.'", ")", "preds", ",", "nrow", "=", "self", ".", "__pred_for_np2d", "(", "data", ",", "num_iteration", ",", "predict_type", ")", "elif", "isinstance", "(", "data", ",", "DataTable", ")", ":", "preds", ",", "nrow", "=", "self", ".", "__pred_for_np2d", "(", "data", ".", "to_numpy", "(", ")", ",", "num_iteration", ",", "predict_type", ")", "else", ":", "try", ":", "warnings", ".", "warn", "(", "'Converting data to scipy sparse matrix.'", ")", "csr", "=", "scipy", ".", "sparse", ".", "csr_matrix", "(", "data", ")", "except", "BaseException", ":", "raise", "TypeError", "(", "'Cannot predict data for type {}'", ".", "format", "(", "type", "(", "data", ")", ".", "__name__", ")", ")", "preds", ",", "nrow", "=", "self", ".", "__pred_for_csr", "(", "csr", ",", "num_iteration", ",", "predict_type", ")", "if", "pred_leaf", ":", "preds", "=", "preds", ".", "astype", "(", "np", ".", "int32", ")", "if", "is_reshape", "and", "preds", ".", "size", "!=", "nrow", ":", "if", "preds", ".", "size", "%", "nrow", "==", "0", ":", "preds", "=", "preds", ".", "reshape", "(", "nrow", ",", "-", "1", ")", "else", ":", "raise", "ValueError", "(", "'Length of predict result (%d) cannot be divide nrow (%d)'", "%", "(", "preds", ".", "size", ",", "nrow", ")", ")", "return", "preds" ]
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) Iteration used for prediction. raw_score : bool, optional (default=False) Whether to predict raw scores. pred_leaf : bool, optional (default=False) Whether to predict leaf index. pred_contrib : bool, optional (default=False) Whether to predict feature contributions. data_has_header : bool, optional (default=False) Whether data has header. Used only for txt data. is_reshape : bool, optional (default=True) Whether to reshape to (nrow, ncol). Returns ------- result : numpy array Prediction result.
[ "Predict", "logic", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L417-L503
22,877
Microsoft/LightGBM
python-package/lightgbm/basic.py
_InnerPredictor.__get_num_preds
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' 'You can split your data into chunks' 'and then concatenate predictions for them' % MAX_INT32) n_preds = ctypes.c_int64(0) _safe_call(_LIB.LGBM_BoosterCalcNumPredict( self.handle, ctypes.c_int(nrow), ctypes.c_int(predict_type), ctypes.c_int(num_iteration), ctypes.byref(n_preds))) return n_preds.value
python
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' 'You can split your data into chunks' 'and then concatenate predictions for them' % MAX_INT32) n_preds = ctypes.c_int64(0) _safe_call(_LIB.LGBM_BoosterCalcNumPredict( self.handle, ctypes.c_int(nrow), ctypes.c_int(predict_type), ctypes.c_int(num_iteration), ctypes.byref(n_preds))) return n_preds.value
[ "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).\\n'", "'You can split your data into chunks'", "'and then concatenate predictions for them'", "%", "MAX_INT32", ")", "n_preds", "=", "ctypes", ".", "c_int64", "(", "0", ")", "_safe_call", "(", "_LIB", ".", "LGBM_BoosterCalcNumPredict", "(", "self", ".", "handle", ",", "ctypes", ".", "c_int", "(", "nrow", ")", ",", "ctypes", ".", "c_int", "(", "predict_type", ")", ",", "ctypes", ".", "c_int", "(", "num_iteration", ")", ",", "ctypes", ".", "byref", "(", "n_preds", ")", ")", ")", "return", "n_preds", ".", "value" ]
Get size of prediction result.
[ "Get", "size", "of", "prediction", "result", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L505-L519
22,878
Microsoft/LightGBM
python-package/lightgbm/basic.py
_InnerPredictor.__pred_for_np2d
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 == np.float32 or mat.dtype == np.float64: data = np.array(mat.reshape(mat.size), dtype=mat.dtype, copy=False) else: """change non-float data to float data, need to copy""" data = np.array(mat.reshape(mat.size), dtype=np.float32) ptr_data, type_ptr_data, _ = c_float_array(data) n_preds = self.__get_num_preds(num_iteration, mat.shape[0], predict_type) if preds is None: preds = np.zeros(n_preds, dtype=np.float64) elif len(preds.shape) != 1 or len(preds) != n_preds: raise ValueError("Wrong length of pre-allocated predict array") out_num_preds = ctypes.c_int64(0) _safe_call(_LIB.LGBM_BoosterPredictForMat( self.handle, ptr_data, ctypes.c_int(type_ptr_data), ctypes.c_int(mat.shape[0]), ctypes.c_int(mat.shape[1]), ctypes.c_int(C_API_IS_ROW_MAJOR), ctypes.c_int(predict_type), ctypes.c_int(num_iteration), c_str(self.pred_parameter), ctypes.byref(out_num_preds), preds.ctypes.data_as(ctypes.POINTER(ctypes.c_double)))) if n_preds != out_num_preds.value: raise ValueError("Wrong length for predict results") return preds, mat.shape[0] nrow = mat.shape[0] if nrow > MAX_INT32: sections = np.arange(start=MAX_INT32, stop=nrow, step=MAX_INT32) # __get_num_preds() cannot work with nrow > MAX_INT32, so calculate overall number of predictions piecemeal n_preds = [self.__get_num_preds(num_iteration, i, predict_type) for i in np.diff([0] + list(sections) + [nrow])] n_preds_sections = np.array([0] + n_preds, dtype=np.intp).cumsum() preds = np.zeros(sum(n_preds), dtype=np.float64) for chunk, (start_idx_pred, end_idx_pred) in zip_(np.array_split(mat, sections), zip_(n_preds_sections, n_preds_sections[1:])): # avoid memory consumption by arrays concatenation operations inner_predict(chunk, num_iteration, predict_type, preds[start_idx_pred:end_idx_pred]) return preds, nrow else: return inner_predict(mat, num_iteration, predict_type)
python
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 == np.float32 or mat.dtype == np.float64: data = np.array(mat.reshape(mat.size), dtype=mat.dtype, copy=False) else: """change non-float data to float data, need to copy""" data = np.array(mat.reshape(mat.size), dtype=np.float32) ptr_data, type_ptr_data, _ = c_float_array(data) n_preds = self.__get_num_preds(num_iteration, mat.shape[0], predict_type) if preds is None: preds = np.zeros(n_preds, dtype=np.float64) elif len(preds.shape) != 1 or len(preds) != n_preds: raise ValueError("Wrong length of pre-allocated predict array") out_num_preds = ctypes.c_int64(0) _safe_call(_LIB.LGBM_BoosterPredictForMat( self.handle, ptr_data, ctypes.c_int(type_ptr_data), ctypes.c_int(mat.shape[0]), ctypes.c_int(mat.shape[1]), ctypes.c_int(C_API_IS_ROW_MAJOR), ctypes.c_int(predict_type), ctypes.c_int(num_iteration), c_str(self.pred_parameter), ctypes.byref(out_num_preds), preds.ctypes.data_as(ctypes.POINTER(ctypes.c_double)))) if n_preds != out_num_preds.value: raise ValueError("Wrong length for predict results") return preds, mat.shape[0] nrow = mat.shape[0] if nrow > MAX_INT32: sections = np.arange(start=MAX_INT32, stop=nrow, step=MAX_INT32) # __get_num_preds() cannot work with nrow > MAX_INT32, so calculate overall number of predictions piecemeal n_preds = [self.__get_num_preds(num_iteration, i, predict_type) for i in np.diff([0] + list(sections) + [nrow])] n_preds_sections = np.array([0] + n_preds, dtype=np.intp).cumsum() preds = np.zeros(sum(n_preds), dtype=np.float64) for chunk, (start_idx_pred, end_idx_pred) in zip_(np.array_split(mat, sections), zip_(n_preds_sections, n_preds_sections[1:])): # avoid memory consumption by arrays concatenation operations inner_predict(chunk, num_iteration, predict_type, preds[start_idx_pred:end_idx_pred]) return preds, nrow else: return inner_predict(mat, num_iteration, predict_type)
[ "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", "inner_predict", "(", "mat", ",", "num_iteration", ",", "predict_type", ",", "preds", "=", "None", ")", ":", "if", "mat", ".", "dtype", "==", "np", ".", "float32", "or", "mat", ".", "dtype", "==", "np", ".", "float64", ":", "data", "=", "np", ".", "array", "(", "mat", ".", "reshape", "(", "mat", ".", "size", ")", ",", "dtype", "=", "mat", ".", "dtype", ",", "copy", "=", "False", ")", "else", ":", "\"\"\"change non-float data to float data, need to copy\"\"\"", "data", "=", "np", ".", "array", "(", "mat", ".", "reshape", "(", "mat", ".", "size", ")", ",", "dtype", "=", "np", ".", "float32", ")", "ptr_data", ",", "type_ptr_data", ",", "_", "=", "c_float_array", "(", "data", ")", "n_preds", "=", "self", ".", "__get_num_preds", "(", "num_iteration", ",", "mat", ".", "shape", "[", "0", "]", ",", "predict_type", ")", "if", "preds", "is", "None", ":", "preds", "=", "np", ".", "zeros", "(", "n_preds", ",", "dtype", "=", "np", ".", "float64", ")", "elif", "len", "(", "preds", ".", "shape", ")", "!=", "1", "or", "len", "(", "preds", ")", "!=", "n_preds", ":", "raise", "ValueError", "(", "\"Wrong length of pre-allocated predict array\"", ")", "out_num_preds", "=", "ctypes", ".", "c_int64", "(", "0", ")", "_safe_call", "(", "_LIB", ".", "LGBM_BoosterPredictForMat", "(", "self", ".", "handle", ",", "ptr_data", ",", "ctypes", ".", "c_int", "(", "type_ptr_data", ")", ",", "ctypes", ".", "c_int", "(", "mat", ".", "shape", "[", "0", "]", ")", ",", "ctypes", ".", "c_int", "(", "mat", ".", "shape", "[", "1", "]", ")", ",", "ctypes", ".", "c_int", "(", "C_API_IS_ROW_MAJOR", ")", ",", "ctypes", ".", "c_int", "(", "predict_type", ")", ",", "ctypes", ".", "c_int", "(", "num_iteration", ")", ",", "c_str", "(", "self", ".", "pred_parameter", ")", ",", "ctypes", ".", "byref", "(", "out_num_preds", ")", ",", "preds", ".", "ctypes", ".", "data_as", "(", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_double", ")", ")", ")", ")", "if", "n_preds", "!=", "out_num_preds", ".", "value", ":", "raise", "ValueError", "(", "\"Wrong length for predict results\"", ")", "return", "preds", ",", "mat", ".", "shape", "[", "0", "]", "nrow", "=", "mat", ".", "shape", "[", "0", "]", "if", "nrow", ">", "MAX_INT32", ":", "sections", "=", "np", ".", "arange", "(", "start", "=", "MAX_INT32", ",", "stop", "=", "nrow", ",", "step", "=", "MAX_INT32", ")", "# __get_num_preds() cannot work with nrow > MAX_INT32, so calculate overall number of predictions piecemeal", "n_preds", "=", "[", "self", ".", "__get_num_preds", "(", "num_iteration", ",", "i", ",", "predict_type", ")", "for", "i", "in", "np", ".", "diff", "(", "[", "0", "]", "+", "list", "(", "sections", ")", "+", "[", "nrow", "]", ")", "]", "n_preds_sections", "=", "np", ".", "array", "(", "[", "0", "]", "+", "n_preds", ",", "dtype", "=", "np", ".", "intp", ")", ".", "cumsum", "(", ")", "preds", "=", "np", ".", "zeros", "(", "sum", "(", "n_preds", ")", ",", "dtype", "=", "np", ".", "float64", ")", "for", "chunk", ",", "(", "start_idx_pred", ",", "end_idx_pred", ")", "in", "zip_", "(", "np", ".", "array_split", "(", "mat", ",", "sections", ")", ",", "zip_", "(", "n_preds_sections", ",", "n_preds_sections", "[", "1", ":", "]", ")", ")", ":", "# avoid memory consumption by arrays concatenation operations", "inner_predict", "(", "chunk", ",", "num_iteration", ",", "predict_type", ",", "preds", "[", "start_idx_pred", ":", "end_idx_pred", "]", ")", "return", "preds", ",", "nrow", "else", ":", "return", "inner_predict", "(", "mat", ",", "num_iteration", ",", "predict_type", ")" ]
Predict for a 2-D numpy matrix.
[ "Predict", "for", "a", "2", "-", "D", "numpy", "matrix", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L521-L568
22,879
Microsoft/LightGBM
python-package/lightgbm/basic.py
_InnerPredictor.__pred_for_csr
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: preds = np.zeros(n_preds, dtype=np.float64) elif len(preds.shape) != 1 or len(preds) != n_preds: raise ValueError("Wrong length of pre-allocated predict array") out_num_preds = ctypes.c_int64(0) ptr_indptr, type_ptr_indptr, __ = c_int_array(csr.indptr) ptr_data, type_ptr_data, _ = c_float_array(csr.data) assert csr.shape[1] <= MAX_INT32 csr.indices = csr.indices.astype(np.int32, copy=False) _safe_call(_LIB.LGBM_BoosterPredictForCSR( self.handle, ptr_indptr, ctypes.c_int32(type_ptr_indptr), csr.indices.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)), ptr_data, ctypes.c_int(type_ptr_data), ctypes.c_int64(len(csr.indptr)), ctypes.c_int64(len(csr.data)), ctypes.c_int64(csr.shape[1]), ctypes.c_int(predict_type), ctypes.c_int(num_iteration), c_str(self.pred_parameter), ctypes.byref(out_num_preds), preds.ctypes.data_as(ctypes.POINTER(ctypes.c_double)))) if n_preds != out_num_preds.value: raise ValueError("Wrong length for predict results") return preds, nrow nrow = len(csr.indptr) - 1 if nrow > MAX_INT32: sections = [0] + list(np.arange(start=MAX_INT32, stop=nrow, step=MAX_INT32)) + [nrow] # __get_num_preds() cannot work with nrow > MAX_INT32, so calculate overall number of predictions piecemeal n_preds = [self.__get_num_preds(num_iteration, i, predict_type) for i in np.diff(sections)] n_preds_sections = np.array([0] + n_preds, dtype=np.intp).cumsum() preds = np.zeros(sum(n_preds), dtype=np.float64) for (start_idx, end_idx), (start_idx_pred, end_idx_pred) in zip_(zip_(sections, sections[1:]), zip_(n_preds_sections, n_preds_sections[1:])): # avoid memory consumption by arrays concatenation operations inner_predict(csr[start_idx:end_idx], num_iteration, predict_type, preds[start_idx_pred:end_idx_pred]) return preds, nrow else: return inner_predict(csr, num_iteration, predict_type)
python
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: preds = np.zeros(n_preds, dtype=np.float64) elif len(preds.shape) != 1 or len(preds) != n_preds: raise ValueError("Wrong length of pre-allocated predict array") out_num_preds = ctypes.c_int64(0) ptr_indptr, type_ptr_indptr, __ = c_int_array(csr.indptr) ptr_data, type_ptr_data, _ = c_float_array(csr.data) assert csr.shape[1] <= MAX_INT32 csr.indices = csr.indices.astype(np.int32, copy=False) _safe_call(_LIB.LGBM_BoosterPredictForCSR( self.handle, ptr_indptr, ctypes.c_int32(type_ptr_indptr), csr.indices.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)), ptr_data, ctypes.c_int(type_ptr_data), ctypes.c_int64(len(csr.indptr)), ctypes.c_int64(len(csr.data)), ctypes.c_int64(csr.shape[1]), ctypes.c_int(predict_type), ctypes.c_int(num_iteration), c_str(self.pred_parameter), ctypes.byref(out_num_preds), preds.ctypes.data_as(ctypes.POINTER(ctypes.c_double)))) if n_preds != out_num_preds.value: raise ValueError("Wrong length for predict results") return preds, nrow nrow = len(csr.indptr) - 1 if nrow > MAX_INT32: sections = [0] + list(np.arange(start=MAX_INT32, stop=nrow, step=MAX_INT32)) + [nrow] # __get_num_preds() cannot work with nrow > MAX_INT32, so calculate overall number of predictions piecemeal n_preds = [self.__get_num_preds(num_iteration, i, predict_type) for i in np.diff(sections)] n_preds_sections = np.array([0] + n_preds, dtype=np.intp).cumsum() preds = np.zeros(sum(n_preds), dtype=np.float64) for (start_idx, end_idx), (start_idx_pred, end_idx_pred) in zip_(zip_(sections, sections[1:]), zip_(n_preds_sections, n_preds_sections[1:])): # avoid memory consumption by arrays concatenation operations inner_predict(csr[start_idx:end_idx], num_iteration, predict_type, preds[start_idx_pred:end_idx_pred]) return preds, nrow else: return inner_predict(csr, num_iteration, predict_type)
[ "def", "__pred_for_csr", "(", "self", ",", "csr", ",", "num_iteration", ",", "predict_type", ")", ":", "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", ":", "preds", "=", "np", ".", "zeros", "(", "n_preds", ",", "dtype", "=", "np", ".", "float64", ")", "elif", "len", "(", "preds", ".", "shape", ")", "!=", "1", "or", "len", "(", "preds", ")", "!=", "n_preds", ":", "raise", "ValueError", "(", "\"Wrong length of pre-allocated predict array\"", ")", "out_num_preds", "=", "ctypes", ".", "c_int64", "(", "0", ")", "ptr_indptr", ",", "type_ptr_indptr", ",", "__", "=", "c_int_array", "(", "csr", ".", "indptr", ")", "ptr_data", ",", "type_ptr_data", ",", "_", "=", "c_float_array", "(", "csr", ".", "data", ")", "assert", "csr", ".", "shape", "[", "1", "]", "<=", "MAX_INT32", "csr", ".", "indices", "=", "csr", ".", "indices", ".", "astype", "(", "np", ".", "int32", ",", "copy", "=", "False", ")", "_safe_call", "(", "_LIB", ".", "LGBM_BoosterPredictForCSR", "(", "self", ".", "handle", ",", "ptr_indptr", ",", "ctypes", ".", "c_int32", "(", "type_ptr_indptr", ")", ",", "csr", ".", "indices", ".", "ctypes", ".", "data_as", "(", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_int32", ")", ")", ",", "ptr_data", ",", "ctypes", ".", "c_int", "(", "type_ptr_data", ")", ",", "ctypes", ".", "c_int64", "(", "len", "(", "csr", ".", "indptr", ")", ")", ",", "ctypes", ".", "c_int64", "(", "len", "(", "csr", ".", "data", ")", ")", ",", "ctypes", ".", "c_int64", "(", "csr", ".", "shape", "[", "1", "]", ")", ",", "ctypes", ".", "c_int", "(", "predict_type", ")", ",", "ctypes", ".", "c_int", "(", "num_iteration", ")", ",", "c_str", "(", "self", ".", "pred_parameter", ")", ",", "ctypes", ".", "byref", "(", "out_num_preds", ")", ",", "preds", ".", "ctypes", ".", "data_as", "(", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_double", ")", ")", ")", ")", "if", "n_preds", "!=", "out_num_preds", ".", "value", ":", "raise", "ValueError", "(", "\"Wrong length for predict results\"", ")", "return", "preds", ",", "nrow", "nrow", "=", "len", "(", "csr", ".", "indptr", ")", "-", "1", "if", "nrow", ">", "MAX_INT32", ":", "sections", "=", "[", "0", "]", "+", "list", "(", "np", ".", "arange", "(", "start", "=", "MAX_INT32", ",", "stop", "=", "nrow", ",", "step", "=", "MAX_INT32", ")", ")", "+", "[", "nrow", "]", "# __get_num_preds() cannot work with nrow > MAX_INT32, so calculate overall number of predictions piecemeal", "n_preds", "=", "[", "self", ".", "__get_num_preds", "(", "num_iteration", ",", "i", ",", "predict_type", ")", "for", "i", "in", "np", ".", "diff", "(", "sections", ")", "]", "n_preds_sections", "=", "np", ".", "array", "(", "[", "0", "]", "+", "n_preds", ",", "dtype", "=", "np", ".", "intp", ")", ".", "cumsum", "(", ")", "preds", "=", "np", ".", "zeros", "(", "sum", "(", "n_preds", ")", ",", "dtype", "=", "np", ".", "float64", ")", "for", "(", "start_idx", ",", "end_idx", ")", ",", "(", "start_idx_pred", ",", "end_idx_pred", ")", "in", "zip_", "(", "zip_", "(", "sections", ",", "sections", "[", "1", ":", "]", ")", ",", "zip_", "(", "n_preds_sections", ",", "n_preds_sections", "[", "1", ":", "]", ")", ")", ":", "# avoid memory consumption by arrays concatenation operations", "inner_predict", "(", "csr", "[", "start_idx", ":", "end_idx", "]", ",", "num_iteration", ",", "predict_type", ",", "preds", "[", "start_idx_pred", ":", "end_idx_pred", "]", ")", "return", "preds", ",", "nrow", "else", ":", "return", "inner_predict", "(", "csr", ",", "num_iteration", ",", "predict_type", ")" ]
Predict for a CSR data.
[ "Predict", "for", "a", "CSR", "data", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L570-L619
22,880
Microsoft/LightGBM
python-package/lightgbm/basic.py
_InnerPredictor.__pred_for_csc
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) preds = np.zeros(n_preds, dtype=np.float64) out_num_preds = ctypes.c_int64(0) ptr_indptr, type_ptr_indptr, __ = c_int_array(csc.indptr) ptr_data, type_ptr_data, _ = c_float_array(csc.data) assert csc.shape[0] <= MAX_INT32 csc.indices = csc.indices.astype(np.int32, copy=False) _safe_call(_LIB.LGBM_BoosterPredictForCSC( self.handle, ptr_indptr, ctypes.c_int32(type_ptr_indptr), csc.indices.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)), ptr_data, ctypes.c_int(type_ptr_data), ctypes.c_int64(len(csc.indptr)), ctypes.c_int64(len(csc.data)), ctypes.c_int64(csc.shape[0]), ctypes.c_int(predict_type), ctypes.c_int(num_iteration), c_str(self.pred_parameter), ctypes.byref(out_num_preds), preds.ctypes.data_as(ctypes.POINTER(ctypes.c_double)))) if n_preds != out_num_preds.value: raise ValueError("Wrong length for predict results") return preds, nrow
python
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) preds = np.zeros(n_preds, dtype=np.float64) out_num_preds = ctypes.c_int64(0) ptr_indptr, type_ptr_indptr, __ = c_int_array(csc.indptr) ptr_data, type_ptr_data, _ = c_float_array(csc.data) assert csc.shape[0] <= MAX_INT32 csc.indices = csc.indices.astype(np.int32, copy=False) _safe_call(_LIB.LGBM_BoosterPredictForCSC( self.handle, ptr_indptr, ctypes.c_int32(type_ptr_indptr), csc.indices.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)), ptr_data, ctypes.c_int(type_ptr_data), ctypes.c_int64(len(csc.indptr)), ctypes.c_int64(len(csc.data)), ctypes.c_int64(csc.shape[0]), ctypes.c_int(predict_type), ctypes.c_int(num_iteration), c_str(self.pred_parameter), ctypes.byref(out_num_preds), preds.ctypes.data_as(ctypes.POINTER(ctypes.c_double)))) if n_preds != out_num_preds.value: raise ValueError("Wrong length for predict results") return preds, nrow
[ "def", "__pred_for_csc", "(", "self", ",", "csc", ",", "num_iteration", ",", "predict_type", ")", ":", "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", ")", "preds", "=", "np", ".", "zeros", "(", "n_preds", ",", "dtype", "=", "np", ".", "float64", ")", "out_num_preds", "=", "ctypes", ".", "c_int64", "(", "0", ")", "ptr_indptr", ",", "type_ptr_indptr", ",", "__", "=", "c_int_array", "(", "csc", ".", "indptr", ")", "ptr_data", ",", "type_ptr_data", ",", "_", "=", "c_float_array", "(", "csc", ".", "data", ")", "assert", "csc", ".", "shape", "[", "0", "]", "<=", "MAX_INT32", "csc", ".", "indices", "=", "csc", ".", "indices", ".", "astype", "(", "np", ".", "int32", ",", "copy", "=", "False", ")", "_safe_call", "(", "_LIB", ".", "LGBM_BoosterPredictForCSC", "(", "self", ".", "handle", ",", "ptr_indptr", ",", "ctypes", ".", "c_int32", "(", "type_ptr_indptr", ")", ",", "csc", ".", "indices", ".", "ctypes", ".", "data_as", "(", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_int32", ")", ")", ",", "ptr_data", ",", "ctypes", ".", "c_int", "(", "type_ptr_data", ")", ",", "ctypes", ".", "c_int64", "(", "len", "(", "csc", ".", "indptr", ")", ")", ",", "ctypes", ".", "c_int64", "(", "len", "(", "csc", ".", "data", ")", ")", ",", "ctypes", ".", "c_int64", "(", "csc", ".", "shape", "[", "0", "]", ")", ",", "ctypes", ".", "c_int", "(", "predict_type", ")", ",", "ctypes", ".", "c_int", "(", "num_iteration", ")", ",", "c_str", "(", "self", ".", "pred_parameter", ")", ",", "ctypes", ".", "byref", "(", "out_num_preds", ")", ",", "preds", ".", "ctypes", ".", "data_as", "(", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_double", ")", ")", ")", ")", "if", "n_preds", "!=", "out_num_preds", ".", "value", ":", "raise", "ValueError", "(", "\"Wrong length for predict results\"", ")", "return", "preds", ",", "nrow" ]
Predict for a CSC data.
[ "Predict", "for", "a", "CSC", "data", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L621-L653
22,881
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.__init_from_list_np2d
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))() else: ptr_data = (ctypes.POINTER(ctypes.c_float) * len(mats))() holders = [] type_ptr_data = None for i, mat in enumerate(mats): if len(mat.shape) != 2: raise ValueError('Input numpy.ndarray must be 2 dimensional') if mat.shape[1] != ncol: raise ValueError('Input arrays must have same number of columns') nrow[i] = mat.shape[0] if mat.dtype == np.float32 or mat.dtype == np.float64: mats[i] = np.array(mat.reshape(mat.size), dtype=mat.dtype, copy=False) else: # change non-float data to float data, need to copy mats[i] = np.array(mat.reshape(mat.size), dtype=np.float32) chunk_ptr_data, chunk_type_ptr_data, holder = c_float_array(mats[i]) if type_ptr_data is not None and chunk_type_ptr_data != type_ptr_data: raise ValueError('Input chunks must have same type') ptr_data[i] = chunk_ptr_data type_ptr_data = chunk_type_ptr_data holders.append(holder) self.handle = ctypes.c_void_p() _safe_call(_LIB.LGBM_DatasetCreateFromMats( ctypes.c_int(len(mats)), ctypes.cast(ptr_data, ctypes.POINTER(ctypes.POINTER(ctypes.c_double))), ctypes.c_int(type_ptr_data), nrow.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)), ctypes.c_int(ncol), ctypes.c_int(C_API_IS_ROW_MAJOR), c_str(params_str), ref_dataset, ctypes.byref(self.handle))) return self
python
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))() else: ptr_data = (ctypes.POINTER(ctypes.c_float) * len(mats))() holders = [] type_ptr_data = None for i, mat in enumerate(mats): if len(mat.shape) != 2: raise ValueError('Input numpy.ndarray must be 2 dimensional') if mat.shape[1] != ncol: raise ValueError('Input arrays must have same number of columns') nrow[i] = mat.shape[0] if mat.dtype == np.float32 or mat.dtype == np.float64: mats[i] = np.array(mat.reshape(mat.size), dtype=mat.dtype, copy=False) else: # change non-float data to float data, need to copy mats[i] = np.array(mat.reshape(mat.size), dtype=np.float32) chunk_ptr_data, chunk_type_ptr_data, holder = c_float_array(mats[i]) if type_ptr_data is not None and chunk_type_ptr_data != type_ptr_data: raise ValueError('Input chunks must have same type') ptr_data[i] = chunk_ptr_data type_ptr_data = chunk_type_ptr_data holders.append(holder) self.handle = ctypes.c_void_p() _safe_call(_LIB.LGBM_DatasetCreateFromMats( ctypes.c_int(len(mats)), ctypes.cast(ptr_data, ctypes.POINTER(ctypes.POINTER(ctypes.c_double))), ctypes.c_int(type_ptr_data), nrow.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)), ctypes.c_int(ncol), ctypes.c_int(C_API_IS_ROW_MAJOR), c_str(params_str), ref_dataset, ctypes.byref(self.handle))) return self
[ "def", "__init_from_list_np2d", "(", "self", ",", "mats", ",", "params_str", ",", "ref_dataset", ")", ":", "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", ")", ")", "(", ")", "else", ":", "ptr_data", "=", "(", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_float", ")", "*", "len", "(", "mats", ")", ")", "(", ")", "holders", "=", "[", "]", "type_ptr_data", "=", "None", "for", "i", ",", "mat", "in", "enumerate", "(", "mats", ")", ":", "if", "len", "(", "mat", ".", "shape", ")", "!=", "2", ":", "raise", "ValueError", "(", "'Input numpy.ndarray must be 2 dimensional'", ")", "if", "mat", ".", "shape", "[", "1", "]", "!=", "ncol", ":", "raise", "ValueError", "(", "'Input arrays must have same number of columns'", ")", "nrow", "[", "i", "]", "=", "mat", ".", "shape", "[", "0", "]", "if", "mat", ".", "dtype", "==", "np", ".", "float32", "or", "mat", ".", "dtype", "==", "np", ".", "float64", ":", "mats", "[", "i", "]", "=", "np", ".", "array", "(", "mat", ".", "reshape", "(", "mat", ".", "size", ")", ",", "dtype", "=", "mat", ".", "dtype", ",", "copy", "=", "False", ")", "else", ":", "# change non-float data to float data, need to copy", "mats", "[", "i", "]", "=", "np", ".", "array", "(", "mat", ".", "reshape", "(", "mat", ".", "size", ")", ",", "dtype", "=", "np", ".", "float32", ")", "chunk_ptr_data", ",", "chunk_type_ptr_data", ",", "holder", "=", "c_float_array", "(", "mats", "[", "i", "]", ")", "if", "type_ptr_data", "is", "not", "None", "and", "chunk_type_ptr_data", "!=", "type_ptr_data", ":", "raise", "ValueError", "(", "'Input chunks must have same type'", ")", "ptr_data", "[", "i", "]", "=", "chunk_ptr_data", "type_ptr_data", "=", "chunk_type_ptr_data", "holders", ".", "append", "(", "holder", ")", "self", ".", "handle", "=", "ctypes", ".", "c_void_p", "(", ")", "_safe_call", "(", "_LIB", ".", "LGBM_DatasetCreateFromMats", "(", "ctypes", ".", "c_int", "(", "len", "(", "mats", ")", ")", ",", "ctypes", ".", "cast", "(", "ptr_data", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_double", ")", ")", ")", ",", "ctypes", ".", "c_int", "(", "type_ptr_data", ")", ",", "nrow", ".", "ctypes", ".", "data_as", "(", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_int32", ")", ")", ",", "ctypes", ".", "c_int", "(", "ncol", ")", ",", "ctypes", ".", "c_int", "(", "C_API_IS_ROW_MAJOR", ")", ",", "c_str", "(", "params_str", ")", ",", "ref_dataset", ",", "ctypes", ".", "byref", "(", "self", ".", "handle", ")", ")", ")", "return", "self" ]
Initialize data from a list of 2-D numpy matrices.
[ "Initialize", "data", "from", "a", "list", "of", "2", "-", "D", "numpy", "matrices", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L872-L917
22,882
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.construct
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 self._lazy_init(self.data, label=self.label, reference=self.reference, weight=self.weight, group=self.group, init_score=self.init_score, predictor=self._predictor, silent=self.silent, feature_name=self.feature_name, params=self.params) else: # construct subset used_indices = list_to_1d_numpy(self.used_indices, np.int32, name='used_indices') assert used_indices.flags.c_contiguous if self.reference.group is not None: group_info = np.array(self.reference.group).astype(int) _, self.group = np.unique(np.repeat(range_(len(group_info)), repeats=group_info)[self.used_indices], return_counts=True) self.handle = ctypes.c_void_p() params_str = param_dict_to_str(self.params) _safe_call(_LIB.LGBM_DatasetGetSubset( self.reference.construct().handle, used_indices.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)), ctypes.c_int(used_indices.shape[0]), c_str(params_str), ctypes.byref(self.handle))) self.data = self.reference.data self.get_data() if self.group is not None: self.set_group(self.group) if self.get_label() is None: raise ValueError("Label should not be None.") else: # create train self._lazy_init(self.data, label=self.label, weight=self.weight, group=self.group, init_score=self.init_score, predictor=self._predictor, silent=self.silent, feature_name=self.feature_name, categorical_feature=self.categorical_feature, params=self.params) if self.free_raw_data: self.data = None return self
python
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 self._lazy_init(self.data, label=self.label, reference=self.reference, weight=self.weight, group=self.group, init_score=self.init_score, predictor=self._predictor, silent=self.silent, feature_name=self.feature_name, params=self.params) else: # construct subset used_indices = list_to_1d_numpy(self.used_indices, np.int32, name='used_indices') assert used_indices.flags.c_contiguous if self.reference.group is not None: group_info = np.array(self.reference.group).astype(int) _, self.group = np.unique(np.repeat(range_(len(group_info)), repeats=group_info)[self.used_indices], return_counts=True) self.handle = ctypes.c_void_p() params_str = param_dict_to_str(self.params) _safe_call(_LIB.LGBM_DatasetGetSubset( self.reference.construct().handle, used_indices.ctypes.data_as(ctypes.POINTER(ctypes.c_int32)), ctypes.c_int(used_indices.shape[0]), c_str(params_str), ctypes.byref(self.handle))) self.data = self.reference.data self.get_data() if self.group is not None: self.set_group(self.group) if self.get_label() is None: raise ValueError("Label should not be None.") else: # create train self._lazy_init(self.data, label=self.label, weight=self.weight, group=self.group, init_score=self.init_score, predictor=self._predictor, silent=self.silent, feature_name=self.feature_name, categorical_feature=self.categorical_feature, params=self.params) if self.free_raw_data: self.data = None return self
[ "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", "(", "self", ".", "data", ",", "label", "=", "self", ".", "label", ",", "reference", "=", "self", ".", "reference", ",", "weight", "=", "self", ".", "weight", ",", "group", "=", "self", ".", "group", ",", "init_score", "=", "self", ".", "init_score", ",", "predictor", "=", "self", ".", "_predictor", ",", "silent", "=", "self", ".", "silent", ",", "feature_name", "=", "self", ".", "feature_name", ",", "params", "=", "self", ".", "params", ")", "else", ":", "# construct subset", "used_indices", "=", "list_to_1d_numpy", "(", "self", ".", "used_indices", ",", "np", ".", "int32", ",", "name", "=", "'used_indices'", ")", "assert", "used_indices", ".", "flags", ".", "c_contiguous", "if", "self", ".", "reference", ".", "group", "is", "not", "None", ":", "group_info", "=", "np", ".", "array", "(", "self", ".", "reference", ".", "group", ")", ".", "astype", "(", "int", ")", "_", ",", "self", ".", "group", "=", "np", ".", "unique", "(", "np", ".", "repeat", "(", "range_", "(", "len", "(", "group_info", ")", ")", ",", "repeats", "=", "group_info", ")", "[", "self", ".", "used_indices", "]", ",", "return_counts", "=", "True", ")", "self", ".", "handle", "=", "ctypes", ".", "c_void_p", "(", ")", "params_str", "=", "param_dict_to_str", "(", "self", ".", "params", ")", "_safe_call", "(", "_LIB", ".", "LGBM_DatasetGetSubset", "(", "self", ".", "reference", ".", "construct", "(", ")", ".", "handle", ",", "used_indices", ".", "ctypes", ".", "data_as", "(", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_int32", ")", ")", ",", "ctypes", ".", "c_int", "(", "used_indices", ".", "shape", "[", "0", "]", ")", ",", "c_str", "(", "params_str", ")", ",", "ctypes", ".", "byref", "(", "self", ".", "handle", ")", ")", ")", "self", ".", "data", "=", "self", ".", "reference", ".", "data", "self", ".", "get_data", "(", ")", "if", "self", ".", "group", "is", "not", "None", ":", "self", ".", "set_group", "(", "self", ".", "group", ")", "if", "self", ".", "get_label", "(", ")", "is", "None", ":", "raise", "ValueError", "(", "\"Label should not be None.\"", ")", "else", ":", "# create train", "self", ".", "_lazy_init", "(", "self", ".", "data", ",", "label", "=", "self", ".", "label", ",", "weight", "=", "self", ".", "weight", ",", "group", "=", "self", ".", "group", ",", "init_score", "=", "self", ".", "init_score", ",", "predictor", "=", "self", ".", "_predictor", ",", "silent", "=", "self", ".", "silent", ",", "feature_name", "=", "self", ".", "feature_name", ",", "categorical_feature", "=", "self", ".", "categorical_feature", ",", "params", "=", "self", ".", "params", ")", "if", "self", ".", "free_raw_data", ":", "self", ".", "data", "=", "None", "return", "self" ]
Lazy init. Returns ------- self : Dataset Constructed Dataset object.
[ "Lazy", "init", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L971-L1018
22,883
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.create_valid
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.sparse or list of numpy arrays Data source of Dataset. If string, it represents the path to txt file. label : list, numpy 1-D array, pandas Series / one-column DataFrame or None, optional (default=None) Label of the data. weight : list, numpy 1-D array, pandas Series or None, optional (default=None) Weight for each instance. group : list, numpy 1-D array, pandas Series or None, optional (default=None) Group/query size for Dataset. init_score : list, numpy 1-D array, pandas Series or None, optional (default=None) Init score for Dataset. silent : bool, optional (default=False) Whether to print messages during construction. params : dict or None, optional (default=None) Other parameters for validation Dataset. Returns ------- valid : Dataset Validation Dataset with reference to self. """ ret = Dataset(data, label=label, reference=self, weight=weight, group=group, init_score=init_score, silent=silent, params=params, free_raw_data=self.free_raw_data) ret._predictor = self._predictor ret.pandas_categorical = self.pandas_categorical return ret
python
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.sparse or list of numpy arrays Data source of Dataset. If string, it represents the path to txt file. label : list, numpy 1-D array, pandas Series / one-column DataFrame or None, optional (default=None) Label of the data. weight : list, numpy 1-D array, pandas Series or None, optional (default=None) Weight for each instance. group : list, numpy 1-D array, pandas Series or None, optional (default=None) Group/query size for Dataset. init_score : list, numpy 1-D array, pandas Series or None, optional (default=None) Init score for Dataset. silent : bool, optional (default=False) Whether to print messages during construction. params : dict or None, optional (default=None) Other parameters for validation Dataset. Returns ------- valid : Dataset Validation Dataset with reference to self. """ ret = Dataset(data, label=label, reference=self, weight=weight, group=group, init_score=init_score, silent=silent, params=params, free_raw_data=self.free_raw_data) ret._predictor = self._predictor ret.pandas_categorical = self.pandas_categorical return ret
[ "def", "create_valid", "(", "self", ",", "data", ",", "label", "=", "None", ",", "weight", "=", "None", ",", "group", "=", "None", ",", "init_score", "=", "None", ",", "silent", "=", "False", ",", "params", "=", "None", ")", ":", "ret", "=", "Dataset", "(", "data", ",", "label", "=", "label", ",", "reference", "=", "self", ",", "weight", "=", "weight", ",", "group", "=", "group", ",", "init_score", "=", "init_score", ",", "silent", "=", "silent", ",", "params", "=", "params", ",", "free_raw_data", "=", "self", ".", "free_raw_data", ")", "ret", ".", "_predictor", "=", "self", ".", "_predictor", "ret", ".", "pandas_categorical", "=", "self", ".", "pandas_categorical", "return", "ret" ]
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, numpy 1-D array, pandas Series / one-column DataFrame or None, optional (default=None) Label of the data. weight : list, numpy 1-D array, pandas Series or None, optional (default=None) Weight for each instance. group : list, numpy 1-D array, pandas Series or None, optional (default=None) Group/query size for Dataset. init_score : list, numpy 1-D array, pandas Series or None, optional (default=None) Init score for Dataset. silent : bool, optional (default=False) Whether to print messages during construction. params : dict or None, optional (default=None) Other parameters for validation Dataset. Returns ------- valid : Dataset Validation Dataset with reference to self.
[ "Create", "validation", "data", "align", "with", "current", "Dataset", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1020-L1052
22,884
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.subset
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 constructor. Returns ------- subset : Dataset Subset of the current Dataset. """ if params is None: params = self.params ret = Dataset(None, reference=self, feature_name=self.feature_name, categorical_feature=self.categorical_feature, params=params, free_raw_data=self.free_raw_data) ret._predictor = self._predictor ret.pandas_categorical = self.pandas_categorical ret.used_indices = used_indices return ret
python
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 constructor. Returns ------- subset : Dataset Subset of the current Dataset. """ if params is None: params = self.params ret = Dataset(None, reference=self, feature_name=self.feature_name, categorical_feature=self.categorical_feature, params=params, free_raw_data=self.free_raw_data) ret._predictor = self._predictor ret.pandas_categorical = self.pandas_categorical ret.used_indices = used_indices return ret
[ "def", "subset", "(", "self", ",", "used_indices", ",", "params", "=", "None", ")", ":", "if", "params", "is", "None", ":", "params", "=", "self", ".", "params", "ret", "=", "Dataset", "(", "None", ",", "reference", "=", "self", ",", "feature_name", "=", "self", ".", "feature_name", ",", "categorical_feature", "=", "self", ".", "categorical_feature", ",", "params", "=", "params", ",", "free_raw_data", "=", "self", ".", "free_raw_data", ")", "ret", ".", "_predictor", "=", "self", ".", "_predictor", "ret", ".", "pandas_categorical", "=", "self", ".", "pandas_categorical", "ret", ".", "used_indices", "=", "used_indices", "return", "ret" ]
Get subset of current Dataset. 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 ------- subset : Dataset Subset of the current Dataset.
[ "Get", "subset", "of", "current", "Dataset", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1054-L1077
22,885
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.save_binary
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( self.construct().handle, c_str(filename))) return self
python
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( self.construct().handle, c_str(filename))) return self
[ "def", "save_binary", "(", "self", ",", "filename", ")", ":", "_safe_call", "(", "_LIB", ".", "LGBM_DatasetSaveBinary", "(", "self", ".", "construct", "(", ")", ".", "handle", ",", "c_str", "(", "filename", ")", ")", ")", "return", "self" ]
Save Dataset to a binary file. Parameters ---------- filename : string Name of the output file. Returns ------- self : Dataset Returns self.
[ "Save", "Dataset", "to", "a", "binary", "file", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1079-L1095
22,886
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.set_field
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 ------- self : Dataset Dataset with set property. """ if self.handle is None: raise Exception("Cannot set %s before construct dataset" % field_name) if data is None: # set to None _safe_call(_LIB.LGBM_DatasetSetField( self.handle, c_str(field_name), None, ctypes.c_int(0), ctypes.c_int(FIELD_TYPE_MAPPER[field_name]))) return self dtype = np.float32 if field_name == 'group': dtype = np.int32 elif field_name == 'init_score': dtype = np.float64 data = list_to_1d_numpy(data, dtype, name=field_name) if data.dtype == np.float32 or data.dtype == np.float64: ptr_data, type_data, _ = c_float_array(data) elif data.dtype == np.int32: ptr_data, type_data, _ = c_int_array(data) else: raise TypeError("Excepted np.float32/64 or np.int32, meet type({})".format(data.dtype)) if type_data != FIELD_TYPE_MAPPER[field_name]: raise TypeError("Input type error for set_field") _safe_call(_LIB.LGBM_DatasetSetField( self.handle, c_str(field_name), ptr_data, ctypes.c_int(len(data)), ctypes.c_int(type_data))) return self
python
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 ------- self : Dataset Dataset with set property. """ if self.handle is None: raise Exception("Cannot set %s before construct dataset" % field_name) if data is None: # set to None _safe_call(_LIB.LGBM_DatasetSetField( self.handle, c_str(field_name), None, ctypes.c_int(0), ctypes.c_int(FIELD_TYPE_MAPPER[field_name]))) return self dtype = np.float32 if field_name == 'group': dtype = np.int32 elif field_name == 'init_score': dtype = np.float64 data = list_to_1d_numpy(data, dtype, name=field_name) if data.dtype == np.float32 or data.dtype == np.float64: ptr_data, type_data, _ = c_float_array(data) elif data.dtype == np.int32: ptr_data, type_data, _ = c_int_array(data) else: raise TypeError("Excepted np.float32/64 or np.int32, meet type({})".format(data.dtype)) if type_data != FIELD_TYPE_MAPPER[field_name]: raise TypeError("Input type error for set_field") _safe_call(_LIB.LGBM_DatasetSetField( self.handle, c_str(field_name), ptr_data, ctypes.c_int(len(data)), ctypes.c_int(type_data))) return self
[ "def", "set_field", "(", "self", ",", "field_name", ",", "data", ")", ":", "if", "self", ".", "handle", "is", "None", ":", "raise", "Exception", "(", "\"Cannot set %s before construct dataset\"", "%", "field_name", ")", "if", "data", "is", "None", ":", "# set to None", "_safe_call", "(", "_LIB", ".", "LGBM_DatasetSetField", "(", "self", ".", "handle", ",", "c_str", "(", "field_name", ")", ",", "None", ",", "ctypes", ".", "c_int", "(", "0", ")", ",", "ctypes", ".", "c_int", "(", "FIELD_TYPE_MAPPER", "[", "field_name", "]", ")", ")", ")", "return", "self", "dtype", "=", "np", ".", "float32", "if", "field_name", "==", "'group'", ":", "dtype", "=", "np", ".", "int32", "elif", "field_name", "==", "'init_score'", ":", "dtype", "=", "np", ".", "float64", "data", "=", "list_to_1d_numpy", "(", "data", ",", "dtype", ",", "name", "=", "field_name", ")", "if", "data", ".", "dtype", "==", "np", ".", "float32", "or", "data", ".", "dtype", "==", "np", ".", "float64", ":", "ptr_data", ",", "type_data", ",", "_", "=", "c_float_array", "(", "data", ")", "elif", "data", ".", "dtype", "==", "np", ".", "int32", ":", "ptr_data", ",", "type_data", ",", "_", "=", "c_int_array", "(", "data", ")", "else", ":", "raise", "TypeError", "(", "\"Excepted np.float32/64 or np.int32, meet type({})\"", ".", "format", "(", "data", ".", "dtype", ")", ")", "if", "type_data", "!=", "FIELD_TYPE_MAPPER", "[", "field_name", "]", ":", "raise", "TypeError", "(", "\"Input type error for set_field\"", ")", "_safe_call", "(", "_LIB", ".", "LGBM_DatasetSetField", "(", "self", ".", "handle", ",", "c_str", "(", "field_name", ")", ",", "ptr_data", ",", "ctypes", ".", "c_int", "(", "len", "(", "data", ")", ")", ",", "ctypes", ".", "c_int", "(", "type_data", ")", ")", ")", "return", "self" ]
Set property into the Dataset. 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 Dataset with set property.
[ "Set", "property", "into", "the", "Dataset", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1114-L1160
22,887
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.get_field
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. """ if self.handle is None: raise Exception("Cannot get %s before construct Dataset" % field_name) tmp_out_len = ctypes.c_int() out_type = ctypes.c_int() ret = ctypes.POINTER(ctypes.c_void_p)() _safe_call(_LIB.LGBM_DatasetGetField( self.handle, c_str(field_name), ctypes.byref(tmp_out_len), ctypes.byref(ret), ctypes.byref(out_type))) if out_type.value != FIELD_TYPE_MAPPER[field_name]: raise TypeError("Return type error for get_field") if tmp_out_len.value == 0: return None if out_type.value == C_API_DTYPE_INT32: return cint32_array_to_numpy(ctypes.cast(ret, ctypes.POINTER(ctypes.c_int32)), tmp_out_len.value) elif out_type.value == C_API_DTYPE_FLOAT32: return cfloat32_array_to_numpy(ctypes.cast(ret, ctypes.POINTER(ctypes.c_float)), tmp_out_len.value) elif out_type.value == C_API_DTYPE_FLOAT64: return cfloat64_array_to_numpy(ctypes.cast(ret, ctypes.POINTER(ctypes.c_double)), tmp_out_len.value) elif out_type.value == C_API_DTYPE_INT8: return cint8_array_to_numpy(ctypes.cast(ret, ctypes.POINTER(ctypes.c_int8)), tmp_out_len.value) else: raise TypeError("Unknown type")
python
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. """ if self.handle is None: raise Exception("Cannot get %s before construct Dataset" % field_name) tmp_out_len = ctypes.c_int() out_type = ctypes.c_int() ret = ctypes.POINTER(ctypes.c_void_p)() _safe_call(_LIB.LGBM_DatasetGetField( self.handle, c_str(field_name), ctypes.byref(tmp_out_len), ctypes.byref(ret), ctypes.byref(out_type))) if out_type.value != FIELD_TYPE_MAPPER[field_name]: raise TypeError("Return type error for get_field") if tmp_out_len.value == 0: return None if out_type.value == C_API_DTYPE_INT32: return cint32_array_to_numpy(ctypes.cast(ret, ctypes.POINTER(ctypes.c_int32)), tmp_out_len.value) elif out_type.value == C_API_DTYPE_FLOAT32: return cfloat32_array_to_numpy(ctypes.cast(ret, ctypes.POINTER(ctypes.c_float)), tmp_out_len.value) elif out_type.value == C_API_DTYPE_FLOAT64: return cfloat64_array_to_numpy(ctypes.cast(ret, ctypes.POINTER(ctypes.c_double)), tmp_out_len.value) elif out_type.value == C_API_DTYPE_INT8: return cint8_array_to_numpy(ctypes.cast(ret, ctypes.POINTER(ctypes.c_int8)), tmp_out_len.value) else: raise TypeError("Unknown type")
[ "def", "get_field", "(", "self", ",", "field_name", ")", ":", "if", "self", ".", "handle", "is", "None", ":", "raise", "Exception", "(", "\"Cannot get %s before construct Dataset\"", "%", "field_name", ")", "tmp_out_len", "=", "ctypes", ".", "c_int", "(", ")", "out_type", "=", "ctypes", ".", "c_int", "(", ")", "ret", "=", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_void_p", ")", "(", ")", "_safe_call", "(", "_LIB", ".", "LGBM_DatasetGetField", "(", "self", ".", "handle", ",", "c_str", "(", "field_name", ")", ",", "ctypes", ".", "byref", "(", "tmp_out_len", ")", ",", "ctypes", ".", "byref", "(", "ret", ")", ",", "ctypes", ".", "byref", "(", "out_type", ")", ")", ")", "if", "out_type", ".", "value", "!=", "FIELD_TYPE_MAPPER", "[", "field_name", "]", ":", "raise", "TypeError", "(", "\"Return type error for get_field\"", ")", "if", "tmp_out_len", ".", "value", "==", "0", ":", "return", "None", "if", "out_type", ".", "value", "==", "C_API_DTYPE_INT32", ":", "return", "cint32_array_to_numpy", "(", "ctypes", ".", "cast", "(", "ret", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_int32", ")", ")", ",", "tmp_out_len", ".", "value", ")", "elif", "out_type", ".", "value", "==", "C_API_DTYPE_FLOAT32", ":", "return", "cfloat32_array_to_numpy", "(", "ctypes", ".", "cast", "(", "ret", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_float", ")", ")", ",", "tmp_out_len", ".", "value", ")", "elif", "out_type", ".", "value", "==", "C_API_DTYPE_FLOAT64", ":", "return", "cfloat64_array_to_numpy", "(", "ctypes", ".", "cast", "(", "ret", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_double", ")", ")", ",", "tmp_out_len", ".", "value", ")", "elif", "out_type", ".", "value", "==", "C_API_DTYPE_INT8", ":", "return", "cint8_array_to_numpy", "(", "ctypes", ".", "cast", "(", "ret", ",", "ctypes", ".", "POINTER", "(", "ctypes", ".", "c_int8", ")", ")", ",", "tmp_out_len", ".", "value", ")", "else", ":", "raise", "TypeError", "(", "\"Unknown type\"", ")" ]
Get property from the Dataset. 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", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1162-L1199
22,888
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.set_categorical_feature
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. """ if self.categorical_feature == categorical_feature: return self if self.data is not None: if self.categorical_feature is None: self.categorical_feature = categorical_feature return self._free_handle() elif categorical_feature == 'auto': warnings.warn('Using categorical_feature in Dataset.') return self else: warnings.warn('categorical_feature in Dataset is overridden.\n' 'New categorical_feature is {}'.format(sorted(list(categorical_feature)))) self.categorical_feature = categorical_feature return self._free_handle() else: raise LightGBMError("Cannot set categorical feature after freed raw data, " "set free_raw_data=False when construct Dataset to avoid this.")
python
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. """ if self.categorical_feature == categorical_feature: return self if self.data is not None: if self.categorical_feature is None: self.categorical_feature = categorical_feature return self._free_handle() elif categorical_feature == 'auto': warnings.warn('Using categorical_feature in Dataset.') return self else: warnings.warn('categorical_feature in Dataset is overridden.\n' 'New categorical_feature is {}'.format(sorted(list(categorical_feature)))) self.categorical_feature = categorical_feature return self._free_handle() else: raise LightGBMError("Cannot set categorical feature after freed raw data, " "set free_raw_data=False when construct Dataset to avoid this.")
[ "def", "set_categorical_feature", "(", "self", ",", "categorical_feature", ")", ":", "if", "self", ".", "categorical_feature", "==", "categorical_feature", ":", "return", "self", "if", "self", ".", "data", "is", "not", "None", ":", "if", "self", ".", "categorical_feature", "is", "None", ":", "self", ".", "categorical_feature", "=", "categorical_feature", "return", "self", ".", "_free_handle", "(", ")", "elif", "categorical_feature", "==", "'auto'", ":", "warnings", ".", "warn", "(", "'Using categorical_feature in Dataset.'", ")", "return", "self", "else", ":", "warnings", ".", "warn", "(", "'categorical_feature in Dataset is overridden.\\n'", "'New categorical_feature is {}'", ".", "format", "(", "sorted", "(", "list", "(", "categorical_feature", ")", ")", ")", ")", "self", ".", "categorical_feature", "=", "categorical_feature", "return", "self", ".", "_free_handle", "(", ")", "else", ":", "raise", "LightGBMError", "(", "\"Cannot set categorical feature after freed raw data, \"", "\"set free_raw_data=False when construct Dataset to avoid this.\"", ")" ]
Set categorical features. Parameters ---------- categorical_feature : list of int or strings Names or indices of categorical features. Returns ------- self : Dataset Dataset with set categorical features.
[ "Set", "categorical", "features", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1201-L1230
22,889
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset._set_predictor
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 self.data is not None: self._predictor = predictor return self._free_handle() else: raise LightGBMError("Cannot set predictor after freed raw data, " "set free_raw_data=False when construct Dataset to avoid this.")
python
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 self.data is not None: self._predictor = predictor return self._free_handle() else: raise LightGBMError("Cannot set predictor after freed raw data, " "set free_raw_data=False when construct Dataset to avoid this.")
[ "def", "_set_predictor", "(", "self", ",", "predictor", ")", ":", "if", "predictor", "is", "self", ".", "_predictor", ":", "return", "self", "if", "self", ".", "data", "is", "not", "None", ":", "self", ".", "_predictor", "=", "predictor", "return", "self", ".", "_free_handle", "(", ")", "else", ":", "raise", "LightGBMError", "(", "\"Cannot set predictor after freed raw data, \"", "\"set free_raw_data=False when construct Dataset to avoid this.\"", ")" ]
Set predictor for continued training. It is not recommended for user to call this function. Please use init_model argument in engine.train() or engine.cv() instead.
[ "Set", "predictor", "for", "continued", "training", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1232-L1245
22,890
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.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. """ self.set_categorical_feature(reference.categorical_feature) \ .set_feature_name(reference.feature_name) \ ._set_predictor(reference._predictor) # we're done if self and reference share a common upstrem reference if self.get_ref_chain().intersection(reference.get_ref_chain()): return self if self.data is not None: self.reference = reference return self._free_handle() else: raise LightGBMError("Cannot set reference after freed raw data, " "set free_raw_data=False when construct Dataset to avoid this.")
python
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. """ self.set_categorical_feature(reference.categorical_feature) \ .set_feature_name(reference.feature_name) \ ._set_predictor(reference._predictor) # we're done if self and reference share a common upstrem reference if self.get_ref_chain().intersection(reference.get_ref_chain()): return self if self.data is not None: self.reference = reference return self._free_handle() else: raise LightGBMError("Cannot set reference after freed raw data, " "set free_raw_data=False when construct Dataset to avoid this.")
[ "def", "set_reference", "(", "self", ",", "reference", ")", ":", "self", ".", "set_categorical_feature", "(", "reference", ".", "categorical_feature", ")", ".", "set_feature_name", "(", "reference", ".", "feature_name", ")", ".", "_set_predictor", "(", "reference", ".", "_predictor", ")", "# we're done if self and reference share a common upstrem reference", "if", "self", ".", "get_ref_chain", "(", ")", ".", "intersection", "(", "reference", ".", "get_ref_chain", "(", ")", ")", ":", "return", "self", "if", "self", ".", "data", "is", "not", "None", ":", "self", ".", "reference", "=", "reference", "return", "self", ".", "_free_handle", "(", ")", "else", ":", "raise", "LightGBMError", "(", "\"Cannot set reference after freed raw data, \"", "\"set free_raw_data=False when construct Dataset to avoid this.\"", ")" ]
Set reference Dataset. 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", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1247-L1271
22,891
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.set_feature_name
def set_feature_name(self, feature_name): """Set feature name. Parameters ---------- feature_name : list of strings Feature names. Returns ------- self : Dataset Dataset with set feature name. """ if feature_name != 'auto': self.feature_name = feature_name if self.handle is not None and feature_name is not None and feature_name != 'auto': if len(feature_name) != self.num_feature(): raise ValueError("Length of feature_name({}) and num_feature({}) don't match" .format(len(feature_name), self.num_feature())) c_feature_name = [c_str(name) for name in feature_name] _safe_call(_LIB.LGBM_DatasetSetFeatureNames( self.handle, c_array(ctypes.c_char_p, c_feature_name), ctypes.c_int(len(feature_name)))) return self
python
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': self.feature_name = feature_name if self.handle is not None and feature_name is not None and feature_name != 'auto': if len(feature_name) != self.num_feature(): raise ValueError("Length of feature_name({}) and num_feature({}) don't match" .format(len(feature_name), self.num_feature())) c_feature_name = [c_str(name) for name in feature_name] _safe_call(_LIB.LGBM_DatasetSetFeatureNames( self.handle, c_array(ctypes.c_char_p, c_feature_name), ctypes.c_int(len(feature_name)))) return self
[ "def", "set_feature_name", "(", "self", ",", "feature_name", ")", ":", "if", "feature_name", "!=", "'auto'", ":", "self", ".", "feature_name", "=", "feature_name", "if", "self", ".", "handle", "is", "not", "None", "and", "feature_name", "is", "not", "None", "and", "feature_name", "!=", "'auto'", ":", "if", "len", "(", "feature_name", ")", "!=", "self", ".", "num_feature", "(", ")", ":", "raise", "ValueError", "(", "\"Length of feature_name({}) and num_feature({}) don't match\"", ".", "format", "(", "len", "(", "feature_name", ")", ",", "self", ".", "num_feature", "(", ")", ")", ")", "c_feature_name", "=", "[", "c_str", "(", "name", ")", "for", "name", "in", "feature_name", "]", "_safe_call", "(", "_LIB", ".", "LGBM_DatasetSetFeatureNames", "(", "self", ".", "handle", ",", "c_array", "(", "ctypes", ".", "c_char_p", ",", "c_feature_name", ")", ",", "ctypes", ".", "c_int", "(", "len", "(", "feature_name", ")", ")", ")", ")", "return", "self" ]
Set feature name. Parameters ---------- feature_name : list of strings Feature names. Returns ------- self : Dataset Dataset with set feature name.
[ "Set", "feature", "name", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1273-L1297
22,892
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.set_label
def set_label(self, label): """Set label of Dataset. Parameters ---------- label : list, numpy 1-D array, pandas Series / one-column DataFrame or None The label information to be set into Dataset. Returns ------- self : Dataset Dataset with set label. """ self.label = label if self.handle is not None: label = list_to_1d_numpy(_label_from_pandas(label), name='label') self.set_field('label', label) return self
python
def set_label(self, label): """Set label of Dataset. Parameters ---------- label : list, numpy 1-D array, pandas Series / one-column DataFrame or None The label information to be set into Dataset. Returns ------- self : Dataset Dataset with set label. """ self.label = label if self.handle is not None: label = list_to_1d_numpy(_label_from_pandas(label), name='label') self.set_field('label', label) return self
[ "def", "set_label", "(", "self", ",", "label", ")", ":", "self", ".", "label", "=", "label", "if", "self", ".", "handle", "is", "not", "None", ":", "label", "=", "list_to_1d_numpy", "(", "_label_from_pandas", "(", "label", ")", ",", "name", "=", "'label'", ")", "self", ".", "set_field", "(", "'label'", ",", "label", ")", "return", "self" ]
Set label of Dataset. Parameters ---------- label : list, numpy 1-D array, pandas Series / one-column DataFrame or None The label information to be set into Dataset. Returns ------- self : Dataset Dataset with set label.
[ "Set", "label", "of", "Dataset", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1299-L1316
22,893
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.set_weight
def set_weight(self, weight): """Set weight of each instance. Parameters ---------- weight : list, numpy 1-D array, pandas Series or None Weight to be set for each data point. Returns ------- self : Dataset Dataset with set weight. """ if weight is not None and np.all(weight == 1): weight = None self.weight = weight if self.handle is not None and weight is not None: weight = list_to_1d_numpy(weight, name='weight') self.set_field('weight', weight) return self
python
def set_weight(self, weight): """Set weight of each instance. Parameters ---------- weight : list, numpy 1-D array, pandas Series or None Weight to be set for each data point. Returns ------- self : Dataset Dataset with set weight. """ if weight is not None and np.all(weight == 1): weight = None self.weight = weight if self.handle is not None and weight is not None: weight = list_to_1d_numpy(weight, name='weight') self.set_field('weight', weight) return self
[ "def", "set_weight", "(", "self", ",", "weight", ")", ":", "if", "weight", "is", "not", "None", "and", "np", ".", "all", "(", "weight", "==", "1", ")", ":", "weight", "=", "None", "self", ".", "weight", "=", "weight", "if", "self", ".", "handle", "is", "not", "None", "and", "weight", "is", "not", "None", ":", "weight", "=", "list_to_1d_numpy", "(", "weight", ",", "name", "=", "'weight'", ")", "self", ".", "set_field", "(", "'weight'", ",", "weight", ")", "return", "self" ]
Set weight of each instance. Parameters ---------- weight : list, numpy 1-D array, pandas Series or None Weight to be set for each data point. Returns ------- self : Dataset Dataset with set weight.
[ "Set", "weight", "of", "each", "instance", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1318-L1337
22,894
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.set_init_score
def set_init_score(self, init_score): """Set init score of Booster to start from. Parameters ---------- init_score : list, numpy 1-D array, pandas Series or None Init score for Booster. Returns ------- self : Dataset Dataset with set init score. """ self.init_score = init_score if self.handle is not None and init_score is not None: init_score = list_to_1d_numpy(init_score, np.float64, name='init_score') self.set_field('init_score', init_score) return self
python
def set_init_score(self, init_score): """Set init score of Booster to start from. Parameters ---------- init_score : list, numpy 1-D array, pandas Series or None Init score for Booster. Returns ------- self : Dataset Dataset with set init score. """ self.init_score = init_score if self.handle is not None and init_score is not None: init_score = list_to_1d_numpy(init_score, np.float64, name='init_score') self.set_field('init_score', init_score) return self
[ "def", "set_init_score", "(", "self", ",", "init_score", ")", ":", "self", ".", "init_score", "=", "init_score", "if", "self", ".", "handle", "is", "not", "None", "and", "init_score", "is", "not", "None", ":", "init_score", "=", "list_to_1d_numpy", "(", "init_score", ",", "np", ".", "float64", ",", "name", "=", "'init_score'", ")", "self", ".", "set_field", "(", "'init_score'", ",", "init_score", ")", "return", "self" ]
Set init score of Booster to start from. Parameters ---------- init_score : list, numpy 1-D array, pandas Series or None Init score for Booster. Returns ------- self : Dataset Dataset with set init score.
[ "Set", "init", "score", "of", "Booster", "to", "start", "from", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1339-L1356
22,895
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.get_label
def get_label(self): """Get the label of the Dataset. Returns ------- label : numpy array or None The label information from the Dataset. """ if self.label is None: self.label = self.get_field('label') return self.label
python
def get_label(self): """Get the label of the Dataset. Returns ------- label : numpy array or None The label information from the Dataset. """ if self.label is None: self.label = self.get_field('label') return self.label
[ "def", "get_label", "(", "self", ")", ":", "if", "self", ".", "label", "is", "None", ":", "self", ".", "label", "=", "self", ".", "get_field", "(", "'label'", ")", "return", "self", ".", "label" ]
Get the label of the Dataset. Returns ------- label : numpy array or None The label information from the Dataset.
[ "Get", "the", "label", "of", "the", "Dataset", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1377-L1387
22,896
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.get_weight
def get_weight(self): """Get the weight of the Dataset. Returns ------- weight : numpy array or None Weight for each data point from the Dataset. """ if self.weight is None: self.weight = self.get_field('weight') return self.weight
python
def get_weight(self): """Get the weight of the Dataset. Returns ------- weight : numpy array or None Weight for each data point from the Dataset. """ if self.weight is None: self.weight = self.get_field('weight') return self.weight
[ "def", "get_weight", "(", "self", ")", ":", "if", "self", ".", "weight", "is", "None", ":", "self", ".", "weight", "=", "self", ".", "get_field", "(", "'weight'", ")", "return", "self", ".", "weight" ]
Get the weight of the Dataset. Returns ------- weight : numpy array or None Weight for each data point from the Dataset.
[ "Get", "the", "weight", "of", "the", "Dataset", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1389-L1399
22,897
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.get_feature_penalty
def get_feature_penalty(self): """Get the feature penalty of the Dataset. Returns ------- feature_penalty : numpy array or None Feature penalty for each feature in the Dataset. """ if self.feature_penalty is None: self.feature_penalty = self.get_field('feature_penalty') return self.feature_penalty
python
def get_feature_penalty(self): """Get the feature penalty of the Dataset. Returns ------- feature_penalty : numpy array or None Feature penalty for each feature in the Dataset. """ if self.feature_penalty is None: self.feature_penalty = self.get_field('feature_penalty') return self.feature_penalty
[ "def", "get_feature_penalty", "(", "self", ")", ":", "if", "self", ".", "feature_penalty", "is", "None", ":", "self", ".", "feature_penalty", "=", "self", ".", "get_field", "(", "'feature_penalty'", ")", "return", "self", ".", "feature_penalty" ]
Get the feature penalty of the Dataset. Returns ------- feature_penalty : numpy array or None Feature penalty for each feature in the Dataset.
[ "Get", "the", "feature", "penalty", "of", "the", "Dataset", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1401-L1411
22,898
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.get_monotone_constraints
def get_monotone_constraints(self): """Get the monotone constraints of the Dataset. Returns ------- monotone_constraints : numpy array or None Monotone constraints: -1, 0 or 1, for each feature in the Dataset. """ if self.monotone_constraints is None: self.monotone_constraints = self.get_field('monotone_constraints') return self.monotone_constraints
python
def get_monotone_constraints(self): """Get the monotone constraints of the Dataset. Returns ------- monotone_constraints : numpy array or None Monotone constraints: -1, 0 or 1, for each feature in the Dataset. """ if self.monotone_constraints is None: self.monotone_constraints = self.get_field('monotone_constraints') return self.monotone_constraints
[ "def", "get_monotone_constraints", "(", "self", ")", ":", "if", "self", ".", "monotone_constraints", "is", "None", ":", "self", ".", "monotone_constraints", "=", "self", ".", "get_field", "(", "'monotone_constraints'", ")", "return", "self", ".", "monotone_constraints" ]
Get the monotone constraints of the Dataset. Returns ------- monotone_constraints : numpy array or None Monotone constraints: -1, 0 or 1, for each feature in the Dataset.
[ "Get", "the", "monotone", "constraints", "of", "the", "Dataset", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1413-L1423
22,899
Microsoft/LightGBM
python-package/lightgbm/basic.py
Dataset.get_init_score
def get_init_score(self): """Get the initial score of the Dataset. Returns ------- init_score : numpy array or None Init score of Booster. """ if self.init_score is None: self.init_score = self.get_field('init_score') return self.init_score
python
def get_init_score(self): """Get the initial score of the Dataset. Returns ------- init_score : numpy array or None Init score of Booster. """ if self.init_score is None: self.init_score = self.get_field('init_score') return self.init_score
[ "def", "get_init_score", "(", "self", ")", ":", "if", "self", ".", "init_score", "is", "None", ":", "self", ".", "init_score", "=", "self", ".", "get_field", "(", "'init_score'", ")", "return", "self", ".", "init_score" ]
Get the initial score of the Dataset. Returns ------- init_score : numpy array or None Init score of Booster.
[ "Get", "the", "initial", "score", "of", "the", "Dataset", "." ]
8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147
https://github.com/Microsoft/LightGBM/blob/8d2ec69f4f685b0ab1c4624d59ee2d3287bb3147/python-package/lightgbm/basic.py#L1425-L1435