Created
December 18, 2017 00:06
-
-
Save wangkuiyi/f95aa5495d34a1ed3e1061b00b42c53f to your computer and use it in GitHub Desktop.
Beam search implemented in C++11
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// To build this program: g++ -std=c++11 beam_search.cc -o bs | |
// | |
#include <iostream> | |
#include <set> | |
#include <string> | |
#include <functional> | |
#include <map> | |
#include <utility> | |
#include <algorithm> | |
typedef std::string Alphabet; | |
typedef std::string Sequence; // for operator +, or we can use vector and define +. | |
typedef std::function<double(const Sequence&, double, char)> ScoreFn; | |
typedef std::multimap<double, Sequence> Boundary; | |
void print_boundary(const Boundary& boundary) { | |
for (auto& t : boundary) { | |
std::cout << t.first << " : " << t.second << "\n"; | |
} | |
} | |
void beam_search(const Alphabet& alphabet, ScoreFn score_fn, int T, size_t K) { | |
Boundary boundary = { {0.0, ""} }; | |
for (int t = 0; t < T; t++) { | |
Boundary new_boundary; | |
for (auto& beam : boundary) { | |
for (auto& letter : alphabet) { | |
new_boundary.insert(make_pair(score_fn(beam.second, beam.first, letter), | |
beam.second + letter)); | |
} | |
} | |
size_t k = std::min(K, new_boundary.size()); | |
boundary.clear(); | |
std::copy_n(new_boundary.begin(), k, std::inserter(boundary, boundary.begin())); | |
print_boundary(boundary); | |
std::cout << "\n"; | |
} | |
} | |
int main() { | |
const Alphabet alphabet { 'a', 'z' }; | |
beam_search(alphabet, | |
[](const Sequence& seq, double weight, char letter) { | |
return weight - static_cast<double>(letter); | |
}, | |
4, 5); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It outputs: