main_spider.py 7.6 KB

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