text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 shap...
x_sliced = tf.reshape( x, shape=[-1, self.hparams.num_blocks, self.hparams.block_dim]) return x_sliced
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def embedding_lookup(self, x, means): """Compute nearest neighbors and loss for training the embeddings. Args: x: Batch of encoder continuous latent states slice...
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( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def discrete_bottleneck(self, x): """Discretization bottleneck for latent variables. Args: x: Input to the discretization bottleneck. Returns: Embedding to pass ...
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 = \ ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mimic_adam_with_adafactor(hparams): """Switch from Adam to Adafactor, approximating the behavior of Adam. Some minor things may be different, like epsilon an...
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.ByteT...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_deco...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text2class_txt_iterator(source_txt_path, label_txt_path, class_strs=None): """Yield dicts for Text2ClassProblem.generate_samples from lines of files. Args: s...
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 re...
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()}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text2text_generate_encoded(sample_generator, vocab, targets_vocab=None, has_inputs=True, inputs_prefix="", targets_prefix=""): """Encode Text2Text samples fr...
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"]...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: ex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 integ...
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 i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 s...
f = tf.gfile.Open(filepath) b = f.read() yield text_encoder.to_unicode_ignore_errors(b)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, o...
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_fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: fea...
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def GRUCell(units): """Builds a traditional GRU cell with dense internal transformations. Gated Recurrent Unit paper: https://arxiv.org/abs/1412.3555 Args: units...
return GeneralGRUCell( candidate_transform=lambda: core.Dense(units=units), memory_transform=combinators.Identity, gate_nonlinearity=core.Sigmoid, candidate_nonlinearity=core.Tanh)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_si...
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def PreparePairedSequenceBatch(source, target_in, pad=0): """Build masks for this batch. Args: source: (batch, source_len) array of integer-coded symbols for inp...
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 =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def DotProductAttention(query, key, value, mask, dropout, mode, rng): """Core dot product self-attention. Args: query: array of representations key: array of rep...
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 tha...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def PureDotProductAttention(dropout=0.0, mode='train'): """Pure single-headed self-attention. Args: dropout: float: dropout rate mode: str: 'train' or 'eval' Ret...
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.g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def PureMultiHeadedAttention(x, params, num_heads=8, dropout=0.0, mode='train', **kwargs): """Pure transformer-style multi-headed attention. Args: x: inputs ((q,...
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.tra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ChunkedAttentionSelector(x, params, selector=None, **kwargs): """Select which chunks to attend to in chunked attention. Args: x: inputs, a list of elements o...
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ChunkedCausalMultiHeadedAttention( feature_depth, num_heads=8, dropout=0.0, chunk_selector=None, mode='train'): """Transformer-style causal multi-headed atte...
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( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 sym...
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))}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ==...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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(COP...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_attend_to_encoder_cache(cache, attention_name, hparams, num_layers, key_channels, value_channels, vars_3d_num_heads, scope_prefix, encoder_output): """A...
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_channel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _init_evolved_transformer_cache(cache, hparams, batch_size, attention_init_length, encoder_output, encoder_decoder_attention_bias, scope_prefix): """Create t...
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) # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_evolved_transformer_hparams(hparams): """Add Evolved Transformer hparams. Note: These are for the Adam optimizer, not the Adafactor optimizer used in the...
# 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, # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_fact...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
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_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def optimizer(name): """Get pre-registered optimizer keyed by name. `name` should be snake case, though SGD -> sgd, RMSProp -> rms_prop and UpperCamelCase -> sna...
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( "'RM...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 th...
ep_cls = Registries.env_problems[env_problem_name] ep = ep_cls() ep.initialize(**kwargs) return ep
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 wit...
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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_dependicies(objdump_string): """Check the dynamic symbol versions. Parameters objdump_string : string The dynamic symbol table entries of the file (res...
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]+GLI...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ro...
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()) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 y...
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 ar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predict(self, X, raw_score=False, num_iteration=None, pred_leaf=False, pred_contrib=False, **kwargs): """Return the predicted value for each sample. Paramete...
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def predict_proba(self, X, raw_score=False, num_iteration=None, pred_leaf=False, pred_contrib=False, **kwargs): """Return the predicted probability for each clas...
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. - ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_parameter_infos(config_hpp): """Parse config header file. Parameters config_hpp : string Path to the config header file. Returns ------- infos : tuple Tu...
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 "#...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_names(infos): """Get names of all parameters. Parameters infos : list Content of the config header file. Returns ------- names : list Names of all parame...
names = [] for x in infos: for y in x: names.append(y["name"][0]) return names
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_alias(infos): """Get aliases of all parameters. Parameters infos : list Content of the config header file. Returns ------- pairs : list List of tuples (p...
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
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: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 :...
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 f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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.") ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. Parame...
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_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 pre...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_valid(self, data, label=None, weight=None, group=None, init_score=None, silent=False, params=None): """Create validation data align with current Datas...
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 : ...
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 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_binary(self, filename): """Save Dataset to a binary file. Parameters filename : string Name of the output file. Returns ------- self : Dataset Returns s...
_safe_call(_LIB.LGBM_DatasetSaveBinary( self.construct().handle, c_str(filename))) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
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, c...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_field(self, field_name): """Get property from the Dataset. Parameters field_name : string The field name of the information. Returns ------- info : numpy...
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_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_categorical_feature(self, categorical_feature): """Set categorical features. Parameters categorical_feature : list of int or strings Names or indices of ...
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'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _set_predictor(self, predictor): """Set predictor for continued training. It is not recommended for user to call this function. Please use init_model argumen...
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_dat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_reference(self, reference): """Set reference Dataset. Parameters reference : Dataset Reference that is used as a template to construct the current Datase...
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_chai...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_feature_name(self, feature_name): """Set feature name. Parameters feature_name : list of strings Feature names. Returns ------- self : Dataset Dataset wi...
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 matc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 poi...
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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...
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_feature_penalty(self): """Get the feature penalty of the Dataset. Returns ------- feature_penalty : numpy array or None Feature penalty for each feature ...
if self.feature_penalty is None: self.feature_penalty = self.get_field('feature_penalty') return self.feature_penalty
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_monotone_constraints(self): """Get the monotone constraints of the Dataset. Returns ------- monotone_constraints : numpy array or None Monotone constrain...
if self.monotone_constraints is None: self.monotone_constraints = self.get_field('monotone_constraints') return self.monotone_constraints
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_data(self): """Get the raw data of the Dataset. Returns ------- data : string, numpy array, pandas DataFrame, H2O DataTable's Frame, scipy.sparse, list o...
if self.handle is None: raise Exception("Cannot get data before construct Dataset") if self.data is not None and self.used_indices is not None and self.need_slice: if isinstance(self.data, np.ndarray) or scipy.sparse.issparse(self.data): self.data = self.data[sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_group(self): """Get the group of the Dataset. Returns ------- group : numpy array or None Group size of each group. """
if self.group is None: self.group = self.get_field('group') if self.group is not None: # group data from LightGBM is boundaries data, need to convert to group size self.group = np.diff(self.group) return self.group
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def num_data(self): """Get the number of rows in the Dataset. Returns ------- number_of_rows : int The number of rows in the Dataset. """
if self.handle is not None: ret = ctypes.c_int() _safe_call(_LIB.LGBM_DatasetGetNumData(self.handle, ctypes.byref(ret))) return ret.value else: raise LightGBMError("Cannot get num_data before construct da...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_ref_chain(self, ref_limit=100): """Get a chain of Dataset objects. Starts with r, then goes to r.reference (if exists), then to r.reference.reference, et...
head = self ref_chain = set() while len(ref_chain) < ref_limit: if isinstance(head, Dataset): ref_chain.add(head) if (head.reference is not None) and (head.reference not in ref_chain): head = head.reference else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_features_from(self, other): """Add features from other Dataset to the current Dataset. Both Datasets must be constructed before calling this method. Para...
if self.handle is None or other.handle is None: raise ValueError('Both source and target Datasets must be constructed before adding features') _safe_call(_LIB.LGBM_DatasetAddFeaturesFrom(self.handle, other.handle)) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump_text(self, filename): """Save Dataset to a text file. This format cannot be loaded back in by LightGBM, but is useful for debugging purposes. Parameters...
_safe_call(_LIB.LGBM_DatasetDumpText( self.construct().handle, c_str(filename))) return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def free_dataset(self): """Free Booster's Datasets. Returns ------- self : Booster Booster without Datasets. """
self.__dict__.pop('train_set', None) self.__dict__.pop('valid_sets', None) self.__num_dataset = 0 return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_network(self, machines, local_listen_port=12400, listen_time_out=120, num_machines=1): """Set the network configuration. Parameters machines : list, set ...
_safe_call(_LIB.LGBM_NetworkInit(c_str(machines), ctypes.c_int(local_listen_port), ctypes.c_int(listen_time_out), ctypes.c_int(num_machines))) self.network = True return se...