bilstm_attention.py 22 KB

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