main_spider.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. """
  2. 针对爬虫类型数据单独训练模型
  3. """
  4. import os
  5. import sys
  6. import json
  7. import optuna
  8. import numpy as np
  9. from sklearn.preprocessing import LabelEncoder
  10. sys.path.append(os.getcwd())
  11. import pandas as pd
  12. import lightgbm as lgb
  13. from scipy.stats import randint as sp_randint
  14. from scipy.stats import uniform as sp_uniform
  15. from sklearn.model_selection import RandomizedSearchCV, train_test_split
  16. from sklearn.metrics import roc_auc_score, accuracy_score
  17. class LightGBM(object):
  18. """
  19. LightGBM model for classification
  20. """
  21. def __init__(self, flag, dt):
  22. self.label_encoder = LabelEncoder()
  23. self.my_c = [
  24. "channel",
  25. "out_user_id",
  26. "mode",
  27. "out_play_cnt",
  28. "out_like_cnt",
  29. "out_share_cnt",
  30. "lop",
  31. "duration",
  32. "tag1",
  33. "tag2",
  34. "tag3"
  35. ]
  36. self.str_columns = ["channel", "mode", "out_user_id", "tag1", "tag2", "tag3"]
  37. self.float_columns = [
  38. "out_play_cnt",
  39. "out_like_cnt",
  40. "out_share_cnt",
  41. "lop",
  42. "duration"
  43. ]
  44. self.split_c = 0.7
  45. self.yc = 0.8
  46. self.model = "models/lightgbm_0401_spider.bin"
  47. self.flag = flag
  48. self.dt = dt
  49. def read_data(self, path):
  50. """
  51. Read data from local
  52. :return:
  53. """
  54. df = pd.read_json(path)
  55. df = df.dropna(subset=['label'])
  56. labels = df['label']
  57. temp = sorted(labels)
  58. yc = temp[int(len(temp) * 0.7)]
  59. print("阈值", yc)
  60. labels = [0 if i < yc else 1 for i in labels]
  61. features = df.drop("label", axis=1)
  62. for key in self.float_columns:
  63. features[key] = pd.to_numeric(features[key], errors="coerce")
  64. for key in self.str_columns:
  65. features[key] = self.label_encoder.fit_transform(features[key])
  66. return features, labels
  67. def best_params(self):
  68. path = "data/train_data/spider_data_240401.json"
  69. X, y = self.read_data(path)
  70. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  71. lgbm = lgb.LGBMClassifier(objective='binary')
  72. # 设置搜索的参数范围
  73. param_dist = {
  74. 'num_leaves': sp_randint(20, 40),
  75. 'learning_rate': sp_uniform(0.001, 0.1),
  76. 'feature_fraction': sp_uniform(0.5, 0.9),
  77. 'bagging_fraction': sp_uniform(0.5, 0.9),
  78. 'bagging_freq': sp_randint(1, 10),
  79. 'min_child_samples': sp_randint(5, 100),
  80. }
  81. # 定义 RandomizedSearchCV
  82. rsearch = RandomizedSearchCV(
  83. estimator=lgbm,
  84. param_distributions=param_dist,
  85. n_iter=100,
  86. cv=3,
  87. scoring='roc_auc',
  88. random_state=42, verbose=2
  89. )
  90. # 开始搜索
  91. rsearch.fit(X_train, y_train)
  92. # 打印最佳参数和对应的AUC得分
  93. print("Best parameters found: ", rsearch.best_params_)
  94. print("Best AUC found: ", rsearch.best_score_)
  95. # 使用最佳参数在测试集上的表现
  96. best_model = rsearch.best_estimator_
  97. y_pred = best_model.predict_proba(X_test)[:, 1]
  98. auc = roc_auc_score(y_test, y_pred)
  99. print("AUC on test set: ", auc)
  100. def train_model(self):
  101. """
  102. Load dataset
  103. :return:
  104. """
  105. path = "data/train_data/spider_data_240401.json"
  106. x, y = self.read_data(path)
  107. train_size = int(len(x) * self.split_c)
  108. X_train, X_test = x[:train_size], x[train_size:]
  109. Y_train, Y_test = y[:train_size], y[train_size:]
  110. train_data = lgb.Dataset(
  111. X_train,
  112. label=Y_train,
  113. categorical_feature=["channel", "mode", "out_user_id", "tag1", "tag2", "tag3"],
  114. )
  115. test_data = lgb.Dataset(X_test, label=Y_test, reference=train_data)
  116. params = {
  117. 'bagging_fraction': 0.7938866919252519,
  118. 'bagging_freq': 7,
  119. 'feature_fraction': 0.9687508340232414,
  120. 'learning_rate': 0.09711720243493492,
  121. 'min_child_samples': 89,
  122. 'num_leaves': 35,
  123. 'num_threads': 16
  124. }
  125. # 训练模型
  126. num_round = 100
  127. print("开始训练......")
  128. bst = lgb.train(params, train_data, num_round, valid_sets=[test_data])
  129. bst.save_model(self.model)
  130. print("模型训练完成✅")
  131. def evaluate_model(self):
  132. """
  133. 评估模型性能
  134. :return:
  135. """
  136. fw = open("result/summary_{}.txt".format(dt), "a+", encoding="utf-8")
  137. path = 'data/predict_data/predict_{}.json'.format(dt)
  138. x, y = self.read_data(path)
  139. bst = lgb.Booster(model_file=self.model)
  140. y_pred = bst.predict(x, num_iteration=bst.best_iteration)
  141. temp = sorted(list(y_pred))
  142. yuzhi = temp[int(len(temp) * 0.7) - 1]
  143. y_pred_binary = [0 if i <= yuzhi else 1 for i in list(y_pred)]
  144. # 转换为二进制输出
  145. score_list = []
  146. for index, item in enumerate(list(y_pred)):
  147. real_label = y[index]
  148. score = item
  149. prid_label = y_pred_binary[index]
  150. print(real_label, "\t", prid_label, "\t", score)
  151. fw.write("{}\t{}\t{}\n".format(real_label, prid_label, score))
  152. score_list.append(score)
  153. print("预测样本总量: {}".format(len(score_list)))
  154. data_series = pd.Series(score_list)
  155. print("统计 score 信息")
  156. print(data_series.describe())
  157. # 评估模型
  158. accuracy = accuracy_score(y, y_pred_binary)
  159. print(f"Accuracy: {accuracy}")
  160. fw.close()
  161. def feature_importance(self):
  162. """
  163. Get the importance of each feature
  164. :return:
  165. """
  166. lgb_model = lgb.Booster(model_file=self.model)
  167. importance = lgb_model.feature_importance(importance_type='split')
  168. feature_name = lgb_model.feature_name()
  169. feature_importance = sorted(zip(feature_name, importance), key=lambda x: x[1], reverse=True)
  170. # 打印特征重要性
  171. for name, imp in feature_importance:
  172. print(name, imp)
  173. if __name__ == "__main__":
  174. i = int(input("输入 1 训练, 输入 2 预测:\n"))
  175. if i == 1:
  176. f = "train"
  177. dt = "whole"
  178. L = LightGBM(flag=f, dt=dt)
  179. L.train_model()
  180. elif i == 2:
  181. f = "predict"
  182. dt = int(input("输入日期, 20240316-21:\n"))
  183. L = LightGBM(flag=f, dt=dt)
  184. L.evaluate_model()
  185. L.feature_importance()
  186. elif i == 3:
  187. L = LightGBM("train", "whole")
  188. L.best_params()