| 233 | } |
| 234 | |
| 235 | float Lattice::PopulateMarginal(float freq, |
| 236 | std::vector<float> *expected) const { |
| 237 | if (expected == nullptr) return 0.0; |
| 238 | |
| 239 | const int len = size(); |
| 240 | |
| 241 | // alpha and beta (accumulative log prob) in Forward Backward. |
| 242 | // the index of alpha/beta is Node::node_id. |
| 243 | |
| 244 | const auto alpha = ForwardAlgorithm(1.0); |
| 245 | const auto beta = BackwardAlgorithm(1.0); |
| 246 | |
| 247 | const float Z = alpha[begin_nodes_[len][0]->node_id]; |
| 248 | for (int pos = 0; pos < len; ++pos) { |
| 249 | for (Node *node : begin_nodes_[pos]) { |
| 250 | if (node->id >= 0) { |
| 251 | // the index of |expected| is a Node::id, which is a vocabulary id. |
| 252 | (*expected)[node->id] += |
| 253 | freq * |
| 254 | std::exp(static_cast<double>(alpha[node->node_id] + node->score + |
| 255 | beta[node->node_id] - Z)); |
| 256 | } |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | return freq * Z; |
| 261 | } |
| 262 | |
| 263 | float Lattice::CalculateEntropy(float inv_theta) const { |
| 264 | const int len = size(); |