forked from florijanstamenkovic/PytorchRnnLM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_loader.py
executable file
·60 lines (47 loc) · 1.73 KB
/
data_loader.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
Loads and preprocesses the "Wikitext long term dependency
language modeling dataset:
https://einstein.ai/research/the-wikitext-long-term-dependency-language-modeling-dataset
Lowercases all the words and splits into sentences, omitting
the ending period. Add sentence start/end tokens.
"""
import os
from vocab import Vocab
SENT_START = "<sentence_start>"
SENT_END = "<sentence_end>"
def path(part):
""" Gets the dataset for 'part' being train|test|valid. """
assert part in ("train", "test", "valid")
return os.path.join("wikitext-2", "wiki." + part + ".tokens")
def load(path, index):
""" Loads the wikitext2 data at the given path using
the given index (maps tokens to indices). Returns
a list of sentences where each is a list of token
indices.
"""
start = index.add(SENT_START)
sentences = []
with open(path, "r") as f:
for paragraph in f:
for sentence in paragraph.split(" . "):
tokens = sentence.split()
if not tokens:
continue
sentence = [index.add(SENT_START)]
sentence.extend(index.add(t.lower()) for t in tokens)
sentence.append(index.add(SENT_END))
sentences.append(sentence)
return sentences
def main():
print("WikiText2 preprocessing test and dataset statistics")
index = Vocab()
for part in ("train", "valid", "test"):
print("Processing", part)
sentences = load(path(part), index)
print("Found", sum(len(s) for s in sentences),
"tokens in", len(sentences), "sentences")
print("Found in total", len(index), "tokens")
if __name__ == '__main__':
main()