train_utils.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. import lightgbm as lgb
  2. import numpy as np
  3. import pandas as pd
  4. from sklearn.preprocessing import MinMaxScaler, StandardScaler, PolynomialFeatures
  5. from sklearn.feature_selection import SelectKBest, mutual_info_regression, f_regression, SelectFromModel
  6. from sklearn.decomposition import PCA
  7. from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
  8. from sklearn.neural_network import MLPRegressor
  9. from sklearn.pipeline import Pipeline
  10. from sklearn.linear_model import LinearRegression, Ridge, RidgeCV
  11. from sklearn.svm import SVR
  12. from config.conmmon_config import RANDOM_STATE
  13. def feature_manipulation_method(manip_method: str):
  14. if manip_method == 'polynomial':
  15. return PolynomialFeatures(degree=2, interaction_only=True, include_bias=False, order='C')
  16. else:
  17. raise ValueError(f"Invalid feature manipulation method: {manip_method}")
  18. def normalize(normalization_method: str):
  19. if normalization_method == 'standard':
  20. return StandardScaler()
  21. elif normalization_method == 'minmax':
  22. return MinMaxScaler()
  23. else:
  24. raise ValueError(f"Invalid normalization method: {normalization_method}")
  25. def feature_selection(feature_selection_method: str, top_features: int):
  26. if feature_selection_method == 'mutual_info_regression':
  27. return SelectKBest(mutual_info_regression, k=top_features)
  28. elif feature_selection_method == 'f_regression':
  29. return SelectKBest(f_regression, k=top_features)
  30. elif feature_selection_method == 'pca':
  31. return PCA(n_components=top_features, random_state=RANDOM_STATE)
  32. elif feature_selection_method == 'model_rf':
  33. rf = RandomForestRegressor(n_estimators=50, random_state=RANDOM_STATE)
  34. # selector = SelectFromModel(rf, max_features=top_features, threshold=-np.inf) # threshold='median',
  35. selector = SelectFromModel(rf, threshold='median')
  36. return selector
  37. else:
  38. raise ValueError(f"Invalid feature selection method: {feature_selection_method}")
  39. def get_model(model_name: str):
  40. if model_name.startswith('random_forest'):
  41. return RandomForestRegressor(random_state=RANDOM_STATE)
  42. elif model_name.startswith('gbm'):
  43. return GradientBoostingRegressor(random_state=RANDOM_STATE)
  44. elif model_name.startswith('lightgbm'):
  45. return lgb.LGBMRegressor(random_state=RANDOM_STATE, deterministic=True, objective='regression')
  46. elif model_name.startswith('mlp'):
  47. return MLPRegressor(random_state=RANDOM_STATE)
  48. elif model_name.startswith('LR'):
  49. return LinearRegression(fit_intercept=False)
  50. elif model_name.startswith('Ridge'):
  51. return Ridge(random_state=RANDOM_STATE)
  52. elif model_name.startswith('RidgeCV'):
  53. return RidgeCV()
  54. elif model_name.startswith('svm'):
  55. return SVR()
  56. else:
  57. raise ValueError(f"Invalid model name: {model_name}")
  58. def get_model_params(model_name: str, para_dict: dict):
  59. if model_name.startswith('lightgbm'):
  60. model = lgb.LGBMRegressor(
  61. num_leaves=para_dict['model__num_leaves'],
  62. max_depth=para_dict['model__max_depth'],
  63. learning_rate=para_dict['model__learning_rate'],
  64. n_estimators=para_dict['model__n_estimators'],
  65. min_child_samples=para_dict['model__min_child_samples'],
  66. min_child_weight=para_dict['model__min_child_weight'],
  67. reg_alpha=para_dict['model__lambda_l1'],
  68. reg_lambda=para_dict['model__lambda_l2'],
  69. colsample_bytree=para_dict['model__feature_fraction'],
  70. subsample=para_dict['model__bagging_fraction'],
  71. random_state=RANDOM_STATE,
  72. deterministic=True,
  73. objective='regression')
  74. return model
  75. elif model_name.startswith('mlp'):
  76. model = MLPRegressor(
  77. hidden_layer_sizes=para_dict['model__hidden_layer_sizes'],
  78. learning_rate=para_dict['model__learning_rate'],
  79. max_iter=para_dict['model__max_iter'],
  80. solver=para_dict['model__solver'],
  81. alpha=para_dict['model__alpha'],
  82. activation=para_dict['model__activation'],
  83. random_state=RANDOM_STATE)
  84. return model
  85. elif model_name.startswith('gbm'):
  86. model = GradientBoostingRegressor(
  87. n_estimators=para_dict['model__n_estimators'],
  88. learning_rate=para_dict['model__learning_rate'],
  89. max_depth=para_dict['model__max_depth'],
  90. max_leaf_nodes=para_dict['model__max_leaf_nodes'],
  91. subsample=para_dict['model__subsample'],
  92. min_samples_split=para_dict['model__min_samples_split'],
  93. min_samples_leaf=para_dict['model__min_samples_leaf'],
  94. max_features=para_dict['model__max_features'],
  95. loss=para_dict['model__loss'],
  96. alpha=para_dict['model__alpha'],# only useful for loss=huber
  97. random_state=RANDOM_STATE
  98. )
  99. return model
  100. elif model_name.startswith('random_forest'):
  101. model = RandomForestRegressor(
  102. n_estimators=para_dict['model__n_estimators'],
  103. max_depth=para_dict['model__max_depth'],
  104. min_samples_split=para_dict['model__min_samples_split'],
  105. min_samples_leaf=para_dict['model__min_samples_leaf'],
  106. max_features=para_dict['model__max_features'],
  107. criterion=para_dict['model__criterion'],
  108. random_state=RANDOM_STATE
  109. )
  110. return model
  111. else:
  112. raise ValueError(f"Invalid model name: {model_name}")
  113. def get_lgb_features_from_pipeline(pipeline: Pipeline):
  114. all_steps = pipeline.steps
  115. for name, model in all_steps:
  116. if name == 'scaler':
  117. return model.feature_names_in_
  118. else:
  119. print('failed to get feature names from pipeline')
  120. return None
  121. def get_lgb_feature_importance_from_pipeline(pipeline: Pipeline, feature_names=None):
  122. all_steps = pipeline.steps
  123. if feature_names is None:
  124. feature_names = get_lgb_features_from_pipeline(pipeline)
  125. for name, model in all_steps:
  126. if name == 'selector':
  127. feature_scores = model.scores_
  128. break
  129. select_k = model.k
  130. ordered_index = np.argsort(feature_scores)
  131. select_index = ordered_index[::-1][:select_k]
  132. select_features = [feature_names[i] for i in sorted(select_index)]
  133. for name, model in all_steps:
  134. if name == 'model':
  135. f_values = model.feature_importances_
  136. break
  137. f_df = pd.DataFrame({'features': select_features, 'importance': f_values})
  138. f_df = f_df.sort_values(by='importance', ascending=False)
  139. f_df.reset_index(drop=True, inplace=True)
  140. return f_df