-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
180 lines (141 loc) · 4.83 KB
/
main.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
"""
- https://archive.ics.uci.edu/ml/datasets/Twenty+Newsgroups
"""
import os
import logging
from typing import Optional, List
from collections import OrderedDict
from abc import ABC, abstractmethod
import tqdm
import numpy as np
ENG_CHARS = "abcdefghijklmnopqrstuvwxyz"
class Tokenizer(ABC):
@abstractmethod
def next(self) -> Optional[str]:
raise NotImplementedError
@abstractmethod
def reset(self) -> 'Tokenizer':
raise NotImplementedError
class SimpleTokenizer(Tokenizer):
def __init__(self, tokens: List[str]):
self.tokens = tokens
self.index = 0
def next(self) -> Optional[str]:
if self.index >= len(self.tokens):
return None
token = self.tokens[self.index]
self.index += 1
return token
def reset(self) -> 'Tokenizer':
self.index = 0
return self
class FileTokenizer(Tokenizer):
def __init__(self, filename: str):
lines = []
with open(filename, "r", encoding="utf-8", errors="ignore") as f:
for line in f:
lines.append(line.strip())
cnt1, cnt2 = None, None
for i, line in enumerate(lines):
if line.startswith("Lines:"):
try:
cnt1 = int(line[6:].strip())
break
except Exception as e:
logging.warning("parse int with error %s", e)
if cnt2 is None and len(line) == 0:
cnt2 = i
if cnt1 is not None:
lines = lines[-cnt1:]
elif cnt2 is not None:
lines = lines[cnt2:]
self.lines = "\n".join(lines)
self.pos = 0
def _next(self) -> Optional[str]:
while self.pos < len(self.lines):
c = self.lines[self.pos].lower()
if c in ENG_CHARS:
break
self.pos += 1
if self.pos >= len(self.lines):
return None
token = ""
while self.pos < len(self.lines):
c = self.lines[self.pos].lower()
if c not in ENG_CHARS:
break
token += c
self.pos += 1
return token
def next(self) -> Optional[str]:
while True:
token = self._next()
if token is None or len(token) > 1:
return token
def reset(self) -> 'Tokenizer':
self.pos = 0
return self
def test_file_tokenizer(filename):
tokenizer = FileTokenizer(filename)
print(tokenizer.lines)
tokens = []
while True:
token = tokenizer.next()
if token is None:
break
tokens.append(token)
print(tokens)
def check_file_tokenizer():
files = [os.path.join("20_newsgroups", file) for file in os.listdir("20_newsgroups")]
files = [os.path.join(file, file1) for file in files for file1 in os.listdir(file)]
for file in tqdm.tqdm(files):
try:
FileTokenizer(file)
except Exception as e:
print(file, e)
def build(tokenizers: List[Tokenizer], mode: int = 0):
tokens = OrderedDict()
for tokenizer in tokenizers:
while True:
token = tokenizer.next()
if token is None:
break
tokens[token] = 0
for tokenizer in tokenizers:
tokenizer.reset()
m = np.array([[] for _ in range(len(tokens))])
for tokenizer in tokenizers:
for token in tokens:
tokens[token] = 0
while True:
token = tokenizer.next()
if token is None:
break
tokens[token] = (0 if mode == 0 else tokens[token]) + 1
c = np.array([[cnt] for token, cnt in tokens.items()])
m = np.append(m, c, axis=1)
for token in tokens:
tokens[token] = 0
return tokens, m
if __name__ == "__main__":
test_file_tokenizer("20_newsgroups\\alt.atheism\\49960")
check_file_tokenizer()
tokenizer1 = SimpleTokenizer(["this", "is", "a", "a", "sample"])
tokenizer2 = SimpleTokenizer(["this", "is", "another", "another", "example", "example", "example"])
tokens, m = build([tokenizer1, tokenizer2], mode=0)
print(tokens.keys())
print(m)
tokenizer1 = SimpleTokenizer(["this", "is", "a", "a", "sample"])
tokenizer2 = SimpleTokenizer(["this", "is", "another", "another", "example", "example", "example"])
tokens, m = build([tokenizer1, tokenizer2], mode=1)
print(tokens.keys())
print(m)
files = [os.path.join("20_newsgroups", file) for file in os.listdir("20_newsgroups")]
files = [os.path.join(file, file1) for file in files for file1 in os.listdir(file)]
files = files[:500]
tokenizers = [FileTokenizer(train_file) for train_file in files]
tokens, m = build(tokenizers, mode=0)
print(len(tokens.keys()))
print(m.shape)
U, S, Vh = np.linalg.svd(m)
print(U.shape, S.shape, Vh.shape)