Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # загрузка модулей и константы
- import pandas as pd
- import numpy as np
- import sklearn
- from scipy.stats import shapiro
- from sklearn.metrics import r2_score, f1_score, accuracy_score, make_scorer
- from sklearn.model_selection import cross_val_score
- from sklearn.model_selection import train_test_split
- from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, StandardScaler, MinMaxScaler
- from sklearn.impute import SimpleImputer
- from sklearn.linear_model import LinearRegression, LogisticRegression
- from sklearn.neighbors import KNeighborsClassifier
- from sklearn.tree import DecisionTreeClassifier
- from sklearn.svm import SVC
- from sklearn.svm import SVR
- from sklearn.compose import ColumnTransformer
- from sklearn.pipeline import Pipeline
- from sklearn.model_selection import RandomizedSearchCV
- from sklearn.model_selection import GridSearchCV
- import warnings
- warnings.simplefilter(action='ignore', category=FutureWarning)
- RANDOM_STATE = 42
- TEST_SIZE = 0.25
- # пользовательская функция для SMAPE
- def smape_score(y_true, y_pred):
- smape = (np.mean(2.0 * abs(y_true - y_pred) / (abs(y_true) + abs(y_pred))) * 100)
- return smape
- smape_scorer = make_scorer(smape_score, greater_is_better=False)
- # подбор модели (линейная регрессия)
- # перечень входящих признаков
- input_features = [
- 'employment_years',
- 'last_year_promo',
- 'last_year_violations',
- 'supervisor_evaluation',
- 'salary'
- ]
- # целевой признак
- output_features = ['job_satisfaction_rate']
- # train_job_sat - датасет с тренировочными данными для первой модели (удовлетворенность)
- X = train_job_sat[input_features]
- y = train_job_sat[output_features]
- X_train, X_test, y_train, y_test = train_test_split(
- X,
- y,
- test_size = TEST_SIZE,
- random_state = RANDOM_STATE)
- # разделение признаков для предобработки
- # номинальные категориальные
- ohe_columns = []
- # порядковые категориальные
- ord_columns = [
- 'last_year_promo',
- 'last_year_violations',
- ]
- # количественные
- num_columns = [
- 'employment_years',
- 'salary',
- 'supervisor_evaluation'
- ]
- # пайплайн для подготовки признаков из списка номинальных категориальных переменных
- ohe_pipe = Pipeline(
- [('simpleImputer_ohe', SimpleImputer(missing_values=np.nan, strategy='most_frequent')),
- ('ohe', OneHotEncoder(handle_unknown='ignore', sparse=False))
- ]
- )
- # пайплайн для подготовки признаков из списка порядковых категориальных переменных
- ord_pipe = Pipeline(
- [('simpleImputer_before_ord', SimpleImputer(missing_values=np.nan, strategy='most_frequent')),
- ('ord', OrdinalEncoder(
- categories=[
- ['no', 'yes'],
- ['no', 'yes'],
- ],
- handle_unknown='use_encoded_value', unknown_value=np.nan
- )
- ),
- ('simpleImputer_after_ord', SimpleImputer(missing_values=np.nan, strategy='most_frequent'))
- ]
- )
- # общий пайплайн для подготовки данных
- data_preprocessor = ColumnTransformer(
- [('ohe', ohe_pipe, ohe_columns),
- ('ord', ord_pipe, ord_columns),
- ('num', MinMaxScaler(), num_columns)
- ],
- remainder='passthrough'
- )
- # итоговый пайплайн
- pipe_final = Pipeline([
- ('preprocessor', data_preprocessor),
- ('models', LinearRegression())
- ])
- # cловари гиперпараметров для моделей
- param_grid = [
- {
- 'models': [LinearRegression()],
- 'preprocessor__num': [StandardScaler(), MinMaxScaler(), 'passthrough']
- }
- ]
- # поиск лучшей модели и ее гиперпараметров
- model = GridSearchCV(
- pipe_final,
- param_grid,
- cv=5,
- scoring=smape_scorer,
- n_jobs=-1
- )
- model.fit(X_train, y_train)
- print(model.best_score_)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement