(config, ues_word)
| 29 | |
| 30 | |
| 31 | def build_dataset(config, ues_word): |
| 32 | if ues_word: |
| 33 | tokenizer = lambda x: x.split(' ') # 以空格隔开,word-level |
| 34 | else: |
| 35 | tokenizer = lambda x: [y for y in x] # char-level |
| 36 | if os.path.exists(config.vocab_path): |
| 37 | vocab = pkl.load(open(config.vocab_path, 'rb')) |
| 38 | else: |
| 39 | vocab = build_vocab(config.train_path, tokenizer=tokenizer, max_size=MAX_VOCAB_SIZE, min_freq=1) |
| 40 | pkl.dump(vocab, open(config.vocab_path, 'wb')) |
| 41 | print(f"Vocab size: {len(vocab)}") |
| 42 | |
| 43 | def biGramHash(sequence, t, buckets): |
| 44 | t1 = sequence[t - 1] if t - 1 >= 0 else 0 |
| 45 | return (t1 * 14918087) % buckets |
| 46 | |
| 47 | def triGramHash(sequence, t, buckets): |
| 48 | t1 = sequence[t - 1] if t - 1 >= 0 else 0 |
| 49 | t2 = sequence[t - 2] if t - 2 >= 0 else 0 |
| 50 | return (t2 * 14918087 * 18408749 + t1 * 14918087) % buckets |
| 51 | |
| 52 | def load_dataset(path, pad_size=32): |
| 53 | contents = [] |
| 54 | with open(path, 'r', encoding='UTF-8') as f: |
| 55 | for line in tqdm(f): |
| 56 | lin = line.strip() |
| 57 | if not lin: |
| 58 | continue |
| 59 | content, label = lin.split('\t') |
| 60 | words_line = [] |
| 61 | token = tokenizer(content) |
| 62 | seq_len = len(token) |
| 63 | if pad_size: |
| 64 | if len(token) < pad_size: |
| 65 | token.extend([PAD] * (pad_size - len(token))) |
| 66 | else: |
| 67 | token = token[:pad_size] |
| 68 | seq_len = pad_size |
| 69 | # word to id |
| 70 | for word in token: |
| 71 | words_line.append(vocab.get(word, vocab.get(UNK))) |
| 72 | |
| 73 | # fasttext ngram |
| 74 | buckets = config.n_gram_vocab |
| 75 | bigram = [] |
| 76 | trigram = [] |
| 77 | # ------ngram------ |
| 78 | for i in range(pad_size): |
| 79 | bigram.append(biGramHash(words_line, i, buckets)) |
| 80 | trigram.append(triGramHash(words_line, i, buckets)) |
| 81 | # ----------------- |
| 82 | contents.append((words_line, int(label), seq_len, bigram, trigram)) |
| 83 | return contents # [([...], 0), ([...], 1), ...] |
| 84 | train = load_dataset(config.train_path, config.pad_size) |
| 85 | dev = load_dataset(config.dev_path, config.pad_size) |
| 86 | test = load_dataset(config.test_path, config.pad_size) |
| 87 | return vocab, train, dev, test |
| 88 |
nothing calls this directly
no test coverage detected