Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # создаём списки с названиями входящих признаков для модели
- # порядковые категориальные
- ord_columns = [
- 'last_action_1',
- 'last_action_2',
- 'last_action_3',
- ]
- # количественные
- num_columns = [
- 'mean_time',
- 'quantity',
- 'rev',
- 'av_bill',
- 'days_after_purch_1',
- 'days_after_purch_2',
- 'days_after_purch_3',
- 'last_purch_1_cat_level_1',
- 'last_purch_1_cat_level_2',
- 'last_purch_1_cat_level_3',
- 'last_purch_1_cat_level_4',
- 'last_purch_2_cat_level_1',
- 'last_purch_2_cat_level_2',
- 'last_purch_2_cat_level_3',
- 'last_purch_2_cat_level_4',
- 'last_purch_3_cat_level_1',
- 'last_purch_3_cat_level_2',
- 'last_purch_3_cat_level_3',
- 'last_purch_3_cat_level_4',
- 'distance_1_2',
- 'days_from_last_action_1',
- 'days_from_last_action_2',
- 'days_from_last_action_3',
- 'days_from_last_active_action_1',
- 'days_from_last_active_action_2',
- 'days_from_last_active_action_3',
- 'ctr_1',
- 'conversion_1',
- 'ctr_2',
- 'conversion_2',
- 'ctr_3',
- 'conversion_3',
- 'match_preference_1',
- 'match_preference_2',
- 'match_preference_3'
- ]
- all_input_features = ord_columns + num_columns
- # разделяем входящие признаки и таргет в тренировочном датасете
- X = data_train[all_input_features]
- y = data_train['target']
- # сэмплинг
- sampler = RandomOverSampler(random_state=RANDOM_STATE)
- X_resample, y_resample = sampler.fit_resample(X, y)
- # предобработка категориальных признаков
- categorical_transformer = Pipeline(steps=[
- ('imputer', SimpleImputer(missing_values=np.nan, strategy='constant', fill_value='other')),
- ('encoder', OrdinalEncoder(categories=[
- ['complain', 'unsubscribe','hbq_spam','hard_bounce','soft_bounce', 'close',
- 'send', 'open','click','subscribe','purchase'], # last_action_1
- ['complain', 'unsubscribe','hbq_spam','hard_bounce','soft_bounce', 'close',
- 'send', 'open','click','subscribe','purchase'], # last_action_2
- ['complain', 'unsubscribe','hbq_spam','hard_bounce','soft_bounce', 'close',
- 'send', 'open','click','subscribe','purchase'], # last_action_3
- ],
- handle_unknown='use_encoded_value', unknown_value=np.nan)),
- ('imputer2', SimpleImputer(missing_values=np.nan, strategy='constant', fill_value=-1))
- ])
- # предобработка числовых признаков
- numeric_transformer = Pipeline(steps=[
- ('imputer', SimpleImputer(strategy='constant', fill_value=-1)),
- ('scaler', 'passthrough')
- ])
- # объединение предобработки
- preprocessor = ColumnTransformer(
- transformers=[
- ('cat', categorical_transformer, ord_columns),
- ('num', numeric_transformer, num_columns),
- ])
- # создание пайплайна с моделью
- pipeline = Pipeline(steps=[
- ('preprocessor', preprocessor),
- ('models', LGBMClassifier())
- ])
- # cловари гиперпараметров для моделей
- param_grid = [
- {
- 'models': [DecisionTreeClassifier(random_state = RANDOM_STATE)],
- 'models__max_depth': range (3,9),
- 'preprocessor__num': [StandardScaler(), MinMaxScaler(), 'passthrough']
- }
- ]
- # поиск лучшей модели и ее гиперпараметров
- model = GridSearchCV(
- pipeline,
- param_grid,
- cv=5,
- scoring='roc_auc',
- n_jobs=-1
- )
- model.fit(X_resample, y_resample)
- print(f'Лучшая модель: {model.best_estimator_.named_steps["models"]}')
- print(f'Метрика ROC лучшей модели по результатам кросс-валидации: {round(model.best_score_, 2)}')
- # расчет метрики модели на тестовой выборке
- y_pred_proba = model.predict_proba(data_test[all_input_features])[:,1]
- print(f"Метрика roc_auc модели на тестовой выборке: {roc_auc_score(data_test['target'], y_pred_proba)}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement