Advertisement
gagarin_1982

Untitled

Dec 4th, 2024
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.26 KB | None | 0 0
  1. # создаём списки с названиями входящих признаков для модели
  2.  
  3. # порядковые категориальные
  4. ord_columns = [
  5.  
  6. 'last_action_1',
  7. 'last_action_2',
  8. 'last_action_3',
  9. ]
  10.  
  11. # количественные
  12. num_columns = [
  13.  
  14. 'mean_time',
  15. 'quantity',
  16. 'rev',
  17. 'av_bill',
  18.  
  19. 'days_after_purch_1',
  20. 'days_after_purch_2',
  21. 'days_after_purch_3',
  22.  
  23. 'last_purch_1_cat_level_1',
  24. 'last_purch_1_cat_level_2',
  25. 'last_purch_1_cat_level_3',
  26. 'last_purch_1_cat_level_4',
  27.  
  28. 'last_purch_2_cat_level_1',
  29. 'last_purch_2_cat_level_2',
  30. 'last_purch_2_cat_level_3',
  31. 'last_purch_2_cat_level_4',
  32.  
  33. 'last_purch_3_cat_level_1',
  34. 'last_purch_3_cat_level_2',
  35. 'last_purch_3_cat_level_3',
  36. 'last_purch_3_cat_level_4',
  37.  
  38.  
  39. 'distance_1_2',
  40.  
  41.  
  42. 'days_from_last_action_1',
  43. 'days_from_last_action_2',
  44. 'days_from_last_action_3',
  45.  
  46. 'days_from_last_active_action_1',
  47. 'days_from_last_active_action_2',
  48. 'days_from_last_active_action_3',
  49.  
  50. 'ctr_1',
  51. 'conversion_1',
  52. 'ctr_2',
  53. 'conversion_2',
  54. 'ctr_3',
  55. 'conversion_3',
  56.  
  57. 'match_preference_1',
  58. 'match_preference_2',
  59. 'match_preference_3'
  60.  
  61.  
  62. ]
  63.  
  64. all_input_features = ord_columns + num_columns
  65.  
  66. # разделяем входящие признаки и таргет в тренировочном датасете
  67. X = data_train[all_input_features]
  68. y = data_train['target']
  69.  
  70.  
  71. # сэмплинг
  72. sampler = RandomOverSampler(random_state=RANDOM_STATE)
  73. X_resample, y_resample = sampler.fit_resample(X, y)
  74.  
  75.  
  76. # предобработка категориальных признаков
  77. categorical_transformer = Pipeline(steps=[
  78. ('imputer', SimpleImputer(missing_values=np.nan, strategy='constant', fill_value='other')),
  79. ('encoder', OrdinalEncoder(categories=[
  80.  
  81. ['complain', 'unsubscribe','hbq_spam','hard_bounce','soft_bounce', 'close',
  82. 'send', 'open','click','subscribe','purchase'], # last_action_1
  83.  
  84. ['complain', 'unsubscribe','hbq_spam','hard_bounce','soft_bounce', 'close',
  85. 'send', 'open','click','subscribe','purchase'], # last_action_2
  86.  
  87. ['complain', 'unsubscribe','hbq_spam','hard_bounce','soft_bounce', 'close',
  88. 'send', 'open','click','subscribe','purchase'], # last_action_3
  89. ],
  90.  
  91. handle_unknown='use_encoded_value', unknown_value=np.nan)),
  92.  
  93. ('imputer2', SimpleImputer(missing_values=np.nan, strategy='constant', fill_value=-1))
  94. ])
  95.  
  96. # предобработка числовых признаков
  97. numeric_transformer = Pipeline(steps=[
  98. ('imputer', SimpleImputer(strategy='constant', fill_value=-1)),
  99. ('scaler', 'passthrough')
  100. ])
  101.  
  102. # объединение предобработки
  103. preprocessor = ColumnTransformer(
  104. transformers=[
  105. ('cat', categorical_transformer, ord_columns),
  106. ('num', numeric_transformer, num_columns),
  107. ])
  108.  
  109. # создание пайплайна с моделью
  110. pipeline = Pipeline(steps=[
  111. ('preprocessor', preprocessor),
  112. ('models', LGBMClassifier())
  113. ])
  114.  
  115. # cловари гиперпараметров для моделей
  116. param_grid = [
  117. {
  118. 'models': [DecisionTreeClassifier(random_state = RANDOM_STATE)],
  119. 'models__max_depth': range (3,9),
  120.  
  121. 'preprocessor__num': [StandardScaler(), MinMaxScaler(), 'passthrough']
  122. }
  123. ]
  124.  
  125.  
  126. # поиск лучшей модели и ее гиперпараметров
  127. model = GridSearchCV(
  128. pipeline,
  129. param_grid,
  130. cv=5,
  131. scoring='roc_auc',
  132. n_jobs=-1
  133. )
  134.  
  135. model.fit(X_resample, y_resample)
  136. print(f'Лучшая модель: {model.best_estimator_.named_steps["models"]}')
  137. print(f'Метрика ROC лучшей модели по результатам кросс-валидации: {round(model.best_score_, 2)}')
  138.  
  139.  
  140. # расчет метрики модели на тестовой выборке
  141. y_pred_proba = model.predict_proba(data_test[all_input_features])[:,1]
  142. print(f"Метрика roc_auc модели на тестовой выборке: {roc_auc_score(data_test['target'], y_pred_proba)}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement