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 hybrid_forward(self, F, words1, words2, words3):
# pylint: disable=arguments-differ, unused-argument """Compute analogies for given question words. Parameter... |
return self.analogy(words1, words2, words3) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate(data_source, batch_size, ctx=None):
"""Evaluate the model on the dataset with cache model. Parameters data_source : NDArray The dataset is evaluated... |
total_L = 0
hidden = cache_cell.\
begin_state(func=mx.nd.zeros, batch_size=batch_size, ctx=context[0])
next_word_history = None
cache_history = None
for i in range(0, len(data_source) - 1, args.bptt):
if i > 0:
print('Batch %d/%d, ppl %f'%
(i, len(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 bert_12_768_12(dataset_name=None, vocab=None, pretrained=True, ctx=mx.cpu(), root=os.path.join(get_home_dir(), 'models'), use_pooler=True, use_decoder=True, u... |
return get_static_bert_model(model_name='bert_12_768_12', vocab=vocab,
dataset_name=dataset_name, pretrained=pretrained, ctx=ctx,
use_pooler=use_pooler, use_decoder=use_decoder,
use_classifier=use_classifier, root=ro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hybrid_forward(self, F, inputs, token_types, valid_length=None, masked_positions=None):
# pylint: disable=arguments-differ # pylint: disable=unused-argument ... |
outputs = []
seq_out, attention_out = self._encode_sequence(F, inputs, token_types, valid_length)
outputs.append(seq_out)
if self.encoder._output_all_encodings:
assert isinstance(seq_out, list)
output = seq_out[-1]
else:
output = seq_out
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put(self, x):
"""Assign input `x` to an available worker and invoke `parallizable.forward_backward` with x. """ |
if self._num_serial > 0 or len(self._threads) == 0:
self._num_serial -= 1
out = self._parallizable.forward_backward(x)
self._out_queue.put(out)
else:
self._in_queue.put(x) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_json(cls, json_str):
"""Deserialize BERTVocab object from json string. Parameters json_str : str Serialized json string of a BERTVocab object. Returns -... |
vocab_dict = json.loads(json_str)
unknown_token = vocab_dict.get('unknown_token')
bert_vocab = cls(unknown_token=unknown_token)
bert_vocab._idx_to_token = vocab_dict.get('idx_to_token')
bert_vocab._token_to_idx = vocab_dict.get('token_to_idx')
if unknown_token:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def forward(self, inputs, label, begin_state, sampled_values):
# pylint: disable=arguments-differ """Defines the forward computation. Parameters inputs : NDArray... |
encoded = self.embedding(inputs)
length = inputs.shape[0]
batch_size = inputs.shape[1]
encoded, out_states = self.encoder.unroll(length, encoded, begin_state,
layout='TNC', merge_outputs=True)
out, new_target = self.decoder(encod... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hybrid_forward(self, F, center, context, center_words):
"""SkipGram forward pass. Parameters center : mxnet.nd.NDArray or mxnet.sym.Symbol Sparse CSR array o... |
# negatives sampling
negatives = []
mask = []
for _ in range(self._kwargs['num_negatives']):
negatives.append(self.negatives_sampler(center_words))
mask_ = negatives[-1] != center_words
mask_ = F.stack(mask_, (negatives[-1] != context))
m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate(dataloader):
"""Evaluate network on the specified dataset""" |
total_L = 0.0
total_sample_num = 0
total_correct_num = 0
start_log_interval_time = time.time()
print('Begin Testing...')
for i, ((data, valid_length), label) in enumerate(dataloader):
data = mx.nd.transpose(data.as_in_context(context))
valid_length = valid_length.as_in_context(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 hybrid_forward(self, F, inputs, states, i2h_weight, h2h_weight, h2r_weight, i2h_bias, h2h_bias):
r"""Hybrid forward computation for Long-Short Term Memory Pr... |
prefix = 't%d_'%self._counter
i2h = F.FullyConnected(data=inputs, weight=i2h_weight, bias=i2h_bias,
num_hidden=self._hidden_size*4, name=prefix+'i2h')
h2h = F.FullyConnected(data=states[0], weight=h2h_weight, bias=h2h_bias,
num_hidde... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clip_grad_global_norm(parameters, max_norm, check_isfinite=True):
"""Rescales gradients of parameters so that the sum of their 2-norm is smaller than `max_no... |
def _norm(array):
if array.stype == 'default':
x = array.reshape((-1))
return nd.dot(x, x)
return array.norm().square()
arrays = []
i = 0
for p in parameters:
if p.grad_req != 'null':
grad_list = p.list_grad()
arrays.append(grad_l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def forward_backward(self, x):
"""forward backward implementation""" |
with mx.autograd.record():
(ls, next_sentence_label, classified, masked_id, decoded, \
masked_weight, ls1, ls2, valid_length) = forward(x, self._model, self._mlm_loss,
self._nsp_loss, self._vocab_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 log_info(self, logger):
"""Print statistical information via the provided logger Parameters logger : logging.Logger logger created using logging.getLogger() ... |
logger.info('#words in training set: %d' % self._words_in_train_data)
logger.info("Vocab info: #words %d, #tags %d #rels %d" % (self.vocab_size, self.tag_size, self.rel_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 _add_pret_words(self, pret_embeddings):
"""Read pre-trained embedding file for extending vocabulary Parameters pret_embeddings : tuple (embedding_name, sourc... |
words_in_train_data = set(self._id2word)
pret_embeddings = gluonnlp.embedding.create(pret_embeddings[0], source=pret_embeddings[1])
for idx, token in enumerate(pret_embeddings.idx_to_token):
if token not in words_in_train_data:
self._id2word.append(token) |
<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_pret_embs(self, word_dims=None):
"""Read pre-trained embedding file Parameters word_dims : int or None vector size. Use `None` for auto-infer Returns ---... |
assert (self._pret_embeddings is not None), "No pretrained file provided."
pret_embeddings = gluonnlp.embedding.create(self._pret_embeddings[0], source=self._pret_embeddings[1])
embs = [None] * len(self._id2word)
for idx, vec in enumerate(pret_embeddings.idx_to_vec):
embs[id... |
<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_word_embs(self, word_dims):
"""Get randomly initialized embeddings when pre-trained embeddings are used, otherwise zero vectors Parameters word_dims : in... |
if self._pret_embeddings is not None:
return np.random.randn(self.words_in_train, word_dims).astype(np.float32)
return np.zeros((self.words_in_train, word_dims), dtype=np.float32) |
<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_tag_embs(self, tag_dims):
"""Randomly initialize embeddings for tag Parameters tag_dims : int tag vector size Returns ------- numpy.ndarray random embedd... |
return np.random.randn(self.tag_size, tag_dims).astype(np.float32) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def idx_sequence(self):
"""Indices of sentences when enumerating data set from batches. Useful when retrieving the correct order of sentences Returns ------- lis... |
return [x[1] for x in sorted(zip(self._record, list(range(len(self._record)))))] |
<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_batches(self, batch_size, shuffle=True):
"""Get batch iterator Parameters batch_size : int size of one batch shuffle : bool whether to shuffle batches. D... |
batches = []
for bkt_idx, bucket in enumerate(self._buckets):
bucket_size = bucket.shape[1]
n_tokens = bucket_size * self._bucket_lengths[bkt_idx]
n_splits = min(max(n_tokens // batch_size, 1), bucket_size)
range_func = np.random.permutation if shuffle el... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_input_data(filename):
"""Helper function to get training data""" |
logging.info('Opening file %s for reading input', filename)
input_file = open(filename, 'r')
data = []
labels = []
for line in input_file:
tokens = line.split(',', 1)
labels.append(tokens[0].strip())
data.append(tokens[1].strip())
return labels, 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 get_label_mapping(train_labels):
""" Create the mapping from label to numeric label """ |
sorted_labels = np.sort(np.unique(train_labels))
label_mapping = {}
for i, label in enumerate(sorted_labels):
label_mapping[label] = i
logging.info('Label mapping:%s', format(label_mapping))
return label_mapping |
<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_to_sequences(dataset, vocab):
"""This function takes a dataset and converts it into sequences via multiprocessing """ |
start = time.time()
dataset_vocab = map(lambda x: (x, vocab), dataset)
with mp.Pool() as pool:
# Each sample is processed in an asynchronous manner.
output = pool.map(get_sequence, dataset_vocab)
end = time.time()
logging.info('Done! Sequence conversion Time={:.2f}s, #Sentences={}'
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preprocess_dataset(dataset, labels):
""" Preprocess and prepare a dataset""" |
start = time.time()
with mp.Pool() as pool:
# Each sample is processed in an asynchronous manner.
dataset = gluon.data.SimpleDataset(list(zip(dataset, labels)))
lengths = gluon.data.SimpleDataset(pool.map(get_length, dataset))
end = time.time()
logging.info('Done! Preprocessing ... |
<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_dataloader(train_dataset, train_data_lengths, test_dataset, batch_size):
""" Construct the DataLoader. Pad data, stack label and lengths""" |
bucket_num, bucket_ratio = 20, 0.2
batchify_fn = gluonnlp.data.batchify.Tuple(
gluonnlp.data.batchify.Pad(axis=0, ret_length=True),
gluonnlp.data.batchify.Stack(dtype='float32'))
batch_sampler = gluonnlp.data.sampler.FixedBucketSampler(
train_data_lengths,
batch_size=batch_s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def encode(self, inputs, states=None, valid_length=None):
"""Encode the input sequence. Parameters inputs : NDArray states : list of NDArrays or None, default No... |
return self.encoder(self.src_embed(inputs), states, valid_length) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode_seq(self, inputs, states, valid_length=None):
"""Decode given the input sequence. Parameters inputs : NDArray states : list of NDArrays valid_length :... |
outputs, states, additional_outputs =\
self.decoder.decode_seq(inputs=self.tgt_embed(inputs),
states=states,
valid_length=valid_length)
outputs = self.tgt_proj(outputs)
return outputs, states, additional_outputs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def decode_step(self, step_input, states):
"""One step decoding of the translation model. Parameters step_input : NDArray Shape (batch_size,) states : list of ND... |
step_output, states, step_additional_outputs =\
self.decoder(self.tgt_embed(step_input), states)
step_output = self.tgt_proj(step_output)
return step_output, states, step_additional_outputs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def forward(self, src_seq, tgt_seq, src_valid_length=None, tgt_valid_length=None):
#pylint: disable=arguments-differ """Generate the prediction given the src_seq... |
additional_outputs = []
encoder_outputs, encoder_additional_outputs = self.encode(src_seq,
valid_length=src_valid_length)
decoder_states = self.decoder.init_state_from_encoder(encoder_outputs,
... |
<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_subword_function(subword_function_name, **kwargs):
"""Creates an instance of a subword function.""" |
create_ = registry.get_create_func(SubwordFunction, 'token embedding')
return create_(subword_function_name, **kwargs) |
<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_embedding(self, *embeddings):
"""Attaches one or more embeddings to the indexed text tokens. Parameters embeddings : None or tuple of :class:`gluonnlp.em... |
if len(embeddings) == 1 and embeddings[0] is None:
self._embedding = None
return
for embs in embeddings:
assert isinstance(embs, emb.TokenEmbedding), \
'The argument `embeddings` must be an instance or a list of instances of ' \
'`gl... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_json(self):
"""Serialize Vocab object to json string. This method does not serialize the underlying embedding. """ |
if self._embedding:
warnings.warn('Serialization of attached embedding '
'to json is not supported. '
'You may serialize the embedding to a binary format '
'separately using vocab.embedding.serialize')
vocab_dict ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_json(cls, json_str):
"""Deserialize Vocab object from json string. Parameters json_str : str Serialized json string of a Vocab object. Returns ------- V... |
vocab_dict = json.loads(json_str)
unknown_token = vocab_dict.get('unknown_token')
vocab = cls(unknown_token=unknown_token)
vocab._idx_to_token = vocab_dict.get('idx_to_token')
vocab._token_to_idx = vocab_dict.get('token_to_idx')
if unknown_token:
vocab._toke... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pad_arrs_to_max_length(arrs, pad_axis, pad_val, use_shared_mem, dtype):
"""Inner Implementation of the Pad batchify Parameters arrs : list pad_axis : int pa... |
if isinstance(arrs[0], mx.nd.NDArray):
dtype = arrs[0].dtype if dtype is None else dtype
arrs = [arr.asnumpy() for arr in arrs]
elif not isinstance(arrs[0], np.ndarray):
arrs = [np.asarray(ele) for ele in arrs]
else:
dtype = arrs[0].dtype if dtype is None else dtype
ori... |
<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(self, path):
"""Load from disk Parameters path : str path to the directory which typically contains a config.pkl file and a model.bin file Returns -----... |
config = _Config.load(os.path.join(path, 'config.pkl'))
config.save_dir = path # redirect root path to what user specified
self._vocab = vocab = ParserVocabulary.load(config.save_vocab_path)
with mx.Context(mxnet_prefer_gpu()):
self._parser = BiaffineParser(vocab, config.wo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate(self, test_file, save_dir=None, logger=None, num_buckets_test=10, test_batch_size=5000):
"""Run evaluation on test set Parameters test_file : str pa... |
parser = self._parser
vocab = self._vocab
with mx.Context(mxnet_prefer_gpu()):
UAS, LAS, speed = evaluate_official_script(parser, vocab, num_buckets_test, test_batch_size,
test_file, os.path.join(save_dir, 'valid_tmp'))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(self, sentence):
"""Parse raw sentence into ConllSentence Parameters sentence : list a list of (word, tag) tuples Returns ------- ConllSentence ConllSe... |
words = np.zeros((len(sentence) + 1, 1), np.int32)
tags = np.zeros((len(sentence) + 1, 1), np.int32)
words[0, 0] = ParserVocabulary.ROOT
tags[0, 0] = ParserVocabulary.ROOT
vocab = self._vocab
for i, (word, tag) in enumerate(sentence):
words[i + 1, 0], tags[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 apply_weight_drop(block, local_param_regex, rate, axes=(), weight_dropout_mode='training'):
"""Apply weight drop to the parameter of a block. Parameters bloc... |
if not rate:
return
existing_params = _find_params(block, local_param_regex)
for (local_param_name, param), \
(ref_params_list, ref_reg_params_list) in existing_params.items():
dropped_param = WeightDropParameter(param, rate, weight_dropout_mode, axes)
for ref_params in... |
<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_rnn_cell(mode, num_layers, input_size, hidden_size, dropout, weight_dropout, var_drop_in, var_drop_state, var_drop_out, skip_connection, proj_size=None, ... |
assert mode == 'lstmpc' and proj_size is not None, \
'proj_size takes effect only when mode is lstmpc'
assert mode == 'lstmpc' and cell_clip is not None, \
'cell_clip takes effect only when mode is lstmpc'
assert mode == 'lstmpc' and proj_clip is not None, \
'proj_clip takes effect... |
<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_rnn_layer(mode, num_layers, input_size, hidden_size, dropout, weight_dropout):
"""create rnn layer given specs""" |
if mode == 'rnn_relu':
rnn_block = functools.partial(rnn.RNN, activation='relu')
elif mode == 'rnn_tanh':
rnn_block = functools.partial(rnn.RNN, activation='tanh')
elif mode == 'lstm':
rnn_block = rnn.LSTM
elif mode == 'gru':
rnn_block = rnn.GRU
block = rnn_block(hi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _extract_and_flatten_nested_structure(data, flattened=None):
"""Flatten the structure of a nested container to a list. Parameters data : A single NDArray/Sym... |
if flattened is None:
flattened = []
structure = _extract_and_flatten_nested_structure(data, flattened)
return structure, flattened
if isinstance(data, list):
return list(_extract_and_flatten_nested_structure(x, flattened) for x in data)
elif isinstance(data, tuple):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def data(self, ctx=None):
"""Returns a copy of this parameter on one context. Must have been initialized on this context before. Parameters ctx : Context Desired... |
d = self._check_and_get(self._data, ctx)
if self._rate:
d = nd.Dropout(d, self._rate, self._mode, self._axes)
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def elmo_2x1024_128_2048cnn_1xhighway(dataset_name=None, pretrained=False, ctx=mx.cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs):
r"""ELMo 2-layer... |
predefined_args = {'rnn_type': 'lstmpc',
'output_size': 128,
'filters': [[1, 32], [2, 32], [3, 64], [4, 128],
[5, 256], [6, 512], [7, 1024]],
'char_embed_size': 16,
'num_highway': 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 awd_lstm_lm_1150(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs):
r"""3-layer LSTM languag... |
predefined_args = {'embed_size': 400,
'hidden_size': 1150,
'mode': 'lstm',
'num_layers': 3,
'tie_weights': True,
'dropout': 0.4,
'weight_drop': 0.5,
'drop... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def standard_lstm_lm_200(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs):
r"""Standard 2-layer... |
predefined_args = {'embed_size': 200,
'hidden_size': 200,
'mode': 'lstm',
'num_layers': 2,
'tie_weights': True,
'dropout': 0.2}
mutable_args = ['dropout']
assert all((k not in kwargs or k in m... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def big_rnn_lm_2048_512(dataset_name=None, vocab=None, pretrained=False, ctx=cpu(), root=os.path.join(get_home_dir(), 'models'), **kwargs):
r"""Big 1-layer LSTMP... |
predefined_args = {'embed_size': 512,
'hidden_size': 2048,
'projection_size': 512,
'num_layers': 1,
'embed_dropout': 0.1,
'encode_dropout': 0.1}
mutable_args = ['embed_dropout', 'encode_dropout']
... |
<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_cell_type(cell_type):
"""Get the object type of the cell by parsing the input Parameters cell_type : str or type Returns ------- cell_constructor: type ... |
if isinstance(cell_type, str):
if cell_type == 'lstm':
return rnn.LSTMCell
elif cell_type == 'gru':
return rnn.GRUCell
elif cell_type == 'relu_rnn':
return partial(rnn.RNNCell, activation='relu')
elif cell_type == 'tanh_rnn':
return pa... |
<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_context(center_idx, sentence_boundaries, window_size, random_window_size, seed):
"""Compute the context with respect to a center word in a sentence. Tak... |
random.seed(seed + center_idx)
sentence_index = np.searchsorted(sentence_boundaries, center_idx)
sentence_start, sentence_end = _get_sentence_start_end(
sentence_boundaries, sentence_index)
if random_window_size:
window_size = random.randint(1, window_size)
start_idx = max(sentenc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def model(dropout, vocab, model_mode, output_size):
"""Construct the model.""" |
textCNN = SentimentNet(dropout=dropout, vocab_size=len(vocab), model_mode=model_mode,\
output_size=output_size)
textCNN.hybridize()
return textCNN |
<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(textCNN, vocab, model_mode, context, lr):
"""Initialize parameters.""" |
textCNN.initialize(mx.init.Xavier(), ctx=context, force_reinit=True)
if model_mode != 'rand':
textCNN.embedding.weight.set_data(vocab.embedding.idx_to_vec)
if model_mode == 'multichannel':
textCNN.embedding_extend.weight.set_data(vocab.embedding.idx_to_vec)
if model_mode == 'static' 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 preprocess_dataset(dataset, transform, num_workers=8):
"""Use multiprocessing to perform transform for dataset. Parameters dataset: dataset-like object Sourc... |
worker_fn = partial(_worker_fn, transform=transform)
start = time.time()
pool = mp.Pool(num_workers)
dataset_transform = []
dataset_len = []
for data in pool.map(worker_fn, dataset):
if data:
for _data in data:
dataset_transform.append(_data[:-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 _masked_softmax(F, att_score, mask, dtype):
"""Ignore the masked elements when calculating the softmax Parameters F : symbol or ndarray att_score : Symborl o... |
if mask is not None:
# Fill in the masked scores with a very small value
neg = -1e4 if np.dtype(dtype) == np.float16 else -1e18
att_score = F.where(mask, att_score, neg * F.ones_like(att_score))
att_weights = F.softmax(att_score, axis=-1) * mask
else:
att_weights = F.sof... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_by_weight(self, F, att_weights, value):
"""Read from the value matrix given the attention weights. Parameters F : symbol or ndarray att_weights : Symbo... |
output = F.batch_dot(att_weights, value)
return output |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def translate(self, src_seq, src_valid_length):
"""Get the translation result given the input sentence. Parameters src_seq : mx.nd.NDArray Shape (batch_size, len... |
batch_size = src_seq.shape[0]
encoder_outputs, _ = self._model.encode(src_seq, valid_length=src_valid_length)
decoder_states = self._model.decoder.init_state_from_encoder(encoder_outputs,
src_valid_length)
inputs = mx.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate_official_script(parser, vocab, num_buckets_test, test_batch_size, test_file, output_file, debug=False):
"""Evaluate parser on a data set Parameters ... |
if output_file is None:
output_file = tempfile.NamedTemporaryFile().name
data_loader = DataLoader(test_file, num_buckets_test, vocab)
record = data_loader.idx_sequence
results = [None] * len(record)
idx = 0
seconds = time.time()
for words, tags, arcs, rels in data_loader.get_batches... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parameter_from_numpy(self, name, array):
""" Create parameter with its value initialized according to a numpy tensor Parameters name : str parameter name arr... |
p = self.params.get(name, shape=array.shape, init=mx.init.Constant(array))
return p |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parameter_init(self, name, shape, init):
"""Create parameter given name, shape and initiator Parameters name : str parameter name shape : tuple parameter sha... |
p = self.params.get(name, shape=shape, init=init)
return p |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _thread_worker_fn(samples, batchify_fn, dataset):
"""Threadpool worker function for processing data.""" |
if isinstance(samples[0], (list, tuple)):
batch = [batchify_fn([dataset[i] for i in shard]) for shard in samples]
else:
batch = batchify_fn([dataset[i] for i in samples])
return batch |
<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_source(cls, source_file_hash, source):
"""Checks if a pre-trained token embedding source name is valid. Parameters source : str The pre-trained token ... |
embedding_name = cls.__name__.lower()
if source not in source_file_hash:
raise KeyError('Cannot find pre-trained source {} for token embedding {}. '
'Valid pre-trained file names for embedding {}: {}'.format(
source, embedding_name, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_file(file_path, elem_delim=' ', encoding='utf8', **kwargs):
"""Creates a user-defined token embedding from a pre-trained embedding file. This is to load... |
embedding = TokenEmbedding(**kwargs)
embedding._load_embedding(file_path, elem_delim=elem_delim, encoding=encoding)
return embedding |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialize(self, file_path, compress=True):
"""Serializes the TokenEmbedding to a file specified by file_path. TokenEmbedding is serialized by converting the ... |
if self.unknown_lookup is not None:
warnings.warn(
'Serialization of `unknown_lookup` is not supported. '
'Save it manually and pass the loaded lookup object '
'during deserialization.')
unknown_token = np.array(self.unknown_token)
id... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deserialize(cls, file_path, **kwargs):
"""Create a new TokenEmbedding from a serialized one. TokenEmbedding is serialized by converting the list of tokens, t... |
# idx_to_token is of dtype 'O' so we need to allow pickle
npz_dict = np.load(file_path, allow_pickle=True)
unknown_token = npz_dict['unknown_token']
if not unknown_token:
unknown_token = None
else:
if isinstance(unknown_token, np.ndarray):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate(data_source):
"""Evaluate the model on a mini-batch. """ |
log.info('Start predict')
tic = time.time()
for batch in data_source:
inputs, token_types, valid_length = batch
out = net(inputs.astype('float32').as_in_context(ctx),
token_types.astype('float32').as_in_context(ctx),
valid_length.astype('float32').as_in_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 register(class_=None, **kwargs):
"""Registers a dataset with segment specific hyperparameters. When passing keyword arguments to `register`, they are checked... |
def _real_register(class_):
# Assert that the passed kwargs are meaningful
for kwarg_name, values in kwargs.items():
try:
real_args = inspect.getfullargspec(class_).args
except AttributeError:
# pylint: disable=deprecated-method
... |
<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(name, **kwargs):
"""Creates an instance of a registered dataset. Parameters name : str The dataset name (case-insensitive). Returns ------- An instanc... |
create_ = registry.get_create_func(Dataset, 'dataset')
return create_(name, **kwargs) |
<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_datasets(name=None):
"""Get valid datasets and registered parameters. Parameters name : str or None, default None Return names and registered parameters... |
reg = registry.get_registry(Dataset)
if name is not None:
class_ = reg[name.lower()]
return _REGSITRY_NAME_KWARGS[class_]
else:
return {
dataset_name: _REGSITRY_NAME_KWARGS[class_]
for dataset_name, class_ in registry.get_registry(Dataset).items()
} |
<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_vocab(args):
"""Compute the vocabulary.""" |
counter = nlp.data.Counter()
start = time.time()
for filename in args.files:
print('Starting processing of {} after {:.1f} seconds.'.format(
filename,
time.time() - start))
with open(filename, 'r') as f:
tokens = itertools.chain.from_iterable((l.split() 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 add_parameters(parser):
"""Add evaluation specific parameters to parser.""" |
group = parser.add_argument_group('Evaluation arguments')
group.add_argument('--eval-batch-size', type=int, default=1024)
# Datasets
group.add_argument(
'--similarity-datasets', type=str,
default=nlp.data.word_embedding_evaluation.word_similarity_datasets,
nargs='*',
h... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iterate_similarity_datasets(args):
"""Generator over all similarity evaluation datasets. Iterates over dataset names, keyword arguments for their creation an... |
for dataset_name in args.similarity_datasets:
parameters = nlp.data.list_datasets(dataset_name)
for key_values in itertools.product(*parameters.values()):
kwargs = dict(zip(parameters.keys(), key_values))
yield dataset_name, kwargs, nlp.data.create(dataset_name, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iterate_analogy_datasets(args):
"""Generator over all analogy evaluation datasets. Iterates over dataset names, keyword arguments for their creation and the ... |
for dataset_name in args.analogy_datasets:
parameters = nlp.data.list_datasets(dataset_name)
for key_values in itertools.product(*parameters.values()):
kwargs = dict(zip(parameters.keys(), key_values))
yield dataset_name, kwargs, nlp.data.create(dataset_name, **kwargs) |
<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_similarity_task_tokens(args):
"""Returns a set of all tokens occurring the evaluation datasets.""" |
tokens = set()
for _, _, dataset in iterate_similarity_datasets(args):
tokens.update(
itertools.chain.from_iterable((d[0], d[1]) for d in dataset))
return tokens |
<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_analogy_task_tokens(args):
"""Returns a set of all tokens occuring the evaluation datasets.""" |
tokens = set()
for _, _, dataset in iterate_analogy_datasets(args):
tokens.update(
itertools.chain.from_iterable(
(d[0], d[1], d[2], d[3]) for d in dataset))
return tokens |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate_similarity(args, token_embedding, ctx, logfile=None, global_step=0):
"""Evaluate on specified similarity datasets.""" |
results = []
for similarity_function in args.similarity_functions:
evaluator = nlp.embedding.evaluation.WordEmbeddingSimilarity(
idx_to_vec=token_embedding.idx_to_vec,
similarity_function=similarity_function)
evaluator.initialize(ctx=ctx)
if not args.no_hybridiz... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate_analogy(args, token_embedding, ctx, logfile=None, global_step=0):
"""Evaluate on specified analogy datasets. The analogy task is an open vocabulary ... |
results = []
exclude_question_words = not args.analogy_dont_exclude_question_words
for analogy_function in args.analogy_functions:
evaluator = nlp.embedding.evaluation.WordEmbeddingAnalogy(
idx_to_vec=token_embedding.idx_to_vec,
exclude_question_words=exclude_question_words,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log_similarity_result(logfile, result):
"""Log a similarity evaluation result dictionary as TSV to logfile.""" |
assert result['task'] == 'similarity'
if not logfile:
return
with open(logfile, 'a') as f:
f.write('\t'.join([
str(result['global_step']),
result['task'],
result['dataset_name'],
json.dumps(result['dataset_kwargs']),
result['simi... |
<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_model_loss(ctx, model, pretrained, dataset_name, dtype, ckpt_dir=None, start_step=None):
"""Get model for pre-training.""" |
# model
model, vocabulary = nlp.model.get_model(model,
dataset_name=dataset_name,
pretrained=pretrained, ctx=ctx)
if not pretrained:
model.initialize(init=mx.init.Normal(0.02), ctx=ctx)
model.cast(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 get_pretrain_dataset(data, batch_size, num_ctxes, shuffle, use_avg_len, num_buckets, num_parts=1, part_idx=0, prefetch=True):
"""create dataset for pretraini... |
num_files = len(glob.glob(os.path.expanduser(data)))
logging.debug('%d files found.', num_files)
assert num_files >= num_parts, \
'Number of training files must be greater than the number of partitions'
split_sampler = nlp.data.SplitSampler(num_files, num_parts=num_parts, part_index=part_idx)
... |
<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_dummy_dataloader(dataloader, target_shape):
"""Return a dummy data loader which returns a fixed data batch of target shape""" |
data_iter = enumerate(dataloader)
_, data_batch = next(data_iter)
logging.debug('Searching target batch shape: %s', target_shape)
while data_batch[0].shape != target_shape:
logging.debug('Skip batch with shape %s', data_batch[0].shape)
_, data_batch = next(data_iter)
logging.debug('... |
<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_params(step_num, model, trainer, ckpt_dir):
"""Save the model parameter, marked by step_num.""" |
param_path = os.path.join(ckpt_dir, '%07d.params'%step_num)
trainer_path = os.path.join(ckpt_dir, '%07d.states'%step_num)
logging.info('[step %d] Saving checkpoints to %s, %s.',
step_num, param_path, trainer_path)
model.save_parameters(param_path)
trainer.save_states(trainer_path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log(begin_time, running_num_tks, running_mlm_loss, running_nsp_loss, step_num, mlm_metric, nsp_metric, trainer, log_interval):
"""Log training progress.""" |
end_time = time.time()
duration = end_time - begin_time
throughput = running_num_tks / duration / 1000.0
running_mlm_loss = running_mlm_loss / log_interval
running_nsp_loss = running_nsp_loss / log_interval
lr = trainer.learning_rate if trainer else 0
# pylint: disable=line-too-long
log... |
<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_and_load(arrs, ctx):
"""split and load arrays to a list of contexts""" |
assert isinstance(arrs, (list, tuple))
# split and load
loaded_arrs = [mx.gluon.utils.split_and_load(arr, ctx, even_split=False) for arr in arrs]
return zip(*loaded_arrs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def forward(data, model, mlm_loss, nsp_loss, vocab_size, dtype):
"""forward computation for evaluation""" |
(input_id, masked_id, masked_position, masked_weight, \
next_sentence_label, segment_id, valid_length) = data
num_masks = masked_weight.sum() + 1e-8
valid_length = valid_length.reshape(-1)
masked_id = masked_id.reshape(-1)
valid_length_typed = valid_length.astype(dtype, copy=False)
_, _, 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 evaluate(data_eval, model, nsp_loss, mlm_loss, vocab_size, ctx, log_interval, dtype):
"""Evaluation function.""" |
mlm_metric = MaskedAccuracy()
nsp_metric = MaskedAccuracy()
mlm_metric.reset()
nsp_metric.reset()
eval_begin_time = time.time()
begin_time = time.time()
step_num = 0
running_mlm_loss = running_nsp_loss = 0
total_mlm_loss = total_nsp_loss = 0
running_num_tks = 0
for _, datal... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cache_dataset(dataset, prefix):
"""Cache the processed npy dataset the dataset into a npz Parameters dataset : SimpleDataset file_path : str """ |
if not os.path.exists(_constants.CACHE_PATH):
os.makedirs(_constants.CACHE_PATH)
src_data = np.concatenate([e[0] for e in dataset])
tgt_data = np.concatenate([e[1] for e in dataset])
src_cumlen = np.cumsum([0]+[len(e[0]) for e in dataset])
tgt_cumlen = np.cumsum([0]+[len(e[1]) for e in 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 load_fasttext_format(cls, path, ctx=cpu(), **kwargs):
"""Create an instance of the class and load weights. Load the weights from the fastText binary format c... |
with open(path, 'rb') as f:
new_format, dim, bucket, minn, maxn, = cls._read_model_params(f)
idx_to_token = cls._read_vocab(f, new_format)
dim, matrix = cls._read_vectors(f, new_format, bucket,
len(idx_to_token))
token_to_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def logging_config(logpath=None, level=logging.DEBUG, console_level=logging.INFO, no_console=False):
""" Config the logging. """ |
logger = logging.getLogger('nli')
# Remove all the current handlers
for handler in logger.handlers:
logger.removeHandler(handler)
logger.handlers = []
logger.propagate = False
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(filename)s:%(funcName)s: %(message)s')
... |
<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_train_data(args):
"""Helper function to get training data.""" |
counter = dict()
with io.open(args.vocab, 'r', encoding='utf-8') as f:
for line in f:
token, count = line.split('\t')
counter[token] = int(count)
vocab = nlp.Vocab(counter, unknown_token=None, padding_token=None,
bos_token=None, eos_token=None, min_freq... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log(args, kwargs):
"""Log to a file.""" |
logfile = os.path.join(args.logdir, 'log.tsv')
if 'log_created' not in globals():
if os.path.exists(logfile):
logging.error('Logfile %s already exists.', logfile)
sys.exit(1)
global log_created
log_created = sorted(kwargs.keys())
header = '\t'.join((st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, labels, preds, masks=None):
# pylint: disable=arguments-differ """Updates the internal evaluation result. Parameters labels : list of `NDArray` ... |
labels, preds = check_label_shapes(labels, preds, True)
masks = [None] * len(labels) if masks is None else masks
for label, pred_label, mask in zip(labels, preds, masks):
if pred_label.shape != label.shape:
# TODO(haibin) topk does not support fp16. Issue tracked at... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hybrid_forward(self, F, sentence1, sentence2):
""" Predict the relation of two sentences. Parameters sentence1 : NDArray Shape (batch_size, length) sentence2... |
feature1 = self.lin_proj(self.word_emb(sentence1))
feature2 = self.lin_proj(self.word_emb(sentence2))
if self.use_intra_attention:
feature1 = F.concat(feature1, self.intra_attention(feature1), dim=-1)
feature2 = F.concat(feature2, self.intra_attention(feature2), dim=-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 hybrid_forward(self, F, feature_a):
""" Compute intra-sentence attention given embedded words. Parameters feature_a : NDArray Shape (batch_size, length, hidd... |
tilde_a = self.intra_attn_emb(feature_a)
e_matrix = F.batch_dot(tilde_a, tilde_a, transpose_b=True)
alpha = F.batch_dot(e_matrix.softmax(), tilde_a)
return alpha |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hybrid_forward(self, F, a, b):
""" Forward of Decomposable Attention layer """ |
# a.shape = [B, L1, H]
# b.shape = [B, L2, H]
# extract features
tilde_a = self.f(a) # shape = [B, L1, H]
tilde_b = self.f(b) # shape = [B, L2, H]
# attention
# e.shape = [B, L1, L2]
e = F.batch_dot(tilde_a, tilde_b, transpose_b=True)
# beta: 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 count_tokens(tokens, to_lower=False, counter=None):
r"""Counts tokens in the specified string. For token_delim='(td)' and seq_delim='(sd)', a specified strin... |
if to_lower:
tokens = [t.lower() for t in tokens]
if counter is None:
return Counter(tokens)
else:
counter.update(tokens)
return counter |
<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_sequence(sequence, length, pad_last=False, pad_val=C.PAD_TOKEN, overlap=0):
"""Slice a flat sequence of tokens into sequences tokens, with each inner s... |
if length <= overlap:
raise ValueError('length needs to be larger than overlap')
if pad_last:
pad_len = _slice_pad_length(len(sequence), length, overlap)
sequence = sequence + [pad_val] * pad_len
num_samples = (len(sequence) - length) // (length - overlap) + 1
return [sequence... |
<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_pad_length(num_items, length, overlap=0):
"""Calculate the padding length needed for sliced samples in order not to discard data. Parameters num_items... |
if length <= overlap:
raise ValueError('length needs to be larger than overlap')
step = length - overlap
span = num_items - length
residual = span % step
if residual:
return step - residual
else:
return 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 train_valid_split(dataset, valid_ratio=0.05):
"""Split the dataset into training and validation sets. Parameters dataset : list A list of training samples. v... |
if not 0.0 <= valid_ratio <= 1.0:
raise ValueError('valid_ratio should be in [0, 1]')
num_train = len(dataset)
num_valid = np.ceil(num_train * valid_ratio).astype('int')
indices = np.arange(num_train)
np.random.shuffle(indices)
valid = SimpleDataset([dataset[indices[i]] for i in range... |
<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_pretrained_vocab(name, root=os.path.join(get_home_dir(), 'models'), cls=None):
"""Load the accompanying vocabulary object for pre-trained model. Parame... |
file_name = '{name}-{short_hash}'.format(name=name,
short_hash=short_hash(name))
root = os.path.expanduser(root)
file_path = os.path.join(root, file_name + '.vocab')
sha1_hash = _vocab_sha1[name]
if os.path.exists(file_path):
if check_sha1(file_p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _extract_archive(file, target_dir):
"""Extract archive file Parameters file : str Absolute path of the archive file. target_dir : str Target directory of the... |
if file.endswith('.gz') or file.endswith('.tar') or file.endswith('.tgz'):
archive = tarfile.open(file, 'r')
elif file.endswith('.zip'):
archive = zipfile.ZipFile(file, 'r')
else:
raise Exception('Unrecognized file type: ' + file)
archive.extractall(path=target_dir)
archive.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def discard(self, min_freq, unknown_token):
"""Discards tokens with frequency below min_frequency and represents them as `unknown_token`. Parameters min_freq: in... |
freq = 0
ret = Counter({})
for token, count in self.items():
if count < min_freq:
freq += count
else:
ret[token] = count
ret[unknown_token] = ret.get(unknown_token, 0) + freq
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hybrid_forward(self, F, inputs, **kwargs):
# pylint: disable=unused-argument r""" Forward computation for highway layer Parameters inputs: NDArray Returns ou... |
current_input = inputs
for layer in self.hnet:
projected_input = layer(current_input)
linear_transform = current_input
nonlinear_transform, transform_gate = projected_input.split(num_outputs=2, axis=-1)
nonlinear_transform = self._activation(nonlinear_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 main(args):
""" Read tokens from the provided parse tree in the SNLI dataset. Illegal examples are removed. """ |
examples = []
with open(args.input, 'r') as fin:
reader = csv.DictReader(fin, delimiter='\t')
for cols in reader:
s1 = read_tokens(cols['sentence1_parse'])
s2 = read_tokens(cols['sentence2_parse'])
label = cols['gold_label']
if label in ('neutral'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.