main.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. import os
  2. import sys
  3. import json
  4. import optuna
  5. from sklearn.linear_model import LogisticRegression
  6. sys.path.append(os.getcwd())
  7. import numpy as np
  8. import pandas as pd
  9. import lightgbm as lgb
  10. from sklearn.preprocessing import LabelEncoder
  11. from sklearn.metrics import accuracy_score
  12. class LightGBM(object):
  13. """
  14. LightGBM model for classification
  15. """
  16. def __init__(self, flag, dt):
  17. self.label_encoder = LabelEncoder()
  18. self.my_c = [
  19. "uid",
  20. "type",
  21. "channel",
  22. "fans",
  23. "view_count_user_30days",
  24. "share_count_user_30days",
  25. "return_count_user_30days",
  26. "rov_user",
  27. "str_user",
  28. "out_user_id",
  29. "mode",
  30. "out_play_cnt",
  31. "out_like_cnt",
  32. "out_share_cnt",
  33. "out_collection_cnt",
  34. "tag1",
  35. "tag2",
  36. "tag3"
  37. ]
  38. self.str_columns = ["uid", "type", "channel", "mode", "out_user_id", "tag1", "tag2", "tag3"]
  39. self.float_columns = [
  40. "fans",
  41. "view_count_user_30days",
  42. "share_count_user_30days",
  43. "return_count_user_30days",
  44. "rov_user",
  45. "str_user",
  46. "out_play_cnt",
  47. "out_like_cnt",
  48. "out_share_cnt",
  49. "out_collection_cnt",
  50. ]
  51. self.split_c = 0.999
  52. self.yc = 0.8
  53. self.model = "lightgbm_0326.bin"
  54. self.flag = flag
  55. self.dt = dt
  56. def bays_params(self, trial):
  57. """
  58. Bayesian parameters for
  59. :return: best parameters
  60. """
  61. # 定义搜索空间
  62. param = {
  63. 'objective': 'binary',
  64. 'metric': 'binary_logloss',
  65. 'verbosity': -1,
  66. 'boosting_type': 'gbdt',
  67. 'num_leaves': trial.suggest_int('num_leaves', 20, 40),
  68. 'learning_rate': trial.suggest_loguniform('learning_rate', 1e-8, 1.0),
  69. 'feature_fraction': trial.suggest_uniform('feature_fraction', 0.4, 1.0),
  70. 'bagging_fraction': trial.suggest_uniform('bagging_fraction', 0.4, 1.0),
  71. 'bagging_freq': trial.suggest_int('bagging_freq', 1, 7),
  72. 'min_child_samples': trial.suggest_int('min_child_samples', 5, 100),
  73. "num_threads": 16, # 线程数量
  74. }
  75. X_train, X_test = self.generate_x_data()
  76. Y_train, Y_test = self.generate_y_data()
  77. train_data = lgb.Dataset(
  78. X_train,
  79. label=Y_train,
  80. categorical_feature=["uid", "type", "channel", "mode", "out_user_id", "tag1", "tag2", "tag3"],
  81. )
  82. test_data = lgb.Dataset(X_test, label=Y_test, reference=train_data)
  83. gbm = lgb.train(param, train_data, num_boost_round=100, valid_sets=[test_data])
  84. preds = gbm.predict(X_test)
  85. pred_labels = np.rint(preds)
  86. accuracy = accuracy_score(Y_test, pred_labels)
  87. return accuracy
  88. def generate_x_data(self):
  89. """
  90. Generate data for feature engineering
  91. :return:
  92. """
  93. with open("data/produce_data/x_data_total_return_{}_{}.json".format(self.flag, self.dt)) as f1:
  94. x_list = json.loads(f1.read())
  95. index_t = int(len(x_list) * self.split_c)
  96. X_train = pd.DataFrame(x_list[:index_t], columns=self.my_c)
  97. for key in self.str_columns:
  98. X_train[key] = self.label_encoder.fit_transform(X_train[key])
  99. for key in self.float_columns:
  100. X_train[key] = pd.to_numeric(X_train[key], errors="coerce")
  101. X_test = pd.DataFrame(x_list[index_t:], columns=self.my_c)
  102. for key in self.str_columns:
  103. X_test[key] = self.label_encoder.fit_transform(X_test[key])
  104. for key in self.float_columns:
  105. X_test[key] = pd.to_numeric(X_test[key], errors="coerce")
  106. return X_train, X_test
  107. def generate_y_data(self):
  108. """
  109. Generate data for label
  110. :return:
  111. """
  112. with open("data/produce_data/y_data_total_return_{}_{}.json".format(self.flag, self.dt)) as f2:
  113. y_list = json.loads(f2.read())
  114. index_t = int(len(y_list) * self.split_c)
  115. temp = sorted(y_list)
  116. yuzhi = temp[int(len(temp) * self.yc) - 1]
  117. print("阈值是: {}".format(yuzhi))
  118. y__list = [0 if i <= yuzhi else 1 for i in y_list]
  119. y_train = np.array(y__list[:index_t])
  120. y_test = np.array(y__list[index_t:])
  121. return y_train, y_test
  122. def train_model(self):
  123. """
  124. Load dataset
  125. :return:
  126. """
  127. X_train, X_test = self.generate_x_data()
  128. Y_train, Y_test = self.generate_y_data()
  129. train_data = lgb.Dataset(
  130. X_train,
  131. label=Y_train,
  132. categorical_feature=["uid", "type", "channel", "mode", "out_user_id", "tag1", "tag2", "tag3"],
  133. )
  134. test_data = lgb.Dataset(X_test, label=Y_test, reference=train_data)
  135. params = {
  136. "objective": "binary", # 指定二分类任务
  137. "metric": "binary_logloss", # 评估指标为二分类的log损失
  138. "num_leaves": 36, # 叶子节点数
  139. "learning_rate": 0.08479152931388902, # 学习率
  140. "bagging_fraction": 0.6588121592044218, # 建树的样本采样比例
  141. "feature_fraction": 0.4572757903437793, # 建树的特征选择比例
  142. "bagging_freq": 2, # k 意味着每 k 次迭代执行bagging
  143. "num_threads": 16, # 线程数量
  144. "mini_child_samples": 71
  145. }
  146. # 训练模型
  147. num_round = 100
  148. print("开始训练......")
  149. bst = lgb.train(params, train_data, num_round, valid_sets=[test_data])
  150. bst.save_model(self.model)
  151. print("模型训练完成✅")
  152. def evaluate_model(self):
  153. """
  154. 评估模型性能
  155. :return:
  156. """
  157. fw = open("summary_tag_03{}.txt".format(self.dt), "a+", encoding="utf-8")
  158. # 测试数据
  159. with open("data/produce_data/x_data_total_return_predict_{}.json".format(self.dt)) as f1:
  160. x_list = json.loads(f1.read())
  161. # 测试 label
  162. with open("data/produce_data/y_data_total_return_predict_{}.json".format(self.dt)) as f2:
  163. Y_test = json.loads(f2.read())
  164. Y_test = [0 if i <= 27 else 1 for i in Y_test]
  165. X_test = pd.DataFrame(x_list, columns=self.my_c)
  166. for key in self.str_columns:
  167. X_test[key] = self.label_encoder.fit_transform(X_test[key])
  168. for key in self.float_columns:
  169. X_test[key] = pd.to_numeric(X_test[key], errors="coerce")
  170. bst = lgb.Booster(model_file=self.model)
  171. y_pred = bst.predict(X_test, num_iteration=bst.best_iteration)
  172. temp = sorted(list(y_pred))
  173. yuzhi = temp[int(len(temp) * 0.7) - 1]
  174. y_pred_binary = [0 if i <= yuzhi else 1 for i in list(y_pred)]
  175. # 转换为二进制输出
  176. score_list = []
  177. for index, item in enumerate(list(y_pred)):
  178. real_label = Y_test[index]
  179. score = item
  180. prid_label = y_pred_binary[index]
  181. print(real_label, "\t", prid_label, "\t", score)
  182. fw.write("{}\t{}\t{}\n".format(real_label, prid_label, score))
  183. score_list.append(score)
  184. print("预测样本总量: {}".format(len(score_list)))
  185. data_series = pd.Series(score_list)
  186. print("统计 score 信息")
  187. print(data_series.describe())
  188. # 评估模型
  189. accuracy = accuracy_score(Y_test, y_pred_binary)
  190. print(f"Accuracy: {accuracy}")
  191. fw.close()
  192. def feature_importance(self):
  193. """
  194. Get the importance of each feature
  195. :return:
  196. """
  197. lgb_model = lgb.Booster(model_file=self.model)
  198. importance = lgb_model.feature_importance(importance_type='split')
  199. feature_name = lgb_model.feature_name()
  200. feature_importance = sorted(zip(feature_name, importance), key=lambda x: x[1], reverse=True)
  201. # 打印特征重要性
  202. for name, imp in feature_importance:
  203. print(name, imp)
  204. if __name__ == "__main__":
  205. i = int(input("输入 1 训练, 输入 2 预测:\n"))
  206. if i == 1:
  207. f = "train"
  208. dt = "whole"
  209. L = LightGBM(flag=f, dt=dt)
  210. L.train_model()
  211. elif i == 2:
  212. f = "predict"
  213. dt = int(input("输入日期, 16-21:\n"))
  214. L = LightGBM(flag=f, dt=dt)
  215. L.evaluate_model()
  216. # study = optuna.create_study(direction='maximize')
  217. # study.optimize(L.bays_params, n_trials=100)
  218. # print('Number of finished trials:', len(study.trials))
  219. # print('Best trial:', study.best_trial.params)
  220. # L.train_model()
  221. # L.evaluate_model()
  222. # L.feature_importance()