-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.py
More file actions
245 lines (207 loc) · 6.27 KB
/
Copy pathutils.py
File metadata and controls
245 lines (207 loc) · 6.27 KB
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
#!/usr/bin/env python
# encoding: utf-8
'''
@author: slade
@file: utils.py
@time: 2020/9/26 16:41
@desc:
'''
import sys
import os
getModulePath = lambda p: os.path.join(os.path.dirname(__file__), p)
sys.path.append(getModulePath("."))
import json
from Config import Config
import numpy as np
from random import choice
import re
rule = re.compile("[^\u4e00-\u9fa5a-zA-Z0-9.,,。!?!?]<>《》\'\"")
def load_vocab(file_path):
'''字映射'''
word_dict = {}
with open(file_path, encoding='utf8') as f:
for idx, word in enumerate(f.readlines()):
word = word.strip()
word_dict[word] = idx
return word_dict
def gen_word_set(file_path="title_reviews.txt", out_path='./data/chars.txt'):
'''扩充字映射表'''
char_set = set()
with open(file_path, encoding='utf8') as f:
for line in f.readlines():
spline = line.strip().split('\t')
if len(spline) != 6:
continue
char_set.update(set("".join(spline)))
with open(out_path, 'w', encoding='utf8') as out:
for w in char_set:
out.write(w + '\n')
pass
def convert_word2id(query, vocab_map):
'''query转换为id'''
ids = []
for w in query:
ids.append(vocab_map.get(w, vocab_map[Config.unk]))
while len(ids) < Config.sequenceLength:
ids.append(vocab_map[Config.pad])
return ids[:Config.sequenceLength]
def convert_seq2bow(query, vocab_map):
'''query做onehot'''
bow_ids = np.zeros(len(vocab_map))
for w in query:
bow_ids[vocab_map.get(w, vocab_map[Config.unk])] += 1
return bow_ids
def convert_word2bow(wordid, vocab_map):
'''query做onehot'''
bow_ids = np.zeros(len(vocab_map))
for w in wordid:
if w == 0:
continue
bow_ids[w] += 1
return bow_ids
def is_num_by_except(num):
try:
int(num.replace(" ", ""))
return True
except ValueError:
# print "%s ValueError" % num
return False
def _reshape_input(file_path):
formated_data = {}
with open(file_path, encoding='utf8') as f:
for line in f.readlines():
spline = line.strip().split('\t')
if len(spline) != 4:
continue
news_id, title, reviews, scores = spline
if formated_data.get(title):
formated_data[title] = list(set(formated_data[title] + eval(reviews)))
else:
formated_data[title] = list(set(eval(reviews)))
formated_data_final = {}
for k, v in formated_data.items():
tmp = []
for review in v:
review = review.replace("\u200b", "").replace(" ", "").strip()
# 过短
if len(review) < 2:
continue
# 网址广告
if "http" in review or "www." in review:
continue
# 过长
if len(review) > 20:
continue
# 純數字
if is_num_by_except(review):
continue
tmp.append(review)
if len(tmp) > 0:
formated_data_final[k] = tmp
return formated_data_final
def genSamples(file_path, out_path="title_reviews.txt"):
formated_data_final = _reshape_input(file_path)
neg_reviews = list(formated_data_final.values())
out = open(out_path, "w")
for k, v in formated_data_final.items():
for review in v:
out.write(k)
out.write("\t")
out.write(review)
out.write("\t")
for i in range(4):
neg_temp_match = choice(neg_reviews)
neg_r = choice(neg_temp_match)
while neg_r in v:
neg_temp_match = choice(neg_reviews)
neg_r = choice(neg_temp_match)
out.write(neg_r)
out.write("\t")
out.write("\n")
out.close()
def accuracy(pred_y, true_y):
"""
计算二类和多类的准确率
:param pred_y: 预测结果
:param true_y: 真实结果
:return:
"""
if isinstance(pred_y[0], list):
pred_y = [item[0] for item in pred_y]
corr = 0
for i in range(len(pred_y)):
if pred_y[i] == true_y[i]:
corr += 1
acc = corr / len(pred_y) if len(pred_y) > 0 else 0
return acc
def binary_precision(pred_y, true_y, positive=1):
"""
二类的精确率计算
:param pred_y: 预测结果
:param true_y: 真实结果
:param positive: 正例的索引表示
:return:
"""
corr = 0
pred_corr = 0
for i in range(len(pred_y)):
if pred_y[i] == positive:
pred_corr += 1
if pred_y[i] == true_y[i]:
corr += 1
prec = corr / pred_corr if pred_corr > 0 else 0
return prec
def binary_recall(pred_y, true_y, positive=1):
"""
二类的召回率
:param pred_y: 预测结果
:param true_y: 真实结果
:param positive: 正例的索引表示
:return:
"""
corr = 0
true_corr = 0
for i in range(len(pred_y)):
if true_y[i] == positive:
true_corr += 1
if pred_y[i] == true_y[i]:
corr += 1
rec = corr / true_corr if true_corr > 0 else 0
return rec
def binary_f_beta(pred_y, true_y, beta=1.0, positive=1):
"""
二类的f beta值
:param pred_y: 预测结果
:param true_y: 真实结果
:param beta: beta值
:param positive: 正例的索引表示
:return:
"""
precision = binary_precision(pred_y, true_y, positive)
recall = binary_recall(pred_y, true_y, positive)
try:
f_b = (1 + beta * beta) * precision * recall / (beta * beta * precision + recall)
except:
f_b = 0
return f_b
def get_binary_metrics(pred_y, true_y, f_beta=1.0):
"""
得到二分类的性能指标
:param pred_y:
:param true_y:
:param f_beta:
:return:
"""
acc = accuracy(pred_y, true_y)
recall = binary_recall(pred_y, true_y)
precision = binary_precision(pred_y, true_y)
f_beta = binary_f_beta(pred_y, true_y, f_beta)
return acc, recall, precision, f_beta
def mean(item: list) -> float:
"""
计算列表中元素的平均值
:param item: 列表对象
:return:
"""
res = sum(item) / len(item) if len(item) > 0 else 0
return res