ad_xgboost_train.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import pandas as pd
  2. import datetime
  3. import time
  4. from sklearn.model_selection import train_test_split
  5. from xgboost.sklearn import XGBClassifier
  6. from sklearn import metrics
  7. def xgboost_train():
  8. now_date = datetime.datetime.today()
  9. dt = datetime.datetime.strftime(now_date, '%Y%m%d')
  10. # 1. 读取数据
  11. # data = pd.read_csv(f'./data/train_test_data/train_test_{dt}.csv')
  12. # print(data.shape)
  13. train_data = pd.read_csv(f'./data/train_test_data/train_{dt}.csv')
  14. print(train_data.shape)
  15. test_data = pd.read_csv(f'./data/train_test_data/test_{dt}.csv')
  16. print(test_data.shape)
  17. # 2. 划分x和y
  18. # data_columns = data.columns.values.tolist()
  19. # x = data[data_columns[:-1]]
  20. # y = data[data_columns[-1]]
  21. # print(f"x_shape: {x.shape}, y_shape: {y.shape}")
  22. data_columns = train_data.columns.values.tolist()
  23. x_train = train_data[data_columns[:-1]]
  24. y_train = train_data[data_columns[-1]]
  25. x_test = test_data[data_columns[:-1]]
  26. y_test = test_data[data_columns[-1]]
  27. # 3. 训练集和测试集分割
  28. # x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=1)
  29. print(f"x_train_shape: {x_train.shape}")
  30. print(f"x_test_shape: {x_test.shape}")
  31. # 4. 模型训练
  32. xgb_model = XGBClassifier(
  33. objective='binary:logistic',
  34. learning_rate=0.05,
  35. max_depth=9,
  36. min_child_weight=8,
  37. n_estimators=450,
  38. eval_metric=['error', 'auc']
  39. )
  40. xgb_model.fit(x_train, y_train, eval_set=[(x_train, y_train), (x_test, y_test)])
  41. # 5. 模型保存
  42. xgb_model.save_model('./data/ad_xgb.model')
  43. # 6. 测试集预测
  44. y_test_pre = xgb_model.predict(x_test)
  45. # test_df = x_test.copy()
  46. # test_df['y'] = y_test
  47. # test_df['y_pre'] = y_test_pre
  48. # test_df.to_csv('./data/test_pre.csv', index=False)
  49. # 7. 模型效果验证
  50. test_accuracy = metrics.accuracy_score(y_test, y_test_pre)
  51. print("Test Accuracy: %.2f%%" % (test_accuracy * 100.0))
  52. test_auc = metrics.roc_auc_score(y_test, y_test_pre)
  53. print("auc: %.2f%%" % (test_auc * 100.0))
  54. test_recall = metrics.recall_score(y_test, y_test_pre)
  55. print("recall:%.2f%%"%(test_recall*100.0))
  56. test_f1 = metrics.f1_score(y_test, y_test_pre)
  57. print("f1:%.2f%%"%(test_f1*100.0))
  58. test_precision = metrics.precision_score(y_test, y_test_pre)
  59. print("precision:%.2f%%"%(test_precision*100.0))
  60. if __name__ == '__main__':
  61. st_time = time.time()
  62. xgboost_train()
  63. print(f"{time.time() - st_time}s")