term_frequency_map.cc 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. /* Copyright 2016 Google Inc. All Rights Reserved.
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. ==============================================================================*/
  12. #include "syntaxnet/term_frequency_map.h"
  13. #include <stddef.h>
  14. #include <algorithm>
  15. #include <limits>
  16. #include "tensorflow/core/lib/core/status.h"
  17. #include "tensorflow/core/lib/io/buffered_inputstream.h"
  18. #include "tensorflow/core/lib/io/random_inputstream.h"
  19. #include "tensorflow/core/lib/strings/strcat.h"
  20. #include "tensorflow/core/platform/env.h"
  21. namespace syntaxnet {
  22. int TermFrequencyMap::Increment(const string &term) {
  23. CHECK_EQ(term_index_.size(), term_data_.size());
  24. const TermIndex::const_iterator it = term_index_.find(term);
  25. if (term_index_.find(term) != term_index_.end()) {
  26. // Increment the existing term.
  27. std::pair<string, int64> &data = term_data_[it->second];
  28. CHECK_EQ(term, data.first);
  29. ++(data.second);
  30. return it->second;
  31. } else {
  32. // Add a new term.
  33. const int index = term_index_.size();
  34. CHECK_LT(index, std::numeric_limits<int32>::max()); // overflow
  35. term_index_[term] = index;
  36. term_data_.push_back(std::pair<string, int64>(term, 1));
  37. return index;
  38. }
  39. }
  40. void TermFrequencyMap::Clear() {
  41. term_index_.clear();
  42. term_data_.clear();
  43. }
  44. void TermFrequencyMap::Load(const string &filename, int min_frequency,
  45. int max_num_terms) {
  46. Clear();
  47. // If max_num_terms is non-positive, replace it with INT_MAX.
  48. if (max_num_terms <= 0) max_num_terms = std::numeric_limits<int>::max();
  49. // Read the first line (total # of terms in the mapping).
  50. std::unique_ptr<tensorflow::RandomAccessFile> file;
  51. TF_CHECK_OK(tensorflow::Env::Default()->NewRandomAccessFile(filename, &file));
  52. static const int kInputBufferSize = 1 * 1024 * 1024; /* bytes */
  53. tensorflow::io::RandomAccessInputStream stream(file.get());
  54. tensorflow::io::BufferedInputStream buffer(&stream, kInputBufferSize);
  55. string line;
  56. TF_CHECK_OK(buffer.ReadLine(&line));
  57. int32 total = -1;
  58. CHECK(utils::ParseInt32(line.c_str(), &total));
  59. CHECK_GE(total, 0);
  60. // Read the mapping.
  61. int64 last_frequency = -1;
  62. for (int i = 0; i < total && i < max_num_terms; ++i) {
  63. TF_CHECK_OK(buffer.ReadLine(&line));
  64. std::vector<string> elements = utils::Split(line, ' ');
  65. CHECK_EQ(2, elements.size());
  66. CHECK(!elements[0].empty());
  67. CHECK(!elements[1].empty());
  68. int64 frequency = 0;
  69. CHECK(utils::ParseInt64(elements[1].c_str(), &frequency));
  70. CHECK_GT(frequency, 0);
  71. const string &term = elements[0];
  72. // Check frequency sorting (descending order).
  73. if (i > 0) CHECK_GE(last_frequency, frequency);
  74. last_frequency = frequency;
  75. // Ignore low-frequency items.
  76. if (frequency < min_frequency) continue;
  77. // Check uniqueness of the mapped terms.
  78. CHECK(term_index_.find(term) == term_index_.end())
  79. << "File " << filename << " has duplicate term: " << term;
  80. // Assign the next available index.
  81. const int index = term_index_.size();
  82. term_index_[term] = index;
  83. term_data_.push_back(std::pair<string, int64>(term, frequency));
  84. }
  85. CHECK_EQ(term_index_.size(), term_data_.size());
  86. LOG(INFO) << "Loaded " << term_index_.size() << " terms from " << filename
  87. << ".";
  88. }
  89. struct TermFrequencyMap::SortByFrequencyThenTerm {
  90. // Return a > b to sort in descending order of frequency; otherwise,
  91. // lexicographic sort on term.
  92. bool operator()(const std::pair<string, int64> &a,
  93. const std::pair<string, int64> &b) const {
  94. return (a.second > b.second || (a.second == b.second && a.first < b.first));
  95. }
  96. };
  97. void TermFrequencyMap::Save(const string &filename) const {
  98. CHECK_EQ(term_index_.size(), term_data_.size());
  99. // Copy and sort the term data.
  100. std::vector<std::pair<string, int64>> sorted_data(term_data_);
  101. std::sort(sorted_data.begin(), sorted_data.end(), SortByFrequencyThenTerm());
  102. // Write the number of terms.
  103. std::unique_ptr<tensorflow::WritableFile> file;
  104. TF_CHECK_OK(tensorflow::Env::Default()->NewWritableFile(filename, &file));
  105. CHECK_LE(term_index_.size(), std::numeric_limits<int32>::max()); // overflow
  106. const int32 num_terms = term_index_.size();
  107. const string header = tensorflow::strings::StrCat(num_terms, "\n");
  108. TF_CHECK_OK(file->Append(header));
  109. // Write each term and frequency.
  110. for (size_t i = 0; i < sorted_data.size(); ++i) {
  111. if (i > 0) CHECK_GE(sorted_data[i - 1].second, sorted_data[i].second);
  112. const string line = tensorflow::strings::StrCat(
  113. sorted_data[i].first, " ", sorted_data[i].second, "\n");
  114. TF_CHECK_OK(file->Append(line));
  115. }
  116. TF_CHECK_OK(file->Close()) << "for file " << filename;
  117. LOG(INFO) << "Saved " << term_index_.size() << " terms to " << filename
  118. << ".";
  119. }
  120. TagToCategoryMap::TagToCategoryMap(const string &filename) {
  121. // Load the mapping.
  122. std::unique_ptr<tensorflow::RandomAccessFile> file;
  123. TF_CHECK_OK(tensorflow::Env::Default()->NewRandomAccessFile(filename, &file));
  124. static const int kInputBufferSize = 1 * 1024 * 1024; /* bytes */
  125. tensorflow::io::RandomAccessInputStream stream(file.get());
  126. tensorflow::io::BufferedInputStream buffer(&stream, kInputBufferSize);
  127. string line;
  128. while (buffer.ReadLine(&line) == tensorflow::Status::OK()) {
  129. std::vector<string> pair = utils::Split(line, '\t');
  130. CHECK(line.empty() || pair.size() == 2) << line;
  131. tag_to_category_[pair[0]] = pair[1];
  132. }
  133. }
  134. // Returns the category associated with the given tag.
  135. const string &TagToCategoryMap::GetCategory(const string &tag) const {
  136. const auto it = tag_to_category_.find(tag);
  137. CHECK(it != tag_to_category_.end()) << "No category found for tag " << tag;
  138. return it->second;
  139. }
  140. void TagToCategoryMap::SetCategory(const string &tag, const string &category) {
  141. const auto it = tag_to_category_.find(tag);
  142. if (it != tag_to_category_.end()) {
  143. CHECK_EQ(category, it->second)
  144. << "POS tag cannot be mapped to multiple coarse POS tags. "
  145. << "'" << tag << "' is mapped to: '" << category << "' and '"
  146. << it->second << "'";
  147. } else {
  148. tag_to_category_[tag] = category;
  149. }
  150. }
  151. void TagToCategoryMap::Save(const string &filename) const {
  152. // Write tag and category on each line.
  153. std::unique_ptr<tensorflow::WritableFile> file;
  154. TF_CHECK_OK(tensorflow::Env::Default()->NewWritableFile(filename, &file));
  155. for (const auto &pair : tag_to_category_) {
  156. const string line =
  157. tensorflow::strings::StrCat(pair.first, "\t", pair.second, "\n");
  158. TF_CHECK_OK(file->Append(line));
  159. }
  160. TF_CHECK_OK(file->Close()) << "for file " << filename;
  161. }
  162. } // namespace syntaxnet