code stringlengths 17 6.64M |
|---|
class TripleDataProvider(data_provider.DataProvider):
'Creates a TripleDataProvider. This data provider reads two datasets\n and their list of schemas in parallel, keep g them aligned.\n\n Args:\n dataset1: The first dataset. An instance of the Dataset class.\n dataset2: The second dataset. An instance of... |
class VocabInfo(collections.namedtuple('VocbabInfo', ['path', 'vocab_size', 'special_vocab'])):
'Convenience structure for vocabulary information.\n '
@property
def total_size(self):
'Returns size the the base vocabulary plus the size of extra vocabulary'
return (self.vocab_size + len(se... |
def get_vocab_info(vocab_path):
'Creates a `VocabInfo` instance that contains the vocabulary size and\n the special vocabulary for the given file.\n\n Args:\n vocab_path: Path to a vocabulary file with one word per line.\n\n Returns:\n A VocabInfo tuple.\n '
with gfile.GFile(vocab_path) as file:
... |
def get_special_vocab(vocabulary_size):
'Returns the `SpecialVocab` instance for a given vocabulary size.\n '
return SpecialVocab(*range(vocabulary_size, (vocabulary_size + 5)))
|
def read_vocab(filename):
'Reads vocab file into the memory and adds special-vocab to it.\n\n Args:\n filename: Path to a vocabulary file containg one word per line.\n Each word is mapped to its line number.\n \n Returns:\n A tuple (vocab, counts, special_vocab)\n '
tf.logging.info(('Reading voca... |
def create_vocabulary_lookup_table(filename, default_value=None):
'Creates a lookup table for a vocabulary file.\n Args:\n filename: Path to a vocabulary file containg one word per line.\n Each word is mapped to its line number.\n default_value: UNK tokens will be mapped to this id.\n If None, UN... |
@function.Defun(tf.float32, tf.float32, tf.float32, func_name='att_sum_bahdanau', noinline=True)
def att_sum_bahdanau(v_att, keys, query):
'Calculates a batch- and timweise dot product with a variable'
return tf.reduce_sum((v_att * tf.tanh((keys + tf.expand_dims(query, 1)))), [2])
|
@function.Defun(tf.float32, tf.float32, func_name='att_sum_dot', noinline=True)
def att_sum_dot(keys, query):
'Calculates a batch- and timweise dot product'
return tf.reduce_sum((keys * tf.expand_dims(query, 1)), [2])
|
@six.add_metaclass(abc.ABCMeta)
class AttentionLayer(GraphModule, Configurable):
'\n Attention layer according to https://arxiv.org/abs/1409.0473.\n\n Params:\n num_units: Number of units used in the attention layer\n '
def __init__(self, params, mode, name='attention'):
GraphModule.__init__(se... |
class AttentionLayerDot(AttentionLayer):
'An attention layer that calculates attention scores using\n a dot product.\n '
def score_fn(self, keys, query):
return att_sum_dot(keys, query)
|
class AttentionLayerBahdanau(AttentionLayer):
'An attention layer that calculates attention scores using\n a parameterized multiplication.'
def score_fn(self, keys, query):
v_att = tf.get_variable('v_att', shape=[self.params['num_units']], dtype=tf.float32)
return att_sum_bahdanau(v_att, key... |
class AttentionDecoderOutput(namedtuple('DecoderOutput', ['logits', 'predicted_ids', 'cell_output', 'attention_scores', 'attention_context'])):
'Augmented decoder output that also includes the attention scores.\n '
pass
|
class AttentionDecoder(RNNDecoder):
'An RNN Decoder that uses attention over an input sequence.\n\n Args:\n cell: An instance of ` tf.contrib.rnn.RNNCell`\n helper: An instance of `tf.contrib.seq2seq.Helper` to assist decoding\n initial_state: A tensor or tuple of tensors used as the initial cell\n ... |
class BasicDecoder(RNNDecoder):
'Simple RNN decoder that performed a softmax operations on the cell output.\n '
def __init__(self, params, mode, vocab_size, decoder_mask=None, name='basic_decoder'):
super(BasicDecoder, self).__init__(params, mode, name)
self.vocab_size = vocab_size
s... |
class FinalBeamDecoderOutput(namedtuple('FinalBeamDecoderOutput', ['predicted_ids', 'beam_search_output'])):
'Final outputs returned by the beam search after all decoding is finished.\n\n Args:\n predicted_ids: The final prediction. A tensor of shape\n `[T, 1, beam_width]`.\n beam_search_output: An in... |
class BeamDecoderOutput(namedtuple('BeamDecoderOutput', ['logits', 'predicted_ids', 'log_probs', 'scores', 'beam_parent_ids', 'original_outputs'])):
'Structure for the output of a beam search decoder. This class is used\n to define the output at each step as well as the final output of the decoder.\n If used as... |
class BeamSearchDecoder(RNNDecoder):
'The BeamSearchDecoder wraps another decoder to perform beam search instead\n of greedy selection. This decoder must be used with batch size of 1, which\n will result in an effective batch size of `beam_width`.\n\n Args:\n decoder: A instance of `RNNDecoder` to be used w... |
class DecoderOutput(namedtuple('DecoderOutput', ['logits', 'predicted_ids', 'cell_output'])):
'Output of an RNN decoder.\n\n Note that we output both the logits and predictions because during\n dynamic decoding the predictions may not correspond to max(logits).\n For example, we may be sampling from the logits... |
@six.add_metaclass(abc.ABCMeta)
class RNNDecoder(Decoder, GraphModule, Configurable):
'Base class for RNN decoders.\n\n Args:\n cell: An instance of ` tf.contrib.rnn.RNNCell`\n helper: An instance of `tf.contrib.seq2seq.Helper` to assist decoding\n initial_state: A tensor or tuple of tensors used as the... |
class SchemaAttentionDecoderOutput(namedtuple('DecoderOutput', ['logits', 'predicted_ids', 'cell_output', 'attention_scores', 'attention_context', 'schema_attention_scores', 'schema_attention_context'])):
'Augmented decoder output that also includes the attention scores.\n '
pass
|
class SchemaCopyingAttentionDecoderOutput(namedtuple('DecoderOutput', ['logits', 'predicted_ids', 'cell_output', 'attention_scores', 'attention_context', 'schema_attention_scores', 'schema_attention_context', 'schema_attention_copy_vals'])):
'Augmented decoder output that also includes the attention scores\n ... |
class SchemaMapAttentionDecoderOutput(namedtuple('DecoderOutput', ['logits', 'predicted_ids', 'cell_output', 'attention_scores', 'attention_context', 'schema_attention_scores', 'schema_attention_context', 'schema_map_attention_scores', 'schema_map_attention_context'])):
'Augmented decoder output that also include... |
class SchemaAttentionDecoder(RNNDecoder):
'An RNN Decoder that uses attention over an input sequence and a schema.\n\n Args:\n cell: An instance of ` tf.contrib.rnn.RNNCell`\n helper: An instance of `tf.contrib.seq2seq.Helper` to assist decoding\n initial_state: A tensor or tuple of tensors used as the ... |
class SchemaAttentionCopyingDecoder(SchemaAttentionDecoder):
'\n The version of SchemaAttentionCopyingDecoder that uses\n F(score_n, rowembedding_n, h, c, W) to generate a score for the\n n-th field in the schema.\n '
def __init__(self, params, mode, vocab_size, attention_keys, attention_values, attentio... |
class SchemaMapAttentionDecoder(SchemaAttentionDecoder):
'An RNN Decoder that uses attention over an input sequence and a schema\n and a schema map.\n\n Args:\n cell: An instance of ` tf.contrib.rnn.RNNCell`\n helper: An instance of `tf.contrib.seq2seq.Helper` to assist decoding\n initial_state: A tens... |
class ConvEncoder(Encoder):
'A deep convolutional encoder, as described in\n https://arxiv.org/abs/1611.02344. The encoder supports optional positions\n embeddings.\n\n Params:\n attention_cnn.units: Number of units in `cnn_a`. Same in each layer.\n attention_cnn.kernel_size: Kernel size for `cnn_a`.\n ... |
@six.add_metaclass(abc.ABCMeta)
class Encoder(GraphModule, Configurable):
'Abstract encoder class. All encoders should inherit from this.\n\n Args:\n params: A dictionary of hyperparameters for the encoder.\n name: A variable scope for the encoder graph.\n '
def __init__(self, params, mode, name):
... |
class InceptionV3Encoder(Encoder):
'\n A unidirectional RNN encoder. Stacking should be performed as\n part of the cell.\n\n Params:\n resize_height: Resize the image to this height before feeding it\n into the convolutional network.\n resize_width: Resize the image to this width before feeding it\n... |
def _unpack_cell(cell):
'Unpack the cells because the stack_bidirectional_dynamic_rnn\n expects a list of cells, one per layer.'
if isinstance(cell, tf.contrib.rnn.MultiRNNCell):
return cell._cells
else:
return [cell]
|
def _default_rnn_cell_params():
'Creates default parameters used by multiple RNN encoders.\n '
return {'cell_class': 'BasicLSTMCell', 'cell_params': {'num_units': 128}, 'dropout_input_keep_prob': 1.0, 'dropout_output_keep_prob': 1.0, 'num_layers': 1, 'residual_connections': False, 'residual_combiner': 'add',... |
def _toggle_dropout(cell_params, mode):
'Disables dropout during eval/inference mode\n '
cell_params = copy.deepcopy(cell_params)
if (mode != tf.contrib.learn.ModeKeys.TRAIN):
cell_params['dropout_input_keep_prob'] = 1.0
cell_params['dropout_output_keep_prob'] = 1.0
return cell_params... |
class UnidirectionalRNNEncoder(Encoder):
'\n A unidirectional RNN encoder. Stacking should be performed as\n part of the cell.\n\n Args:\n cell: An instance of tf.contrib.rnn.RNNCell\n name: A name for the encoder\n '
def __init__(self, params, mode, name='forward_rnn_encoder'):
super(Unidi... |
class BidirectionalRNNEncoder(Encoder):
'\n A bidirectional RNN encoder. Uses the same cell for both the\n forward and backward RNN. Stacking should be performed as part of\n the cell.\n\n Args:\n cell: An instance of tf.contrib.rnn.RNNCell\n name: A name for the encoder\n '
def __init__(self, par... |
class StackBidirectionalRNNEncoder(Encoder):
'\n A stacked bidirectional RNN encoder. Uses the same cell for both the\n forward and backward RNN. Stacking should be performed as part of\n the cell.\n\n Args:\n cell: An instance of tf.contrib.rnn.RNNCell\n name: A name for the encoder\n '
def __ini... |
class GraphModule(object):
'\n Convenience class that makes it easy to share variables.\n Each insance of this class creates its own set of variables, but\n each subsequent execution of an instance will re-use its variables.\n\n Graph components that define variables should inherit from this class\n and impl... |
def templatemethod(name_):
'This decorator wraps a method with `tf.make_template`. For example,\n\n @templatemethod\n def my_method():\n # Create variables\n '
def template_decorator(func):
'Inner decorator function'
def func_wrapper(*args, **kwargs):
'Inner wrapper functio... |
def add_dict_to_collection(dict_, collection_name):
'Adds a dictionary to a graph collection.\n\n Args:\n dict_: A dictionary of string keys to tensor values\n collection_name: The name of the collection to add the dictionary to\n '
key_collection = (collection_name + '_keys')
value_collection = (... |
def get_dict_from_collection(collection_name):
'Gets a dictionary from a graph collection.\n\n Args:\n collection_name: A collection name to read a dictionary from\n\n Returns:\n A dictionary with string keys and tensor values\n '
key_collection = (collection_name + '_keys')
value_collection = (c... |
def create_inference_graph(model, input_pipeline, batch_size=32):
'Creates a graph to perform inference.\n\n Args:\n task: An `InferenceTask` instance.\n input_pipeline: An instance of `InputPipeline` that defines\n how to read and parse data.\n batch_size: The batch size used for inference\n\n Re... |
def cross_entropy_sequence_loss(logits, targets, sequence_length):
'Calculates the per-example cross-entropy loss for a sequence of logits and\n masks out all losses passed the sequence length.\n\n Args:\n logits: Logits of shape `[T, B, vocab_size]`\n targets: Target classes of shape `[T, B]`\n sequ... |
def moses_multi_bleu(hypotheses, references, lowercase=False):
'Calculate the bleu score for hypotheses and references\n using the MOSES ulti-bleu.perl script.\n\n Args:\n hypotheses: A numpy array of strings where each string is a single example.\n references: A numpy array of strings where each string i... |
def accumulate_strings(values, name='strings'):
'Accumulates strings into a vector.\n\n Args:\n values: A 1-d string tensor that contains values to add to the accumulator.\n\n Returns:\n A tuple (value_tensor, update_op).\n '
tf.assert_type(values, tf.string)
strings = tf.Variable(name=name, init... |
@six.add_metaclass(abc.ABCMeta)
class TextMetricSpec(Configurable, MetricSpec):
'Abstract class for text-based metrics calculated based on\n hypotheses and references. Subclasses must implement `metric_fn`.\n\n Args:\n name: A name for the metric\n separator: A separator used to join predicted tokens. Def... |
class BleuMetricSpec(TextMetricSpec):
'Calculates BLEU score using the Moses multi-bleu.perl script.\n '
def __init__(self, params):
super(BleuMetricSpec, self).__init__(params, 'bleu')
def metric_fn(self, hypotheses, references):
return bleu.moses_multi_bleu(hypotheses, references, low... |
class RougeMetricSpec(TextMetricSpec):
'Calculates BLEU score using the Moses multi-bleu.perl script.\n '
def __init__(self, params, **kwargs):
if (not params['rouge_type']):
raise ValueError('You must provide a rouge_type for ROUGE')
super(RougeMetricSpec, self).__init__(params,... |
class LogPerplexityMetricSpec(MetricSpec, Configurable):
'A MetricSpec to calculate straming log perplexity'
def __init__(self, params):
'Initializer'
Configurable.__init__(self, params, tf.contrib.learn.ModeKeys.EVAL)
@staticmethod
def default_params():
return {}
@prope... |
def _get_ngrams(n, text):
'Calcualtes n-grams.\n\n Args:\n n: which n-grams to calculate\n text: An array of tokens\n\n Returns:\n A set of n-grams\n '
ngram_set = set()
text_length = len(text)
max_index_ngram_start = (text_length - n)
for i in range((max_index_ngram_start + 1)):
... |
def _split_into_words(sentences):
'Splits multiple sentences into words and flattens the result'
return list(itertools.chain(*[_.split(' ') for _ in sentences]))
|
def _get_word_ngrams(n, sentences):
'Calculates word n-grams for multiple sentences.\n '
assert (len(sentences) > 0)
assert (n > 0)
words = _split_into_words(sentences)
return _get_ngrams(n, words)
|
def _len_lcs(x, y):
'\n Returns the length of the Longest Common Subsequence between sequences x\n and y.\n Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence\n\n Args:\n x: sequence of words\n y: sequence of words\n\n Returns\n integer: Length of LCS between x and y\n '
t... |
def _lcs(x, y):
'\n Computes the length of the longest common subsequence (lcs) between two\n strings. The implementation below uses a DP programming algorithm and runs\n in O(nm) time where n = len(x) and m = len(y).\n Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence\n\n Args:\n x... |
def _recon_lcs(x, y):
'\n Returns the Longest Subsequence between x and y.\n Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence\n\n Args:\n x: sequence of words\n y: sequence of words\n\n Returns:\n sequence: LCS of x and y\n '
(i, j) = (len(x), len(y))
table = _lcs(x, ... |
def rouge_n(evaluated_sentences, reference_sentences, n=2):
'\n Computes ROUGE-N of two text collections of sentences.\n Sourece: http://research.microsoft.com/en-us/um/people/cyl/download/\n papers/rouge-working-note-v1.3.1.pdf\n\n Args:\n evaluated_sentences: The sentences that have been picked by the su... |
def _f_p_r_lcs(llcs, m, n):
'\n Computes the LCS-based F-measure score\n Source: http://research.microsoft.com/en-us/um/people/cyl/download/papers/\n rouge-working-note-v1.3.1.pdf\n\n Args:\n llcs: Length of LCS\n m: number of words in reference summary\n n: number of words in candidate summary\n\n ... |
def rouge_l_sentence_level(evaluated_sentences, reference_sentences):
'\n Computes ROUGE-L (sentence level) of two text collections of sentences.\n http://research.microsoft.com/en-us/um/people/cyl/download/papers/\n rouge-working-note-v1.3.1.pdf\n\n Calculated according to:\n R_lcs = LCS(X,Y)/m\n P_lcs = L... |
def _union_lcs(evaluated_sentences, reference_sentence):
'\n Returns LCS_u(r_i, C) which is the LCS score of the union longest common\n subsequence between reference sentence ri and candidate summary C. For example\n if r_i= w1 w2 w3 w4 w5, and C contains two sentences: c1 = w1 w2 w6 w7 w8 and\n c2 = w1 w3 w8... |
def rouge_l_summary_level(evaluated_sentences, reference_sentences):
'\n Computes ROUGE-L (summary level) of two text collections of sentences.\n http://research.microsoft.com/en-us/um/people/cyl/download/papers/\n rouge-working-note-v1.3.1.pdf\n\n Calculated according to:\n R_lcs = SUM(1, u)[LCS<union>(r_i,... |
def rouge(hypotheses, references):
'Calculates average rouge scores for a list of hypotheses and\n references'
rouge_1 = [rouge_n([hyp], [ref], 1) for (hyp, ref) in zip(hypotheses, references)]
(rouge_1_f, rouge_1_p, rouge_1_r) = map(np.mean, zip(*rouge_1))
rouge_2 = [rouge_n([hyp], [ref], 2) for (hy... |
class AttentionSeq2Seq(BasicSeq2Seq):
'Sequence2Sequence model with attention mechanism.\n\n Args:\n source_vocab_info: An instance of `VocabInfo`\n for the source vocabulary\n target_vocab_info: An instance of `VocabInfo`\n for the target vocabulary\n params: A dictionary of hyperparameters\n... |
def _total_tensor_depth(tensor):
'Returns the size of a tensor without the first (batch) dimension'
return np.prod(tensor.get_shape().as_list()[1:])
|
@six.add_metaclass(abc.ABCMeta)
class Bridge(Configurable):
'An abstract bridge class. A bridge defines how state is passed\n between encoder and decoder.\n\n All logic is contained in the `_create` method, which returns an\n initial state for the decoder.\n\n Args:\n encoder_outputs: A namedtuple that cor... |
class ZeroBridge(Bridge):
'A bridge that does not pass any information between encoder and decoder\n and sets the initial decoder state to 0. The input function is not modified.\n '
@staticmethod
def default_params():
return {}
def _create(self):
zero_state = nest.map_structure((la... |
class PassThroughBridge(Bridge):
'Passes the encoder state through to the decoder as-is. This bridge\n can only be used if encoder and decoder have the exact same state size, i.e.\n use the same RNN cell.\n '
@staticmethod
def default_params():
return {}
def _create(self):
nest.as... |
class InitialStateBridge(Bridge):
'A bridge that creates an initial decoder state based on the output\n of the encoder. This state is created by passing the encoder outputs\n through an additional layer to match them to the decoder state size.\n The input function remains unmodified.\n\n Args:\n encoder_ou... |
def _flatten_dict(dict_, parent_key='', sep='.'):
'Flattens a nested dictionary. Namedtuples within\n the dictionary are converted to dicts.\n\n Args:\n dict_: The dictionary to flatten.\n parent_key: A prefix to prepend to each key.\n sep: Separator between parent and child keys, a string. For example... |
class ModelBase(Configurable):
'Abstract base class for models.\n\n Args:\n params: A dictionary of hyperparameter values\n name: A name for this model to be used as a variable scope\n '
def __init__(self, params, mode, name):
self.name = name
Configurable.__init__(self, params, mode)... |
class SchemaAttentionSeq2Seq(BasicSeq2Seq):
'Sequence2Sequence model with attention mechanism for both input sequence\n and database schema.\n\n Args:\n source_vocab_info: An instance of `VocabInfo`\n for the source vocabulary\n target_vocab_info: An instance of `VocabInfo`\n for the target voca... |
class SchemaMapAttentionSeq2Seq(SchemaAttentionSeq2Seq):
'Seq2Seq model with attention to input, schema, and schema map.\n Args:\n source_vocab_info: An instance of `VocabInfo`\n for the source vocabulary\n target_vocab_info: An instance of `VocabInfo`\n for the target vocabulary\n params: A d... |
class DumpBeams(InferenceTask):
'Defines inference for tasks where both the input and output sequences\n are plain text.\n\n Params:\n file: File to write beam search information to.\n '
def __init__(self, params):
super(DumpBeams, self).__init__(params)
self._beam_accum = {'predicted_i... |
def unbatch_dict(dict_):
'Converts a dictionary of batch items to a batch/list of\n dictionary items.\n '
batch_size = list(dict_.values())[0].shape[0]
for i in range(batch_size):
(yield {key: value[i] for (key, value) in dict_.items()})
|
@six.add_metaclass(abc.ABCMeta)
class InferenceTask(tf.train.SessionRunHook, Configurable):
'\n Abstract base class for inference tasks. Defines the logic used to make\n predictions for a specific type of task.\n\n Params:\n model_class: The model class to instantiate. If undefined,\n re-uses the class... |
class AttentionLayerTest(tf.test.TestCase):
'\n Tests the AttentionLayer module.\n '
def setUp(self):
super(AttentionLayerTest, self).setUp()
tf.logging.set_verbosity(tf.logging.INFO)
self.batch_size = 8
self.attention_dim = 128
self.input_dim = 16
self.seq_l... |
class AttentionLayerDotTest(AttentionLayerTest):
'Tests the AttentionLayerDot class'
def _create_layer(self):
return AttentionLayerDot(params={'num_units': self.attention_dim}, mode=tf.contrib.learn.ModeKeys.TRAIN)
def test_layer(self):
self._test_layer()
|
class AttentionLayerBahdanauTest(AttentionLayerTest):
'Tests the AttentionLayerBahdanau class'
def _create_layer(self):
return AttentionLayerBahdanau(params={'num_units': self.attention_dim}, mode=tf.contrib.learn.ModeKeys.TRAIN)
def test_layer(self):
self._test_layer()
|
class TestGatherTree(tf.test.TestCase):
'Tests the gather_tree function'
def test_gather_tree(self):
predicted_ids = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
parent_ids = np.array([[0, 0, 0], [0, 1, 1], [2, 1, 2]])
expected_result = np.array([[2, 2, 2], [6, 5, 6], [7, 8, 9]])
... |
class TestLengthNorm(tf.test.TestCase):
'Tests the length normalization score'
def test_length_norm(self):
lengths_ = np.array([[1, 2, 3], [3, 3, 3]])
penalty_factor_ = 0.6
length_pen = beam_search.length_penalty(sequence_lengths=tf.convert_to_tensor(lengths_), penalty_factor=penalty_... |
class TestBeamStep(tf.test.TestCase):
'Tests a single step of beam search\n '
def setUp(self):
super(TestBeamStep, self).setUp()
self.state_size = 10
config = beam_search.BeamSearchConfig(beam_width=3, vocab_size=5, eos_token=0, length_penalty_weight=0.6, choose_successors_fn=beam_se... |
class TestEosMasking(tf.test.TestCase):
'Tests EOS masking used in beam search\n '
def test_eos_masking(self):
probs = tf.constant([[(- 0.2), (- 0.2), (- 0.2), (- 0.2), (- 0.2)], [(- 0.3), (- 0.3), (- 0.3), 3, 0], [5, 6, 0, 0, 0]])
eos_token = 0
previously_finished = tf.constant([0, ... |
class BridgeTest(tf.test.TestCase):
'Abstract class for bridge tests'
def setUp(self):
super(BridgeTest, self).setUp()
self.batch_size = 4
self.encoder_cell = tf.contrib.rnn.MultiRNNCell([tf.contrib.rnn.GRUCell(4), tf.contrib.rnn.GRUCell(8)])
self.decoder_cell = tf.contrib.rnn... |
class TestZeroBridge(BridgeTest):
'Tests for the ZeroBridge class'
def _create_bridge(self, **kwargs):
return ZeroBridge(encoder_outputs=self.encoder_outputs, decoder_state_size=self.decoder_cell.state_size, params=kwargs, mode=tf.contrib.learn.ModeKeys.TRAIN)
def _assert_correct_outputs(self, i... |
class TestPassThroughBridge(BridgeTest):
'Tests for the ZeroBridge class'
def _create_bridge(self, **kwargs):
return PassThroughBridge(encoder_outputs=self.encoder_outputs, decoder_state_size=self.decoder_cell.state_size, params=kwargs, mode=tf.contrib.learn.ModeKeys.TRAIN)
def _assert_correct_o... |
class TestInitialStateBridge(BridgeTest):
'Tests for the InitialStateBridge class'
def _create_bridge(self, **kwargs):
return InitialStateBridge(encoder_outputs=self.encoder_outputs, decoder_state_size=self.decoder_cell.state_size, params=kwargs, mode=tf.contrib.learn.ModeKeys.TRAIN)
def _assert... |
class ConvEncoderTest(tf.test.TestCase):
'\n Tests the ConvEncoder class.\n '
def setUp(self):
super(ConvEncoderTest, self).setUp()
self.batch_size = 4
self.sequence_length = 16
self.input_depth = 10
self.mode = tf.contrib.learn.ModeKeys.TRAIN
def _test_with_par... |
class SplitTokensDecoderTest(tf.test.TestCase):
'Tests the SplitTokensDecoder class\n '
def test_decode(self):
decoder = split_tokens_decoder.SplitTokensDecoder(delimiter=' ', tokens_feature_name='source_tokens', length_feature_name='source_len')
self.assertEqual(decoder.list_items(), ['sour... |
class ParallelDataProviderTest(tf.test.TestCase):
'Tests the ParallelDataProvider class\n '
def setUp(self):
super(ParallelDataProviderTest, self).setUp()
self.source_lines = ['Hello', 'World', '!', '笑']
self.target_lines = ['1', '2', '3', '笑']
self.source_to_target = dict(zi... |
class DecoderTests(object):
'\n A collection of decoder tests. This class should be inherited together with\n `tf.test.TestCase`.\n '
def __init__(self):
self.batch_size = 4
self.sequence_length = 16
self.input_depth = 10
self.vocab_size = 100
self.max_decode_length... |
class BasicDecoderTest(tf.test.TestCase, DecoderTests):
'Tests the `BasicDecoder` class.\n '
def setUp(self):
tf.test.TestCase.setUp(self)
tf.logging.set_verbosity(tf.logging.INFO)
DecoderTests.__init__(self)
def create_decoder(self, helper, mode):
params = BasicDecoder.... |
class AttentionDecoderTest(tf.test.TestCase, DecoderTests):
'Tests the `AttentionDecoder` class.\n '
def setUp(self):
tf.test.TestCase.setUp(self)
tf.logging.set_verbosity(tf.logging.INFO)
DecoderTests.__init__(self)
self.attention_dim = 64
self.input_seq_len = 10
... |
def _load_model_from_config(config_path, hparam_overrides, vocab_file, mode):
'Loads model from a configuration file'
with gfile.GFile(config_path) as config_file:
config = yaml.load(config_file)
model_cls = (locate(config['model']) or getattr(models, config['model']))
model_params = config['m... |
class ExampleConfigTest(object):
'Interface for configuration-based tests'
def __init__(self, *args, **kwargs):
super(ExampleConfigTest, self).__init__(*args, **kwargs)
self.vocab_file = None
def _config_path(self):
'Returns the path to the configuration to be tested'
rai... |
class TestNMTLarge(ExampleConfigTest, EncoderDecoderTests):
'Tests nmt_large.yml'
def _config_path(self):
return os.path.join(EXAMPLE_CONFIG_DIR, 'nmt_large.yml')
|
class TestNMTMedium(ExampleConfigTest, EncoderDecoderTests):
'Tests nmt_medium.yml'
def _config_path(self):
return os.path.join(EXAMPLE_CONFIG_DIR, 'nmt_medium.yml')
|
class TestNMTSmall(ExampleConfigTest, EncoderDecoderTests):
'Tests nmt_small.yml'
def _config_path(self):
return os.path.join(EXAMPLE_CONFIG_DIR, 'nmt_small.yml')
|
class TestNMTConv(ExampleConfigTest, EncoderDecoderTests):
'Tests nmt_small.yml'
def _config_path(self):
return os.path.join(EXAMPLE_CONFIG_DIR, 'nmt_conv.yml')
|
class TestPrintModelAnalysisHook(tf.test.TestCase):
'Tests the `PrintModelAnalysisHook` hook'
def test_begin(self):
model_dir = tempfile.mkdtemp()
outfile = tempfile.NamedTemporaryFile()
tf.get_variable('weigths', [128, 128])
hook = hooks.PrintModelAnalysisHook(params={}, mode... |
class TestTrainSampleHook(tf.test.TestCase):
'Tests `TrainSampleHook` class.\n '
def setUp(self):
super(TestTrainSampleHook, self).setUp()
self.model_dir = tempfile.mkdtemp()
self.sample_dir = os.path.join(self.model_dir, 'samples')
pred_dict = {}
pred_dict['predicted... |
class TestMetadataCaptureHook(tf.test.TestCase):
'Test for the MetadataCaptureHook'
def setUp(self):
super(TestMetadataCaptureHook, self).setUp()
self.model_dir = tempfile.mkdtemp()
def tearDown(self):
super(TestMetadataCaptureHook, self).tearDown()
shutil.rmtree(self.mod... |
class TestInputPipelineDef(tf.test.TestCase):
'Tests InputPipeline string definitions'
def test_without_extra_args(self):
pipeline_def = yaml.load('\n class: ParallelTextInputPipeline\n params:\n source_files: ["file1"]\n target_files: ["file2"]\n num_epochs: 1\n ... |
class TFRecordsInputPipelineTest(tf.test.TestCase):
'\n Tests Data Provider operations.\n '
def setUp(self):
super(TFRecordsInputPipelineTest, self).setUp()
tf.logging.set_verbosity(tf.logging.INFO)
def test_pipeline(self):
tfrecords_file = test_utils.create_temp_tfrecords(sour... |
class ParallelTextInputPipelineTest(tf.test.TestCase):
'\n Tests Data Provider operations.\n '
def setUp(self):
super(ParallelTextInputPipelineTest, self).setUp()
tf.logging.set_verbosity(tf.logging.INFO)
def test_pipeline(self):
(file_source, file_target) = test_utils.create_t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.