Advertisement
gagarin_1982

Untitled

May 21st, 2024
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.23 KB | None | 0 0
  1. # загрузка модулей и константы
  2. import pandas as pd
  3. import numpy as np
  4. import sklearn
  5.  
  6. from scipy.stats import shapiro
  7.  
  8. from sklearn.metrics import r2_score, f1_score, accuracy_score, make_scorer
  9. from sklearn.model_selection import cross_val_score
  10.  
  11. from sklearn.model_selection import train_test_split
  12. from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, StandardScaler, MinMaxScaler
  13. from sklearn.impute import SimpleImputer
  14.  
  15. from sklearn.linear_model import LinearRegression, LogisticRegression
  16.  
  17. from sklearn.neighbors import KNeighborsClassifier
  18. from sklearn.tree import DecisionTreeClassifier
  19. from sklearn.svm import SVC
  20. from sklearn.svm import SVR
  21.  
  22. from sklearn.compose import ColumnTransformer
  23. from sklearn.pipeline import Pipeline
  24.  
  25. from sklearn.model_selection import RandomizedSearchCV
  26. from sklearn.model_selection import GridSearchCV
  27.  
  28. import warnings
  29. warnings.simplefilter(action='ignore', category=FutureWarning)
  30.  
  31. RANDOM_STATE = 42
  32. TEST_SIZE = 0.25
  33.  
  34. # пользовательская функция для SMAPE
  35. def smape_score(y_true, y_pred):
  36. smape = (np.mean(2.0 * abs(y_true - y_pred) / (abs(y_true) + abs(y_pred))) * 100)
  37. return smape
  38.  
  39. smape_scorer = make_scorer(smape_score, greater_is_better=False)
  40.  
  41. # подбор модели (линейная регрессия)
  42.  
  43. # перечень входящих признаков
  44. input_features = [
  45. 'employment_years',
  46. 'last_year_promo',
  47. 'last_year_violations',
  48. 'supervisor_evaluation',
  49. 'salary'
  50. ]
  51. # целевой признак
  52. output_features = ['job_satisfaction_rate']
  53.  
  54. # train_job_sat - датасет с тренировочными данными для первой модели (удовлетворенность)
  55. X = train_job_sat[input_features]
  56. y = train_job_sat[output_features]
  57.  
  58. X_train, X_test, y_train, y_test = train_test_split(
  59. X,
  60. y,
  61. test_size = TEST_SIZE,
  62. random_state = RANDOM_STATE)
  63.  
  64. # разделение признаков для предобработки
  65. # номинальные категориальные
  66. ohe_columns = []
  67.  
  68. # порядковые категориальные
  69. ord_columns = [
  70. 'last_year_promo',
  71. 'last_year_violations',
  72. ]
  73.  
  74. # количественные
  75. num_columns = [
  76. 'employment_years',
  77. 'salary',
  78. 'supervisor_evaluation'
  79. ]
  80.  
  81. # пайплайн для подготовки признаков из списка номинальных категориальных переменных
  82. ohe_pipe = Pipeline(
  83. [('simpleImputer_ohe', SimpleImputer(missing_values=np.nan, strategy='most_frequent')),
  84. ('ohe', OneHotEncoder(handle_unknown='ignore', sparse=False))
  85. ]
  86. )
  87.  
  88. # пайплайн для подготовки признаков из списка порядковых категориальных переменных
  89. ord_pipe = Pipeline(
  90. [('simpleImputer_before_ord', SimpleImputer(missing_values=np.nan, strategy='most_frequent')),
  91. ('ord', OrdinalEncoder(
  92. categories=[
  93. ['no', 'yes'],
  94. ['no', 'yes'],
  95. ],
  96. handle_unknown='use_encoded_value', unknown_value=np.nan
  97. )
  98. ),
  99. ('simpleImputer_after_ord', SimpleImputer(missing_values=np.nan, strategy='most_frequent'))
  100. ]
  101. )
  102.  
  103. # общий пайплайн для подготовки данных
  104. data_preprocessor = ColumnTransformer(
  105. [('ohe', ohe_pipe, ohe_columns),
  106. ('ord', ord_pipe, ord_columns),
  107. ('num', MinMaxScaler(), num_columns)
  108. ],
  109. remainder='passthrough'
  110. )
  111.  
  112. # итоговый пайплайн
  113. pipe_final = Pipeline([
  114. ('preprocessor', data_preprocessor),
  115. ('models', LinearRegression())
  116. ])
  117.  
  118. # cловари гиперпараметров для моделей
  119. param_grid = [
  120. {
  121. 'models': [LinearRegression()],
  122. 'preprocessor__num': [StandardScaler(), MinMaxScaler(), 'passthrough']
  123. }
  124. ]
  125.  
  126.  
  127. # поиск лучшей модели и ее гиперпараметров
  128. model = GridSearchCV(
  129. pipe_final,
  130. param_grid,
  131. cv=5,
  132. scoring=smape_scorer,
  133. n_jobs=-1
  134. )
  135.  
  136. model.fit(X_train, y_train)
  137. print(model.best_score_)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement