-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathutils.py
More file actions
186 lines (166 loc) · 6 KB
/
utils.py
File metadata and controls
186 lines (166 loc) · 6 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
# coding: utf-8
# Author: Miracle Yoo
import codecs
import os
import datetime
import numpy as np
import pandas as pd
import pickle
import warnings
warnings.filterwarnings("ignore")
def folder_init():
"""
Initialize folders required
"""
if not os.path.exists('source'): os.mkdir('source')
if not os.path.exists('source/log'): os.mkdir('source/log')
if not os.path.exists('source/trained_net'): os.mkdir('source/trained_net')
if not os.path.exists('source/data'): os.mkdir('source/data')
if not os.path.exists('source/nohup'): os.mkdir('source/nohup')
if not os.path.exists('source/summaries'): os.mkdir('source/summaries')
def change_dataset_format(filename):
"""
Change the csv dataset file which fanyu using to stadard || dataset file.
:param filename: dataset filename
"""
oridf = pd.read_csv(filename)
data = []
for line in oridf.iterrows():
if type(line[1]['query']) != float and type(line[1]['main_question']) != float:
data.append(line[1]['query'] + '||' + line[1]['main_question'] + '\n')
with open(os.path.splitext(filename)[0] + '.txt', 'w+') as f:
f.writelines(data)
def multi_dataset_merge(*filenames):
"""
:param filenames: multiple dataset path
:return: merged dataset list
"""
data = []
for filename in filenames:
with open(filename) as f:
data.extend(f.readlines())
return data
def get_equal_pairs(title):
pairs = []
with codecs.open('./reference/equal_pairs.txt', 'r', encoding='utf-8') as f:
raw_pairs = f.readlines()
for line in raw_pairs:
pairs.append([title.index(x.strip('\n')) for x in line.split('||') if x.strip('\n') in title])
return pairs
def use_pairs_mapping(predicts, labels, equal_pairs):
"""
:param predicts:
:param labels:
:param equal_pairs:
:return:
"""
correct_num = 0
# 如果输入的predict是一个[batch_size,top_n_num]的矩阵,
# 用于预测top-n准确率
if type(predicts[0]) != int:
for i in range(len(labels)):
if labels[i] in predicts[i]:
correct_num += 1
else:
for j in range(len(equal_pairs)):
if labels[i] in equal_pairs[j]:
for pred in predicts[i]:
if pred in equal_pairs[j]:
correct_num += 1
break
# 如果输入的predict是一个[batch_size]的list,
# 用于预测top-1准确率
else:
for i in range(len(labels)):
if labels[i] == predicts[i]:
correct_num += 1
else:
for j in range(len(equal_pairs)):
if labels[i] in equal_pairs[j] and predicts[i] in equal_pairs[j]:
correct_num += 1
return correct_num
def get_topn_acc(outputs, labels, top_num=3):
acc = [0] * top_num
for i in range(top_num):
predicts = np.array(outputs.sort(descending=True, dim=1)[1])[:, :top_num]
for j in range(len(labels)):
if labels[j] in predicts:
acc[i] += 1
acc = [x / len(labels) for x in acc]
return acc
def write_summary(net, opt, summary_info):
print(summary_info['best_top_accs'])
current_time = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
prefix = './source/summaries/' + net.model_name
if not os.path.exists(prefix): os.mkdir(prefix)
sum_path = prefix + '/MiracleYoo_' + current_time + '_' + net.model_name + '_Model_Record_Form.md'
with codecs.open('./config.py', 'r', encoding='utf-8') as f:
raw_data = f.readlines()
configs = ''
for line in raw_data:
if line.strip().startswith('self.'):
configs += line.strip().lstrip('self.') + '\n'
content = '''
# Model Testing Record Form
| Item Name | Information |
| --------- | ----------- |
| Model Name | %s |
| Tester's Name | Miracle Yoo |
| Author's Nmae | Miracle Yoo |
| Test Time | %s |
| Test Position | %s |
| Training Epoch | %d |
| Highest Test Acc | %.4f |
| Loss of best Test Acc | %.4f |
| Top2Acc of best Test Acc|%.4f |
| Top3Acc of best Test Acc|%.4f |
| Last epoch test acc | %.4f |
| Last epoch test loss | %.4f |
| Last epoch train acc | %.4f |
| Last epoch train loss | %.4f |
| Train Dataset Path | %s |
| Test Dataset Path | %s |
| Class Number | %d |
| Framwork | Pytorch |
| Basic Method | Classify |
| Input Type | Char |
| Criterion | CrossEntropy|
| Optimizer | %s |
| Learning Rate | %.4f |
| Embedding dimension | %d |
| Data Homogenization | True |
| Pretreatment|Remove punctuation|
| Other Major Param | |
| Other Operation | |
## Configs
```
%s
```
## Net Structure
```
%s
```
''' % (
net.model_name,
current_time,
opt.TEST_POSITION,
summary_info['total_epoch'],
summary_info['best_acc'],
summary_info['best_acc_loss'],
summary_info['best_top_accs'][1],
summary_info['best_top_accs'][2],
summary_info['ave_test_acc'],
summary_info['ave_test_loss'],
summary_info['ave_train_acc'],
summary_info['ave_train_loss'],
os.path.basename(opt.TRAIN_DATASET_PATH),
os.path.basename(opt.TEST_DATASET_PATH),
opt.NUM_CLASSES,
opt.OPTIMIZER,
opt.LEARNING_RATE,
opt.EMBEDDING_DIM,
configs.strip('\n'),
str(net)
)
with codecs.open(sum_path, 'w+', encoding='utf-8') as f:
f.writelines(content)