prepare train data to embedded word vector sequence given sequence limit return: questions_encoded: np ndarray, shape (number samples, seq length, vector size) poss_encoded: same layout, sequence for positive answer negs_encoded: same layo
(train_raw, label2answer, idx2word, q_seq_limit,
ans_seq_limit, idx2vec)
| 112 | |
| 113 | |
| 114 | def limit_encode_train(train_raw, label2answer, idx2word, q_seq_limit, |
| 115 | ans_seq_limit, idx2vec): |
| 116 | ''' prepare train data to embedded word vector sequence given sequence limit |
| 117 | return: |
| 118 | questions_encoded: np ndarray, shape |
| 119 | (number samples, seq length, vector size) |
| 120 | poss_encoded: same layout, sequence for positive answer |
| 121 | negs_encoded: same layout, sequence for negative answer |
| 122 | ''' |
| 123 | questions = [question for question, answers, candis in train_raw] |
| 124 | # choose 1 answer from answer pool |
| 125 | poss = [ |
| 126 | label2answer[random.choice(answers)] |
| 127 | for question, answers, candis in train_raw |
| 128 | ] |
| 129 | # choose 1 candidate from candidate pool |
| 130 | negs = [ |
| 131 | label2answer[random.choice(candis)] |
| 132 | for question, answers, candis in train_raw |
| 133 | ] |
| 134 | |
| 135 | # filtered word not in idx2vec |
| 136 | questions_filtered = [ |
| 137 | [idx for idx in q if idx in idx2vec] for q in questions |
| 138 | ] |
| 139 | poss_filtered = [[idx for idx in ans if idx in idx2vec] for ans in poss] |
| 140 | negs_filtered = [[idx for idx in ans if idx in idx2vec] for ans in negs] |
| 141 | |
| 142 | # crop to seq limit |
| 143 | questions_crop = [ |
| 144 | q[:q_seq_limit] + [0] * max(0, q_seq_limit - len(q)) |
| 145 | for q in questions_filtered |
| 146 | ] |
| 147 | poss_crop = [ |
| 148 | ans[:ans_seq_limit] + [0] * max(0, ans_seq_limit - len(ans)) |
| 149 | for ans in poss_filtered |
| 150 | ] |
| 151 | negs_crop = [ |
| 152 | ans[:ans_seq_limit] + [0] * max(0, ans_seq_limit - len(ans)) |
| 153 | for ans in negs_filtered |
| 154 | ] |
| 155 | |
| 156 | # encoded, word idx to word vector |
| 157 | questions_encoded = [[idx2vec[idx] for idx in q] for q in questions_crop] |
| 158 | poss_encoded = [[idx2vec[idx] for idx in ans] for ans in poss_crop] |
| 159 | negs_encoded = [[idx2vec[idx] for idx in ans] for ans in negs_crop] |
| 160 | |
| 161 | # make nd array |
| 162 | questions_encoded = np.array(questions_encoded).astype(np.float32) |
| 163 | poss_encoded = np.array(poss_encoded).astype(np.float32) |
| 164 | negs_encoded = np.array(negs_encoded).astype(np.float32) |
| 165 | return questions_encoded, poss_encoded, negs_encoded |
| 166 | |
| 167 | |
| 168 | def get_idx2vec_weights(wv, idx2word): |