main_userupload.py 7.1 KB

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