ad_xgboost_train.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import pandas as pd
  2. import datetime
  3. from sklearn.model_selection import train_test_split
  4. from xgboost.sklearn import XGBClassifier
  5. from sklearn import metrics
  6. now_date = datetime.datetime.today()
  7. dt = datetime.datetime.strftime(now_date, '%Y%m%d')
  8. # 1. 读取数据
  9. data = pd.read_csv(f'./data/train_test_data/train_test_{dt}.csv')
  10. print(data.shape)
  11. # 2. 划分x和y
  12. data_columns = data.columns.values.tolist()
  13. x = data[data_columns[:-1]]
  14. y = data[data_columns[-1]]
  15. print(f"x_shape: {x.shape}, y_shape: {y.shape}")
  16. # 3. 训练集和测试集分割
  17. x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state=1)
  18. print(f"x_train_shape: {x_train.shape}")
  19. print(f"x_test_shape: {x_test.shape}")
  20. # 4. 模型训练
  21. xgb_model = XGBClassifier(
  22. objective='binary:logistic',
  23. learning_rate=0.3,
  24. max_depth=10,
  25. eval_metric=['error', 'logloss', 'auc']
  26. )
  27. xgb_model.fit(x_train, y_train, eval_set=[(x_train, y_train), (x_test, y_test)])
  28. # 5. 模型保存
  29. xgb_model.save_model('./data/ad_xgb.model')
  30. # 6. 测试集预测
  31. y_test_pre = xgb_model.predict(x_test)
  32. test_df = x_test.copy()
  33. test_df['y'] = y_test
  34. test_df['y_pre'] = y_test_pre
  35. test_df.to_csv('./data/test_pre.csv', index=False)
  36. # 7. 模型效果验证
  37. test_accuracy = metrics.accuracy_score(y_test, y_test_pre)
  38. print("Test Accuracy: %.2f%%" % (test_accuracy * 100.0))
  39. test_auc = metrics.roc_auc_score(y_test, y_test_pre)
  40. print("auc: %.2f%%" % (test_auc * 100.0))