-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlabel_to_vector.py
277 lines (227 loc) · 7.71 KB
/
label_to_vector.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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import collections
import json
import os
import random
import re
from typing import Dict, List, Any
import MeCab
import numpy as np
import pandas as pd
from gensim import models, corpora, matutils
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import StandardScaler
from image_to_labels import get_labels_and_rects, get_xywh
REDUCTOR_PKL = "static/tmp_reductor.pkl"
LR_PKL = 'static/tmp_lr.pkl'
ET_PKL = 'static/tmp_et.pkl'
DICT_PKL = "static/tmp_dict.pkl"
SCALER_PKL = "static/tmp_scaler.pkl"
CATEGORY2TOKENS_LIST_JSON = "static/tmp_category2tokens_list.json"
CATEGORY_CSV = "static/category.csv"
MIN_SIZE = 30
NUM_TOPICS = 30
# https://shogo82148.github.io/blog/2015/12/20/mecab-in-python3-final/
mecab_tokenizer = MeCab.Tagger("")
mecab_tokenizer.parse('')
def tokenize(text: str) -> List[str]:
tokens = []
node = mecab_tokenizer.parseToNode(text)
while node:
feats = node.feature.split(",")
surface = node.surface
if feats[0] in ['名詞'] or surface in ["あり", "有り", "アリ", "なし", "無し", "ナシ"]:
surface = re.sub(r"\d", "0", surface)
tokens.append(surface)
node = node.next
# print(text, tokens)
return tokens
def vec2dense(vec, num_terms):
return list(matutils.corpus2dense([vec], num_terms=num_terms).T[0])
def sparse_to_dense(vec):
ret = [e[1] for e in vec]
return ret
def get_tokens(labels: List[Dict[str, Any]], rects: List[Dict[str, int]], i: int) -> List[str]:
x, y, w, h = get_xywh(rects[i])
tokens = []
added_texts = []
# 中と左横、直下のテキストを見る
for cur_y in range(y, y + h, 10):
for label in labels:
x2, y2, w2, h2 = get_xywh(label)
text = label["text"]
if text in added_texts:
continue
if y2 <= cur_y < y2 + h2 and (x2 <= x < x2 + w2 or x <= x2 < x + w or x2 + w2 < x):
tokens += tokenize(text)
added_texts.append(text)
if tokens:
return tokens
# 見つからないなら、上のテキストを見る
for cur_y in range(y - 10, y - 51, -10):
for label in labels:
x2, y2, w2, h2 = get_xywh(label)
text = label["text"]
if text in added_texts:
continue
if y2 <= cur_y < y2 + h2:
tokens += tokenize(text)
added_texts.append(text)
if tokens:
return tokens
# 見つからないなら、下のテキストを見る
for cur_y in range(y + h + 10, y + h + 51, 10):
for label in labels:
x2, y2, w2, h2 = get_xywh(label)
text = label["text"]
if text in added_texts:
continue
if y2 <= cur_y < y2 + h2:
tokens += tokenize(text)
added_texts.append(text)
if tokens:
return tokens
# 見つからないなら、もっと上のテキストを見る
for cur_y in range(y - 51, y - 101, -10):
for label in labels:
x2, y2, w2, h2 = get_xywh(label)
text = label["text"]
if text in added_texts:
continue
if y2 <= cur_y < y2 + h2:
tokens += tokenize(text)
added_texts.append(text)
if tokens:
return tokens
# 見つからないなら、もっと下のテキストを見る
for cur_y in range(y + h + 51, y + h + 101, 10):
for label in labels:
x2, y2, w2, h2 = get_xywh(label)
text = label["text"]
if text in added_texts:
continue
if y2 <= cur_y < y2 + h2:
tokens += tokenize(text)
added_texts.append(text)
if tokens:
return tokens
return tokens
def get_typetext_count_tokens(rects: List[Dict[str, int]], i: int) -> List[str]:
rect = rects[i]
x, y, w, h = get_xywh(rect)
tokens = []
# 左横にあるtype=textの数を数える
left = 0
for i2 in range(len(rects)):
if i == i2:
continue
rect2 = rects[i2]
x2, y2, w2, h2 = get_xywh(rect2)
if (y2 <= y + h / 2 < y2 + h2 or y <= y2 + h2 / 2 < y + h) and x2 + w2 < x:
left += 1
if left > 0:
tokens.append("__LEFT_COUNT_%d__" % left)
# 右横にあるtype=textの数を数える
right = 0
for i2 in range(len(rects)):
if i == i2:
continue
rect2 = rects[i2]
x2, y2, w2, h2 = get_xywh(rect2)
if (y2 <= y + h / 2 < y2 + h2 or y <= y2 + h2 / 2 < y + h) and x + w < x2:
right += 1
if right > 0:
tokens.append("__RIGHT_COUNT_%d__" % right)
return tokens
def get_category2tokens_list():
if os.path.exists(CATEGORY2TOKENS_LIST_JSON):
with open(CATEGORY2TOKENS_LIST_JSON) as f:
return json.load(f)
df = pd.read_csv(CATEGORY_CSV)
gs = df.query("deleted == False and done == True").groupby(["page_id", "form_id"])
x = []
y = []
category2tokens_list = collections.defaultdict(list)
for g in gs:
page_id = g[0][0]
form_id = int(g[0][1])
rows = g[1]
typetext_ids = rows["typetext_id"].astype("int").tolist()
jpg_path = "static/data/%s/%d.jpg" % (page_id, form_id)
rects_json_path = "static/data/%s/%d.json" % (page_id, form_id)
labels, rects = get_labels_and_rects(jpg_path, rects_json_path)
for i in typetext_ids:
tokens = get_tokens(labels, rects, i)
tokens += get_typetext_count_tokens(rects, i)
x.append(tokens)
row = rows.query("typetext_id == %d" % i).iloc[0]
category = row["value"]
y.append(category)
category2tokens_list[category].append(tokens)
print(page_id, form_id, i, tokens, category)
with open(CATEGORY2TOKENS_LIST_JSON, "w") as f:
json.dump(category2tokens_list, f, indent=2)
return category2tokens_list
def get_XY():
category2tokens_list = get_category2tokens_list()
too_few_categories = []
# サンプルデータ内のカテゴリの出現数を同じにする
for category in category2tokens_list:
tokens_list = category2tokens_list[category]
if len(tokens_list) >= MIN_SIZE:
random.shuffle(tokens_list)
category2tokens_list[category] = tokens_list[:MIN_SIZE]
else:
too_few_categories.append(category)
# 出現回数が少なすぎるカテゴリを除去
for category in too_few_categories:
del category2tokens_list[category]
X = []
Y = []
for category in category2tokens_list:
for tokens in category2tokens_list[category]:
X.append(tokens)
Y.append(category)
print("%d unique labels" % len(set(Y)))
X = np.array(X)
Y = np.array(Y)
# 2:1の比率で訓練データとテストデータに分割する
kf = StratifiedKFold(n_splits=3, shuffle=True)
X_train = Y_train = X_test = Y_test = None
for train_index, test_index in kf.split(X, Y):
print(len(train_index), len(test_index))
X_train = X[train_index]
Y_train = Y[train_index]
X_test = X[test_index]
Y_test = Y[test_index]
break
# BoW化
dictionary = corpora.Dictionary(X_train)
corpus = [dictionary.doc2bow(x) for x in X_train]
# 次元削減
reductor = models.LsiModel(corpus, id2word=dictionary, num_topics=NUM_TOPICS)
X_train2, Y_train2 = apply_reductor(X_train, Y_train, dictionary, reductor)
# 標準化
scaler = StandardScaler()
scaler.fit(X_train2)
X_train2 = scaler.transform(X_train2)
# テストデータも同様の処理をする
X_test2, Y_test2 = apply_reductor(X_test, Y_test, dictionary, reductor)
X_test2 = scaler.transform(X_test2)
return X_train2, Y_train2, X_test2, Y_test2
def apply_reductor(X, Y, dictionary, reductor):
X_reducted = []
Y_reducted = []
for i in range(len(X)):
x = X[i]
vec_bow = dictionary.doc2bow(x)
vec_reducted = sparse_to_dense(reductor[vec_bow])
# 全部0だと[]を返すので[0,0,...]に直す
if len(vec_reducted) < NUM_TOPICS:
vec_reducted = [0 for _ in range(NUM_TOPICS)]
X_reducted.append(vec_reducted)
Y_reducted.append(Y[i])
return X_reducted, Y_reducted
if __name__ == "__main__":
X_train_, Y_train_, X_test_, Y_test_ = get_XY()
print(X_train_, Y_train_, X_test_, Y_test_)
pass