Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

keras_topk_word_predictions_layer.py 1.7 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
  1. import tensorflow as tf
  2. from tensorflow import keras
  3. from tensorflow.keras.layers import Layer
  4. import tensorflow.keras.backend as K
  5. from collections import namedtuple
  6. TopKWordPredictionsLayerResult = namedtuple('TopKWordPredictionsLayerResult', ['words', 'scores'])
  7. class TopKWordPredictionsLayer(Layer):
  8. def __init__(self,
  9. top_k: int,
  10. index_to_word_table: tf.lookup.StaticHashTable,
  11. **kwargs):
  12. kwargs['dtype'] = tf.string
  13. kwargs['trainable'] = False
  14. super(TopKWordPredictionsLayer, self).__init__(**kwargs)
  15. self.top_k = top_k
  16. self.index_to_word_table = index_to_word_table
  17. def build(self, input_shape):
  18. if len(input_shape) < 2:
  19. raise ValueError("Input shape for TopKWordPredictionsLayer should be of >= 2 dimensions.")
  20. if input_shape[-1] < self.top_k:
  21. raise ValueError("Last dimension of input shape for TopKWordPredictionsLayer should be of >= `top_k`.")
  22. super(TopKWordPredictionsLayer, self).build(input_shape)
  23. self.trainable = False
  24. def call(self, y_pred, **kwargs) -> TopKWordPredictionsLayerResult:
  25. top_k_pred_scores, top_k_pred_indices = tf.nn.top_k(y_pred, k=self.top_k, sorted=True)
  26. top_k_pred_indices = tf.cast(top_k_pred_indices, dtype=self.index_to_word_table.key_dtype)
  27. top_k_pred_words = self.index_to_word_table.lookup(top_k_pred_indices)
  28. return TopKWordPredictionsLayerResult(words=top_k_pred_words, scores=top_k_pred_scores)
  29. def compute_output_shape(self, input_shape):
  30. output_shape = tuple(input_shape[:-1]) + (self.top_k, )
  31. return output_shape, output_shape
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...