* \brief Samples a string of words/characters from the model * \details This can be used to debug and/or have fun. Try it on * new datasets! * * \param d Dictionary to use (should be same as the one used for training) * \param max_len maximu number of tokens to generate * \param temp Temperature for sampling (the softmax computed is * \f$\frac{e^{\frac{r_t^{(i)}}{T}}}{\sum_{j=
| 162 | * Intuitively lower temperature -> less deviation from the distribution (= more "standard" samples) |
| 163 | */ |
| 164 | void RandomSample(const dynet::Dict& d, int max_len = 150, float temp = 1.0) { |
| 165 | // Make some space |
| 166 | cerr << endl; |
| 167 | // Initialize computation graph |
| 168 | ComputationGraph cg; |
| 169 | // Initialize the RNN for the new computation graph |
| 170 | rnn.new_graph(cg); |
| 171 | // Initialize for new sequence (set hidden states, etc..) |
| 172 | rnn.start_new_sequence(); |
| 173 | // Instantiate embedding parameters in the computation graph |
| 174 | // output -> word rep parameters (matrix + bias) |
| 175 | Expression i_R = parameter(cg, p_R); |
| 176 | Expression i_bias = parameter(cg, p_bias); |
| 177 | |
| 178 | // Start generating |
| 179 | int len = 0; |
| 180 | int cur = kSOS; |
| 181 | while (len < max_len) { |
| 182 | ++len; |
| 183 | // Embed current token |
| 184 | Expression i_x_t = lookup(cg, p_c, cur); |
| 185 | // Run one step of the rnn |
| 186 | // y_t = RNN(x_t) |
| 187 | Expression i_y_t = rnn.add_input(i_x_t); |
| 188 | // Project into token space |
| 189 | Expression i_r_t = i_bias + i_R * i_y_t; |
| 190 | // Get distribution over tokens (with temperature) |
| 191 | Expression ydist = softmax(i_r_t / temp); |
| 192 | |
| 193 | // Sample token |
| 194 | unsigned w = 0; |
| 195 | while (w == 0 || (int)w == kSOS) { |
| 196 | auto dist = as_vector(cg.incremental_forward(ydist)); |
| 197 | double p = rand01(); |
| 198 | for (; w < dist.size(); ++w) { |
| 199 | p -= dist[w]; |
| 200 | if (p < 0.0) { break; } |
| 201 | } |
| 202 | if (w == dist.size()) w = kEOS; |
| 203 | } |
| 204 | |
| 205 | if (static_cast<int>(w) == kEOS) { |
| 206 | // If the sampled token is an EOS, reinitialize network and start generating a new sample |
| 207 | rnn.start_new_sequence(); |
| 208 | cerr << endl; |
| 209 | cur = kSOS; |
| 210 | } else { |
| 211 | // Otherwise print token and continue |
| 212 | cerr << (cur == kSOS ? "" : " ") << d.convert(w); |
| 213 | cur = w; |
| 214 | } |
| 215 | |
| 216 | } |
| 217 | cerr << endl; |
| 218 | } |
| 219 | }; |
| 220 | |
| 221 | #endif |
no test coverage detected