| 165 | |
| 166 | |
| 167 | def generate(self, word2idx): |
| 168 | # convert word2idx -> idx2word |
| 169 | idx2word = {v:k for k,v in iteritems(word2idx)} |
| 170 | V = len(word2idx) |
| 171 | |
| 172 | # generate 4 lines at a time |
| 173 | n_lines = 0 |
| 174 | |
| 175 | # why? because using the START symbol will always yield the same first word! |
| 176 | X = [ 0 ] |
| 177 | while n_lines < 4: |
| 178 | # print "X:", X |
| 179 | PY_X, _ = self.predict_op(X) |
| 180 | PY_X = PY_X[-1].flatten() |
| 181 | P = [ np.random.choice(V, p=PY_X)] |
| 182 | X = np.concatenate([X, P]) # append to the sequence |
| 183 | # print "P.shape:", P.shape, "P:", P |
| 184 | P = P[-1] # just grab the most recent prediction |
| 185 | if P > 1: |
| 186 | # it's a real word, not start/end token |
| 187 | word = idx2word[P] |
| 188 | print(word, end=" ") |
| 189 | elif P == 1: |
| 190 | # end token |
| 191 | n_lines += 1 |
| 192 | X = [0] |
| 193 | print('') |
| 194 | |
| 195 | |
| 196 | def train_poetry(): |