bilstm_attention.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. # -*- coding: utf-8 -*-
  2. import copy
  3. import sklearn
  4. import torch
  5. import torch.nn as nn
  6. import torch.nn.functional as F
  7. from torch.autograd import Variable
  8. import data_processor
  9. import logging
  10. fileName = './model_train.log'
  11. formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(module)s: %(message)s',
  12. datefmt='%m/%d/%Y %H:%M:%S')
  13. handler = logging.FileHandler(filename=fileName, encoding="utf-8")
  14. handler.setFormatter(formatter)
  15. logging.basicConfig(level=logging.DEBUG, handlers=[handler])
  16. torch.manual_seed(123) # 保证每次运行初始化的随机数相同
  17. vocab_size = 5000 # 词表大小
  18. embedding_size = 64 # 词向量维度
  19. num_classes = 6 # 6分类 todo
  20. sentence_max_len = 64 # 单个句子的长度
  21. hidden_size = 16
  22. num_layers = 1 # 一层lstm
  23. num_directions = 2 # 双向lstm
  24. lr = 1e-3
  25. batch_size = 16 # batch_size 批尺寸
  26. epochs = 50
  27. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  28. app_names = ["航天中认自主可控众包测试练习赛"]
  29. # 航天 random_state 6
  30. # 趣享 13
  31. # ,"决赛自主可控众测web自主可控运维管理系统"
  32. bug_type = ["不正常退出", "功能不完整", "用户体验", "页面布局缺陷", "性能", "安全"]
  33. lexicon = {0: [], 1: [], 2: [], 3: [], 4: [], 5: []}
  34. word_with_attention = {}
  35. n = 5 # 选择置信度最高的前n条数据
  36. m = 3 # 选择注意力权重最高的前m个词
  37. t1 = 3
  38. t2 = 8
  39. threshold_confidence = 0.9
  40. # Bi-LSTM模型
  41. class BiLSTMModel(nn.Module):
  42. # 声明带有模型参数的层
  43. def __init__(self, embedding_size, hidden_size, num_layers, num_directions, num_classes):
  44. super(BiLSTMModel, self).__init__()
  45. self.input_size = embedding_size
  46. self.hidden_size = hidden_size
  47. self.num_layers = num_layers
  48. self.num_directions = num_directions
  49. self.lstm = nn.LSTM(embedding_size, hidden_size, num_layers=num_layers, bidirectional=(num_directions == 2))
  50. # torch.nn.Sequential 类是 torch.nn 中的一种序列容器,通过在容器中嵌套各种实现神经网络中具体功能相关的类,来完成对神经网络模型的搭建,
  51. # 最主要的是,参数会按照我们定义好的序列自动传递下去。
  52. # torch.nn.Linear 类接收的参数有三个,分别是输入特征数、输出特征数和是否使用偏置,
  53. # 设置是否使用偏置的参数是一个布尔值,默认为 True ,即使用偏置。
  54. self.attention_weights_layer = nn.Sequential(
  55. nn.Linear(hidden_size, hidden_size), # 从hidden_size到hideen_size的线性变换
  56. nn.ReLU(inplace=True) # 激活函数
  57. )
  58. self.liner = nn.Linear(hidden_size, num_classes)
  59. self.act_func = nn.Softmax(dim=1)
  60. # 定义模型的前向计算,即如何根据输入x计算返回所需要的模型输出
  61. def forward(self, x):
  62. # lstm的输入维度为 [seq_len, batch, input_size]
  63. # x [batch_size, sentence_length, embedding_size]
  64. x = x.permute(1, 0, 2) # [sentence_length, batch_size, embedding_size] ,将x进行依次转置
  65. # 由于数据集不一定是预先设置的batch_size的整数倍,所以用size(1)获取当前数据实际的batch
  66. batch_size = x.size(1)
  67. # 设置lstm最初的前项输出
  68. h_0 = torch.randn(self.num_layers * self.num_directions, batch_size, self.hidden_size).to(device)
  69. c_0 = torch.randn(self.num_layers * self.num_directions, batch_size, self.hidden_size).to(device)
  70. # out[seq_len, batch, num_directions * hidden_size]。多层lstm,out只保存最后一层每个时间步t的输出h_t
  71. # h_n, c_n [num_laye,rs * num_directions, batch, hidden_size]
  72. out, (h_n, c_n) = self.lstm(x, (h_0, c_0))
  73. # 将双向lstm的输出拆分为前向输出和后向输出
  74. (forward_out, backward_out) = torch.chunk(out, 2, dim=2)
  75. out = forward_out + backward_out # [seq_len, batch, hidden_size]
  76. out = out.permute(1, 0, 2) # [batch, seq_len, hidden_size]
  77. # 为了使用到lstm最后一个时间步时,每层lstm的表达,用h_n生成attention的权重
  78. h_n = h_n.permute(1, 0, 2) # [batch, num_layers * num_directions, hidden_size]
  79. h_n = torch.sum(h_n, dim=1) # [batch, 1, hidden_size]
  80. h_n = h_n.squeeze(dim=1) # [batch, hidden_size]
  81. # Bi-LSTM + Attention 就是在Bi-LSTM的模型上加入Attention层,在Bi-LSTM中我们会用最后一个时序的输出向量 作为特征向量,然后进行softmax分类。Attention是先计算每个时序的权重,然后将所有时序 的向量进行加权和作为特征向量,然后进行softmax分类。在实验中,加上Attention确实对结果有所提升。
  82. # https://blog.csdn.net/zwqjoy/article/details/96724702
  83. attention_w = self.attention_weights_layer(h_n) # [batch, hidden_size]
  84. attention_w = attention_w.unsqueeze(dim=1) # [batch, 1, hidden_size] [16, 1, 16]
  85. # print(attention_w)
  86. attention_context = torch.bmm(attention_w, out.transpose(1, 2)) # [batch, 1, seq_len] [16 ,1, 32]
  87. # print(attention_context)
  88. softmax_w = F.softmax(attention_context, dim=-1) # [batch, 1, seq_len],权重归一化 [16, 1, 32]
  89. # print(softmax_w) # 这个是注意力机制的权重向量
  90. x = torch.bmm(softmax_w, out) # [batch, 1, hidden_size]
  91. x = x.squeeze(dim=1) # [batch, hidden_size]
  92. x = self.liner(x)
  93. x = self.act_func(x) # [16, 6]
  94. return softmax_w, x
  95. # 将 发展集中新预测的标签数据添加到训练集中,然后再次训练分类器
  96. # 这些新伪标签数据的类别分布要平衡
  97. # 通过基础分类器和词库共同 预测 标签的类型。
  98. # 这种预测 共分为两个流程:第一个是 预测发展集的标签并把预测好的数据加到训练集中
  99. # 第二个是 当加完所有的伪标签数据后,重新训练 基础分类器,用 新的基础分类器+最全的词库去预测 测试集
  100. def develop_to_train(new_labeled_data, train_features, develop_features, train_labels, develop_labels):
  101. for key in sorted(new_labeled_data, reverse=True):
  102. feature = develop_features.pop(key)
  103. del develop_labels[key]
  104. label_index = new_labeled_data[key]
  105. label = [0] * num_classes
  106. label[label_index] = 1
  107. train_labels.append(label)
  108. train_features.append(feature)
  109. return train_features, develop_features, train_labels, develop_labels
  110. # 在发展集上重新运行基础分类器,获得一组关于发展集的关键词
  111. # 方法 是 通过基础分类器在发展集上预测出的置信度和单词的attention 为发展集收集词库
  112. def test_with_lexicon(model, develop_loader, develop_feature_origin, word2index):
  113. model.eval() # 评估模式而非训练模式,batchNorm层和dropout层等用于优化训练而添加的网络层会被关闭,使评估时不会发生偏移
  114. confidence_list = [] # 总的置信度列表
  115. category_list = [] # 总的预判种类列表
  116. attention_list = [] # 总的word权重列表
  117. for datas, labels in develop_loader:
  118. datas = datas.to(device) # 将所有最开始读取数据时的tensor变量copy一份到device所指定的GPU上去,之后的运算都在GPU上进行
  119. softmax_w, preds = model.forward(datas)
  120. softmax_w = softmax_w.squeeze(dim=1) # [16, 32]
  121. attention = softmax_w.tolist()
  122. attention_list.extend(attention)
  123. # pre_test = torch.argmax(preds, dim=1)
  124. # label_test = torch.argmax(labels, dim=1)
  125. # develop_true += torch.sum(pre_test == label_test).item()
  126. a = preds.max(dim=1)
  127. confidence = a[0].tolist() # 置信度列表
  128. category = a[1].tolist() # 预测的类别列表
  129. confidence_list.extend(confidence)
  130. category_list.extend(category)
  131. confidence_dict = dict(zip(confidence_list, list(range(len(confidence_list)))))
  132. category_dict = dict(zip(list(range(len(category_list))), category_list))
  133. attention_dict = dict(zip(list(range(len(attention_list))), attention_list))
  134. develop_true = 0
  135. develop_all = 0
  136. lexicon_num = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
  137. for i in sorted(confidence_dict, reverse=True):
  138. lexicon_key = category_dict[confidence_dict[i]]
  139. if lexicon_num[lexicon_key] <= n: # 每个类别取置信度最高的前n条数据
  140. # print(str(lexicon_key) + ":" + str(i))
  141. label = torch.argmax(develop_loader.dataset.tensors[1].data, dim=1)[confidence_dict[i]]
  142. develop_all += 1
  143. if label == lexicon_key:
  144. develop_true += 1
  145. # TODO 伪标签 与标签
  146. lexicon_num[lexicon_key] += 1
  147. lexicon_value_attention = attention_dict[confidence_dict[i]]
  148. lexicon_value_word = develop_feature_origin[confidence_dict[i]]
  149. attention2word = dict(zip(lexicon_value_attention, lexicon_value_word))
  150. word2attention = {}
  151. for j in sorted(attention2word, reverse=True):
  152. word = list(word2index.keys())[list(word2index.values()).index(attention2word[j])]
  153. if word != "<unk>" and word != "<pad>":
  154. if word in word2attention.keys():
  155. word2attention[word] += j
  156. else:
  157. word2attention[word] = j
  158. q = 0
  159. for k in sorted(word2attention.items(), key=lambda kv: (kv[1], kv[0]), reverse=True):
  160. if k[0] not in word_with_attention:
  161. word_with_attention[k[0]] = k[1]
  162. if q < m and k[1] >= word_with_attention[k[0]]: # 按关键字在剧中的attention 判定关键字类别
  163. for key, value in lexicon.items():
  164. if k[0] in lexicon[key]:
  165. lexicon[key].remove(k[0])
  166. lexicon[lexicon_key].append(k[0])
  167. q += 1
  168. print("每类选出前{}个,正确的有{}个,一共有{}个".format(n, develop_true, develop_all))
  169. new_labeled_data = {}
  170. # 此时,已经获得了这一轮的类别词库
  171. # 记录下新被贴标签的数据,记录第k个数据和它新的类别,之后在发展集中剔除它,把它加到训练集
  172. for k in range(len(confidence_list)):
  173. lexicon_value_word = develop_feature_origin[k]
  174. match_num = [0] * num_classes
  175. for value_word in lexicon_value_word:
  176. word = list(word2index.keys())[list(word2index.values()).index(value_word)]
  177. if word != "<unk>" and word != "<pad>":
  178. for l in range(num_classes):
  179. if word in lexicon.get(l):
  180. # 会不会出现同一个词在多个类别词库中出现的问题
  181. match_num[l] = match_num[l] + 1
  182. max_num = max(match_num)
  183. # print(str(match_num) + "---"+ str(confidence_list[k]))
  184. if match_num.count(max_num) != 1:
  185. continue
  186. elif max_num >= t2:
  187. # 就根据词库对应的类贴标签给这个数据
  188. new_labeled_data[k] = match_num.index(max_num)
  189. elif confidence_list[k] > threshold_confidence and t1 <= max_num < t2:
  190. new_labeled_data[k] = category_list[k]
  191. # 返回被标记的数据的行数和它的新类别
  192. return new_labeled_data
  193. def test(model, test_loader, loss_func, test_feature_origin, word2index):
  194. model.eval()
  195. loss_val = 0.0
  196. corrects = 0.0
  197. confidence_list = [] # 总的置信度列表
  198. category_list = [] # 总的预判种类列表
  199. label_list = []
  200. for datas, labels in test_loader:
  201. datas = datas.to(device)
  202. labels = labels.to(device)
  203. labels_num = labels.tolist()
  204. label_list_tmp = []
  205. for label in labels_num:
  206. sum_label = 0
  207. for i in range(len(label)):
  208. sum_label = sum_label + label[i] * i
  209. label_list_tmp.append(sum_label)
  210. softmax_w, preds = model.forward(datas)
  211. a = preds.max(dim=1)
  212. confidence = a[0].tolist() # 置信度列表
  213. category = a[1].tolist() # 预测的类别列表
  214. confidence_list.extend(confidence)
  215. category_list.extend(category)
  216. label_list.extend(label_list_tmp)
  217. """
  218. loss = loss_func(preds, labels)
  219. loss_val += loss.item() * datas.size(0)
  220. #获取预测的最大概率出现的位置
  221. preds = torch.argmax(preds, dim=1)
  222. labels = torch.argmax(labels, dim=1)
  223. corrects += torch.sum(preds == labels).item()
  224. """
  225. for k in range(len(confidence_list)):
  226. lexicon_value_word = test_feature_origin[k]
  227. match_num = [0] * num_classes
  228. for value_word in lexicon_value_word:
  229. word = list(word2index.keys())[list(word2index.values()).index(value_word)]
  230. if word != "<unk>" and word != "<pad>":
  231. for l in range(num_classes):
  232. if word in lexicon.get(l):
  233. # 会不会出现同一个词在多个类别词库中出现的问题
  234. match_num[l] = match_num[l] + 1
  235. max_num = max(match_num)
  236. if match_num.count(max_num) != 1:
  237. continue
  238. elif max_num >= t2:
  239. # 就根据词库对应的类贴标签给这个数据
  240. category_list[k] = match_num.index(max_num)
  241. test_loss = 0
  242. test_acc = 1
  243. for i in range(len(category_list)):
  244. # print("第{}个标签: category_list: {}, label_list: {}".format(i, category_list[i], label_list[i]))
  245. if category_list[i] == label_list[i]:
  246. corrects = corrects + 1
  247. test_acc = corrects / len(category_list)
  248. print("Test Loss: {}, Test Acc: {}".format(test_loss, test_acc))
  249. return test_acc
  250. def test_origin(model, test_loader, loss_func):
  251. model.eval()
  252. with torch.no_grad():
  253. loss_val = 0.0
  254. corrects = 0.0
  255. recall_all = 0
  256. f1_all = 0
  257. pre_all = 0
  258. for datas, labels in test_loader:
  259. datas = datas.to(device)
  260. labels = labels.to(device)
  261. softmax_w, preds = model.forward(datas)
  262. loss = loss_func(preds, labels)
  263. loss_val += loss.item() * datas.size(0)
  264. # 获取预测的最大概率出现的位置
  265. preds = torch.argmax(preds, dim=1)
  266. labels = torch.argmax(labels, dim=1)
  267. recall = sklearn.metrics.recall_score(labels, preds, average="macro", zero_division=0)
  268. f1 = sklearn.metrics.f1_score(labels, preds, average="macro", zero_division=0)
  269. pre = sklearn.metrics.precision_score(labels, preds, average="macro", zero_division=0)
  270. corrects += torch.sum(preds == labels).item()
  271. recall_all += recall
  272. f1_all += f1
  273. pre_all += pre
  274. test_acc = corrects / len(test_loader.dataset)
  275. test_recall = recall_all / len(test_loader.batch_sampler)
  276. test_f1 = f1_all / len(test_loader.batch_sampler)
  277. test_pre = pre_all / len(test_loader.batch_sampler)
  278. # print("Test Loss: {}, Test Acc: {}".format(test_loss, test_acc))
  279. return test_acc, test_recall, test_f1, test_pre
  280. def get_evaluation(model, test_loader):
  281. model.eval()
  282. # print(model.state_dict())
  283. with torch.no_grad():
  284. corrects = 0.0
  285. recall_all = 0
  286. f1_all = 0
  287. pre_all = 0
  288. label_all = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}
  289. test_label_all = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}
  290. for datas, labels in test_loader:
  291. datas = datas.to(device)
  292. labels = labels.to(device)
  293. softmax_w, preds = model.forward(datas)
  294. preds = torch.argmax(preds, dim=1)
  295. labels = torch.argmax(labels, dim=1)
  296. for i in range(len(preds)):
  297. category_a = preds[i].tolist() # 预测的类别列表
  298. category_b = labels[i].tolist()
  299. test_label_all[category_b + 1] += 1
  300. if category_b == category_a:
  301. label_all[category_b + 1] += 1
  302. recall = sklearn.metrics.recall_score(labels, preds, average="macro", zero_division=0)
  303. f1 = sklearn.metrics.f1_score(labels, preds, average="macro", zero_division=0)
  304. pre = sklearn.metrics.precision_score(labels, preds, average="macro", zero_division=0)
  305. corrects += torch.sum(preds == labels).item()
  306. # label_all[labels.]+=torch.sum(preds == labels).item()
  307. recall_all += recall
  308. f1_all += f1
  309. pre_all += pre
  310. test_acc = corrects / len(test_loader.dataset)
  311. test_recall = recall_all / len(test_loader.batch_sampler)
  312. test_f1 = f1_all / len(test_loader.batch_sampler)
  313. test_pre = pre_all / len(test_loader.batch_sampler)
  314. print(label_all)
  315. print(test_label_all)
  316. # print("Test Loss: {}, Test Acc: {}".format(test_loss, test_acc))
  317. return test_acc, test_recall, test_f1, test_pre
  318. def train_origin(model, train_loader, test_loader, optimizer, loss_func, epochs):
  319. # best_val_acc = 0.0
  320. best_val_acc = test_origin(model, test_loader, loss_func)[0]
  321. best_model_params = copy.deepcopy(model.state_dict())
  322. for epoch in range(epochs):
  323. model.train()
  324. loss_val = 0.0
  325. corrects = 0.0
  326. for datas, labels in train_loader:
  327. datas = datas.to(device)
  328. labels = labels.to(device)
  329. attention_w, preds = model.forward(datas) # 使用model预测数据
  330. loss = loss_func(preds, labels)
  331. optimizer.zero_grad()
  332. loss.backward()
  333. optimizer.step()
  334. loss_val += loss.item() * datas.size(0)
  335. # 获取预测的最大概率出现的位置
  336. preds = torch.argmax(preds, dim=1)
  337. labels = torch.argmax(labels, dim=1)
  338. corrects += torch.sum(preds == labels).item()
  339. train_loss = loss_val / len(train_loader.dataset)
  340. train_acc = corrects / len(train_loader.dataset)
  341. # print("Train Loss: {}, Train Acc: {}".format(train_loss, train_acc))
  342. if epoch % 2 == 0:
  343. test_acc = test_origin(model, test_loader, loss_func)[0]
  344. if best_val_acc < test_acc:
  345. print("best:", best_val_acc, " new_best:", test_acc)
  346. best_val_acc = test_acc
  347. best_model_params = copy.deepcopy(model.state_dict())
  348. model.load_state_dict(best_model_params)
  349. return model
  350. # 从给定的训练集数据中创建一个基础分类器,训练集数据很少,数据类别分布平衡
  351. # 这个基础分类器过度拟合训练集??????? todo
  352. def train(model, train_loader, optimizer, loss_func, epochs):
  353. best_val_acc = 0.0
  354. best_model_params = copy.deepcopy(model.state_dict())
  355. # epoch、batch、iteration的概念 https://www.jianshu.com/p/22c50ded4cf7?from=groupmessage
  356. for epoch in range(epochs):
  357. model.train()
  358. loss_val = 0.0
  359. corrects = 0.0
  360. for datas, labels in train_loader:
  361. datas = datas.to(device)
  362. labels = labels.to(device)
  363. # print("第{}批训练数据: labels: {}".format(epoch, labels))
  364. attention_w, preds = model.forward(datas) # 使用model预测数据
  365. loss = loss_func(preds, labels)
  366. optimizer.zero_grad()
  367. loss.backward()
  368. optimizer.step()
  369. loss_val += loss.item() * datas.size(0)
  370. # 获取预测的最大概率出现的位置
  371. preds = torch.argmax(preds, dim=1)
  372. labels = torch.argmax(labels, dim=1)
  373. corrects += torch.sum(preds == labels).item()
  374. train_loss = loss_val / len(train_loader.dataset)
  375. train_acc = corrects / len(train_loader.dataset)
  376. # print("Train Loss: {}, Train Acc: {}".format(train_loss, train_acc))
  377. if best_val_acc < train_acc:
  378. best_val_acc = train_acc
  379. best_model_params = copy.deepcopy(model.state_dict())
  380. model.load_state_dict(best_model_params)
  381. return model
  382. def main():
  383. for app_name in app_names:
  384. processor = data_processor.DataProcessor(dataset_name=app_name)
  385. train_features, develop_features, test_features, train_labels, develop_labels, test_labels, word2index = processor.get_datasets_origin(
  386. vocab_size=vocab_size, max_len=sentence_max_len)
  387. train_datasets, develop_datasets, test_datasets = processor.get_datasets(train_features, develop_features,
  388. test_features, train_labels,
  389. develop_labels, test_labels,
  390. vocab_size=vocab_size,
  391. embedding_size=embedding_size)
  392. logging.info("开始训练模型:" + app_name)
  393. # train_loader是 batch_size(16)个 数据(train_features)
  394. logging.info("pytorch 初始化")
  395. train_loader = torch.utils.data.DataLoader(train_datasets, batch_size=batch_size, shuffle=False)
  396. develop_loader = torch.utils.data.DataLoader(develop_datasets, batch_size=batch_size, shuffle=False)
  397. test_loader = torch.utils.data.DataLoader(test_datasets, batch_size=batch_size, shuffle=False)
  398. logging.info("模型初始化")
  399. model = BiLSTMModel(embedding_size, hidden_size, num_layers, num_directions, num_classes)
  400. model = model.to(device)
  401. optimizer = torch.optim.Adam(model.parameters(), lr=lr)
  402. loss_func = nn.BCELoss()
  403. # 训练基础的模型
  404. logging.info("开始训练基础分类器")
  405. # model = train(model, train_loader, optimizer, loss_func, epochs)
  406. model = train_origin(model, train_loader, test_loader, optimizer, loss_func, epochs)
  407. test_acc, test_recall, test_f1, test_pre = get_evaluation(model, test_loader)
  408. # torch.load("../classify_model/" + app_name + ".pth")
  409. # best_acc = 0
  410. # best_recall = 0
  411. # best_f1 = 0
  412. # best_pre = 0
  413. #
  414. # for i in range(20):
  415. # test_acc, test_recall, test_f1, test_pre = get_evaluation(model, test_loader)
  416. # # torch.load("../classify_model/" + app_name + ".pth")
  417. #
  418. # if test_acc > best_acc:
  419. # best_acc = test_acc
  420. # best_recall = test_recall
  421. # best_f1 = test_f1
  422. # best_pre = test_pre
  423. logging.info("初始分类器accuracy为{}".format(test_acc))
  424. logging.info("初始分类器召回率为{}".format(test_recall))
  425. logging.info("初始分类器precision为{}".format(test_pre))
  426. logging.info("初始分类器f1_score为{}".format(test_f1))
  427. i = 0
  428. while 1:
  429. i = i + 1
  430. # 从发展集中构建词库
  431. new_labeled_data = test_with_lexicon(model, develop_loader, develop_features, word2index)
  432. print("重新贴标签的数据是{}".format(new_labeled_data))
  433. print("现在的词库是{}".format(lexicon))
  434. if len(new_labeled_data) == 0:
  435. break
  436. train_features, develop_features, train_labels, develop_labels = develop_to_train(new_labeled_data,
  437. train_features,
  438. develop_features,
  439. train_labels,
  440. develop_labels)
  441. embed = nn.Embedding(vocab_size + 2, embedding_size) # https://www.jianshu.com/p/63e7acc5e890
  442. train_features_after1 = torch.LongTensor(train_features)
  443. train_features_after1 = embed(train_features_after1)
  444. train_features_after2 = Variable(train_features_after1, requires_grad=False)
  445. train_labels_after = torch.FloatTensor(train_labels)
  446. train_datasets = torch.utils.data.TensorDataset(train_features_after2, train_labels_after)
  447. train_loader = torch.utils.data.DataLoader(train_datasets, batch_size=batch_size, shuffle=False)
  448. develop_features_after1 = torch.LongTensor(develop_features)
  449. develop_features_after1 = embed(develop_features_after1)
  450. develop_features_after2 = Variable(develop_features_after1, requires_grad=False)
  451. develop_labels_after = torch.FloatTensor(develop_labels)
  452. develop_datasets = torch.utils.data.TensorDataset(develop_features_after2, develop_labels_after)
  453. develop_loader = torch.utils.data.DataLoader(develop_datasets, batch_size=batch_size, shuffle=False)
  454. logging.info("开始第{}次重训练".format(i))
  455. model = train_origin(model, train_loader, test_loader, optimizer, loss_func, epochs)
  456. model = train_origin(model, train_loader, test_loader, optimizer, loss_func, epochs)
  457. best_acc = 0
  458. best_recall = 0
  459. best_f1 = 0
  460. best_pre = 0
  461. for i in range(20):
  462. test_acc, test_recall, test_f1, test_pre = get_evaluation(model, test_loader)
  463. # torch.load("../classify_model/" + app_name + ".pth")
  464. if test_acc > best_acc:
  465. best_acc = test_acc
  466. best_recall = test_recall
  467. best_f1 = test_f1
  468. best_pre = test_pre
  469. logging.info("训练完成,测试集Accuracy为{}".format(best_acc))
  470. logging.info("训练完成,测试集召回率为{}".format(best_recall))
  471. logging.info("训练完成,测试集Precision为{}".format(best_pre))
  472. logging.info("训练完成,测试集f1_score为{}".format(best_f1))
  473. torch.save(model, "../classify_model/" + app_name + ".pth")
  474. if __name__ == '__main__':
  475. main()