Encoder based on a user-supplied vocabulary (file or list).
| 741 | |
| 742 | |
| 743 | class TokenTextEncoder(TextEncoder): |
| 744 | """Encoder based on a user-supplied vocabulary (file or list).""" |
| 745 | |
| 746 | def __init__(self, |
| 747 | vocab_filename, |
| 748 | reverse=False, |
| 749 | vocab_list=None, |
| 750 | replace_oov="UNK", |
| 751 | num_reserved_ids=NUM_RESERVED_TOKENS): |
| 752 | """Initialize from a file or list, one token per line. |
| 753 | |
| 754 | Handling of reserved tokens works as follows: |
| 755 | - When initializing from a list, we add reserved tokens to the vocab. |
| 756 | - When initializing from a file, we do not add reserved tokens to the vocab. |
| 757 | - When saving vocab files, we save reserved tokens to the file. |
| 758 | |
| 759 | Args: |
| 760 | vocab_filename: If not None, the full filename to read vocab from. If this |
| 761 | is not None, then vocab_list should be None. |
| 762 | reverse: Boolean indicating if tokens should be reversed during encoding |
| 763 | and decoding. |
| 764 | vocab_list: If not None, a list of elements of the vocabulary. If this is |
| 765 | not None, then vocab_filename should be None. |
| 766 | replace_oov: If not None, every out-of-vocabulary token seen when |
| 767 | encoding will be replaced by this string (which must be in vocab). |
| 768 | num_reserved_ids: Number of IDs to save for reserved tokens like <EOS>. |
| 769 | """ |
| 770 | super(TokenTextEncoder, self).__init__(num_reserved_ids=num_reserved_ids) |
| 771 | self._reverse = reverse |
| 772 | self._replace_oov = replace_oov |
| 773 | if vocab_filename: |
| 774 | self._init_vocab_from_file(vocab_filename) |
| 775 | else: |
| 776 | assert vocab_list is not None |
| 777 | self._init_vocab_from_list(vocab_list) |
| 778 | |
| 779 | @classmethod |
| 780 | def build_from_corpus(cls, filenames, vocab_size): |
| 781 | """ |
| 782 | |
| 783 | :param filenames: |
| 784 | :param vocab_size: |
| 785 | :return: |
| 786 | """ |
| 787 | |
| 788 | def create_dictionary(names, lim=0): |
| 789 | """ |
| 790 | :param name: |
| 791 | :param lim: |
| 792 | :return: |
| 793 | """ |
| 794 | global_counter = collections.Counter() |
| 795 | for name in names: |
| 796 | fd = open(name) |
| 797 | for line in fd: |
| 798 | words = line.strip().split() |
| 799 | words = filter(lambda x: x != "-1", words) |
| 800 | global_counter.update(words) |
no outgoing calls
no test coverage detected