Datasets:

ArXiv:
DOI:
License:
File size: 137,547 Bytes
0eae2d5
1
{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.10","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy.stats import chi2_contingency ","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:23.707889Z","iopub.execute_input":"2023-05-20T13:31:23.708337Z","iopub.status.idle":"2023-05-20T13:31:24.615636Z","shell.execute_reply.started":"2023-05-20T13:31:23.708303Z","shell.execute_reply":"2023-05-20T13:31:24.614494Z"},"trusted":true},"execution_count":1,"outputs":[{"name":"stderr","text":"/opt/conda/lib/python3.10/site-packages/scipy/__init__.py:146: UserWarning: A NumPy version >=1.16.5 and <1.23.0 is required for this version of SciPy (detected version 1.23.5\n  warnings.warn(f\"A NumPy version >={np_minversion} and <{np_maxversion}\"\n","output_type":"stream"}]},{"cell_type":"code","source":"app_train = pd.read_csv('/kaggle/input/home-credit-default-risk/application_train.csv')\napp_test=pd.read_csv('/kaggle/input/home-credit-default-risk/application_test.csv')","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:24.617951Z","iopub.execute_input":"2023-05-20T13:31:24.618585Z","iopub.status.idle":"2023-05-20T13:31:32.801864Z","shell.execute_reply.started":"2023-05-20T13:31:24.618546Z","shell.execute_reply":"2023-05-20T13:31:32.800838Z"},"trusted":true},"execution_count":2,"outputs":[]},{"cell_type":"code","source":"print(app_train[['ORGANIZATION_TYPE','NAME_FAMILY_STATUS', 'CODE_GENDER']].isnull().sum())\nprint('-'*40)\nprint(app_test[['ORGANIZATION_TYPE','NAME_FAMILY_STATUS', 'CODE_GENDER']].isnull().sum())","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:32.803286Z","iopub.execute_input":"2023-05-20T13:31:32.803708Z","iopub.status.idle":"2023-05-20T13:31:33.178020Z","shell.execute_reply.started":"2023-05-20T13:31:32.803673Z","shell.execute_reply":"2023-05-20T13:31:33.176717Z"},"trusted":true},"execution_count":3,"outputs":[{"name":"stdout","text":"ORGANIZATION_TYPE     0\nNAME_FAMILY_STATUS    0\nCODE_GENDER           0\ndtype: int64\n----------------------------------------\nORGANIZATION_TYPE     0\nNAME_FAMILY_STATUS    0\nCODE_GENDER           0\ndtype: int64\n","output_type":"stream"}]},{"cell_type":"code","source":"users_nan = (app_train.isnull().sum() / app_train.shape[0]) * 100\nusers_nan[users_nan > 0].sort_values(ascending=False)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:33.181034Z","iopub.execute_input":"2023-05-20T13:31:33.181384Z","iopub.status.idle":"2023-05-20T13:31:34.800143Z","shell.execute_reply.started":"2023-05-20T13:31:33.181354Z","shell.execute_reply":"2023-05-20T13:31:34.799026Z"},"trusted":true},"execution_count":4,"outputs":[{"execution_count":4,"output_type":"execute_result","data":{"text/plain":"COMMONAREA_MEDI             69.872297\nCOMMONAREA_AVG              69.872297\nCOMMONAREA_MODE             69.872297\nNONLIVINGAPARTMENTS_MEDI    69.432963\nNONLIVINGAPARTMENTS_MODE    69.432963\n                              ...    \nEXT_SOURCE_2                 0.214626\nAMT_GOODS_PRICE              0.090403\nAMT_ANNUITY                  0.003902\nCNT_FAM_MEMBERS              0.000650\nDAYS_LAST_PHONE_CHANGE       0.000325\nLength: 67, dtype: float64"},"metadata":{}}]},{"cell_type":"code","source":"app_train.replace({'XNA': np.nan, 'XNP': np.nan, 'Unknown': np.nan}, inplace = True)\napp_test.replace({'XNA': np.nan, 'XNP': np.nan, 'Unknown': np.nan}, inplace = True)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:34.801805Z","iopub.execute_input":"2023-05-20T13:31:34.803064Z","iopub.status.idle":"2023-05-20T13:31:37.424943Z","shell.execute_reply.started":"2023-05-20T13:31:34.803022Z","shell.execute_reply":"2023-05-20T13:31:37.423842Z"},"trusted":true},"execution_count":5,"outputs":[]},{"cell_type":"code","source":"print(app_train[['ORGANIZATION_TYPE','NAME_FAMILY_STATUS', 'CODE_GENDER']].isnull().sum())\nprint('-'*40)\nprint(app_test[['ORGANIZATION_TYPE','NAME_FAMILY_STATUS', 'CODE_GENDER']].isnull().sum())","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:37.426208Z","iopub.execute_input":"2023-05-20T13:31:37.426520Z","iopub.status.idle":"2023-05-20T13:31:37.781279Z","shell.execute_reply.started":"2023-05-20T13:31:37.426494Z","shell.execute_reply":"2023-05-20T13:31:37.780147Z"},"trusted":true},"execution_count":6,"outputs":[{"name":"stdout","text":"ORGANIZATION_TYPE     55374\nNAME_FAMILY_STATUS        2\nCODE_GENDER               4\ndtype: int64\n----------------------------------------\nORGANIZATION_TYPE     9274\nNAME_FAMILY_STATUS       0\nCODE_GENDER              0\ndtype: int64\n","output_type":"stream"}]},{"cell_type":"code","source":"users_nan = (app_train.isnull().sum() / app_train.shape[0]) * 100\nusers_nan[users_nan > 0].sort_values(ascending=False)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:37.782696Z","iopub.execute_input":"2023-05-20T13:31:37.783262Z","iopub.status.idle":"2023-05-20T13:31:39.299745Z","shell.execute_reply.started":"2023-05-20T13:31:37.783232Z","shell.execute_reply":"2023-05-20T13:31:39.298642Z"},"trusted":true},"execution_count":7,"outputs":[{"execution_count":7,"output_type":"execute_result","data":{"text/plain":"COMMONAREA_MODE             69.872297\nCOMMONAREA_MEDI             69.872297\nCOMMONAREA_AVG              69.872297\nNONLIVINGAPARTMENTS_MODE    69.432963\nNONLIVINGAPARTMENTS_MEDI    69.432963\n                              ...    \nAMT_ANNUITY                  0.003902\nCODE_GENDER                  0.001301\nCNT_FAM_MEMBERS              0.000650\nNAME_FAMILY_STATUS           0.000650\nDAYS_LAST_PHONE_CHANGE       0.000325\nLength: 70, dtype: float64"},"metadata":{}}]},{"cell_type":"code","source":"app_test.drop(app_train.columns[app_train.isnull().mean()>0.4],axis=1, inplace=True)\n","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:39.301331Z","iopub.execute_input":"2023-05-20T13:31:39.301945Z","iopub.status.idle":"2023-05-20T13:31:40.848654Z","shell.execute_reply.started":"2023-05-20T13:31:39.301915Z","shell.execute_reply":"2023-05-20T13:31:40.847530Z"},"trusted":true},"execution_count":8,"outputs":[]},{"cell_type":"code","source":"app_train.drop(app_train.columns[app_train.isnull().mean()>0.4],axis=1, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:40.850202Z","iopub.execute_input":"2023-05-20T13:31:40.850599Z","iopub.status.idle":"2023-05-20T13:31:42.468788Z","shell.execute_reply.started":"2023-05-20T13:31:40.850564Z","shell.execute_reply":"2023-05-20T13:31:42.467742Z"},"trusted":true},"execution_count":9,"outputs":[]},{"cell_type":"code","source":"app_train.shape","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:42.474330Z","iopub.execute_input":"2023-05-20T13:31:42.474671Z","iopub.status.idle":"2023-05-20T13:31:42.481468Z","shell.execute_reply.started":"2023-05-20T13:31:42.474643Z","shell.execute_reply":"2023-05-20T13:31:42.480481Z"},"trusted":true},"execution_count":10,"outputs":[{"execution_count":10,"output_type":"execute_result","data":{"text/plain":"(307511, 73)"},"metadata":{}}]},{"cell_type":"code","source":"app_test.shape","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:42.482691Z","iopub.execute_input":"2023-05-20T13:31:42.482990Z","iopub.status.idle":"2023-05-20T13:31:42.497810Z","shell.execute_reply.started":"2023-05-20T13:31:42.482965Z","shell.execute_reply":"2023-05-20T13:31:42.496609Z"},"trusted":true},"execution_count":11,"outputs":[{"execution_count":11,"output_type":"execute_result","data":{"text/plain":"(48744, 72)"},"metadata":{}}]},{"cell_type":"code","source":"users_nan = (app_train.isnull().sum() / app_train.shape[0]) * 100\nusers_nan[users_nan > 0].sort_values(ascending=False)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:42.499228Z","iopub.execute_input":"2023-05-20T13:31:42.499575Z","iopub.status.idle":"2023-05-20T13:31:43.679359Z","shell.execute_reply.started":"2023-05-20T13:31:42.499547Z","shell.execute_reply":"2023-05-20T13:31:43.678275Z"},"trusted":true},"execution_count":12,"outputs":[{"execution_count":12,"output_type":"execute_result","data":{"text/plain":"OCCUPATION_TYPE               31.345545\nEXT_SOURCE_3                  19.825307\nORGANIZATION_TYPE             18.007161\nAMT_REQ_CREDIT_BUREAU_YEAR    13.501631\nAMT_REQ_CREDIT_BUREAU_QRT     13.501631\nAMT_REQ_CREDIT_BUREAU_MON     13.501631\nAMT_REQ_CREDIT_BUREAU_WEEK    13.501631\nAMT_REQ_CREDIT_BUREAU_DAY     13.501631\nAMT_REQ_CREDIT_BUREAU_HOUR    13.501631\nNAME_TYPE_SUITE                0.420148\nOBS_60_CNT_SOCIAL_CIRCLE       0.332021\nDEF_60_CNT_SOCIAL_CIRCLE       0.332021\nOBS_30_CNT_SOCIAL_CIRCLE       0.332021\nDEF_30_CNT_SOCIAL_CIRCLE       0.332021\nEXT_SOURCE_2                   0.214626\nAMT_GOODS_PRICE                0.090403\nAMT_ANNUITY                    0.003902\nCODE_GENDER                    0.001301\nCNT_FAM_MEMBERS                0.000650\nNAME_FAMILY_STATUS             0.000650\nDAYS_LAST_PHONE_CHANGE         0.000325\ndtype: float64"},"metadata":{}}]},{"cell_type":"code","source":"users_nan = (app_test.isnull().sum() / app_test.shape[0]) * 100\nusers_nan[users_nan > 0].sort_values(ascending=False)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:43.680639Z","iopub.execute_input":"2023-05-20T13:31:43.680950Z","iopub.status.idle":"2023-05-20T13:31:43.878881Z","shell.execute_reply.started":"2023-05-20T13:31:43.680924Z","shell.execute_reply":"2023-05-20T13:31:43.877523Z"},"trusted":true},"execution_count":13,"outputs":[{"execution_count":13,"output_type":"execute_result","data":{"text/plain":"OCCUPATION_TYPE               32.014197\nORGANIZATION_TYPE             19.025931\nEXT_SOURCE_3                  17.782701\nAMT_REQ_CREDIT_BUREAU_HOUR    12.409732\nAMT_REQ_CREDIT_BUREAU_DAY     12.409732\nAMT_REQ_CREDIT_BUREAU_WEEK    12.409732\nAMT_REQ_CREDIT_BUREAU_MON     12.409732\nAMT_REQ_CREDIT_BUREAU_QRT     12.409732\nAMT_REQ_CREDIT_BUREAU_YEAR    12.409732\nNAME_TYPE_SUITE                1.868948\nOBS_30_CNT_SOCIAL_CIRCLE       0.059495\nDEF_30_CNT_SOCIAL_CIRCLE       0.059495\nOBS_60_CNT_SOCIAL_CIRCLE       0.059495\nDEF_60_CNT_SOCIAL_CIRCLE       0.059495\nAMT_ANNUITY                    0.049237\nEXT_SOURCE_2                   0.016412\ndtype: float64"},"metadata":{}}]},{"cell_type":"code","source":"# Columns have less 14% NaN Values and categorical\nCat_columns_lower_percentage_nan  = [i for i in app_train.columns[(((app_train.isnull().sum() / app_train.shape[0]) * 100) > 0) \n                                                                  & (((app_train.isnull().sum() / app_train.shape[0]) * 100) < 14)] \n                                     if app_train[i].dtype == 'O']\n\n# Columns have less 14% NaN Values and numerical\nnum_columns_lower_percentage_nan  = [i for i in app_train.columns[(((app_train.isnull().sum() / app_train.shape[0]) * 100) > 0) \n                                                                  & (((app_train.isnull().sum() / app_train.shape[0]) * 100) < 14)] \n                                     if app_train[i].dtype != 'O']","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:43.880546Z","iopub.execute_input":"2023-05-20T13:31:43.880911Z","iopub.status.idle":"2023-05-20T13:31:48.486015Z","shell.execute_reply.started":"2023-05-20T13:31:43.880873Z","shell.execute_reply":"2023-05-20T13:31:48.484853Z"},"trusted":true},"execution_count":14,"outputs":[]},{"cell_type":"code","source":"for i in Cat_columns_lower_percentage_nan:\n    app_test[i].fillna(app_train[i].mode()[0], inplace=True)\n    app_train[i].fillna(app_train[i].mode()[0], inplace=True)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:48.487321Z","iopub.execute_input":"2023-05-20T13:31:48.487653Z","iopub.status.idle":"2023-05-20T13:31:48.899460Z","shell.execute_reply.started":"2023-05-20T13:31:48.487625Z","shell.execute_reply":"2023-05-20T13:31:48.898112Z"},"trusted":true},"execution_count":15,"outputs":[]},{"cell_type":"code","source":"col_mod_transfrom = [i for i in num_columns_lower_percentage_nan if i not in ['EXT_SOURCE_2', 'AMT_ANNUITY','AMT_GOODS_PRICE']]\ncol_mean_transform = ['EXT_SOURCE_2', 'AMT_ANNUITY']","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:48.901227Z","iopub.execute_input":"2023-05-20T13:31:48.901595Z","iopub.status.idle":"2023-05-20T13:31:48.907826Z","shell.execute_reply.started":"2023-05-20T13:31:48.901557Z","shell.execute_reply":"2023-05-20T13:31:48.906526Z"},"trusted":true},"execution_count":16,"outputs":[]},{"cell_type":"code","source":"for i in col_mod_transfrom:\n    app_test[i].fillna(app_train[i].mode()[0], inplace=True)\n    app_train[i].fillna(app_train[i].mode()[0], inplace=True)\nfor i in col_mean_transform:\n    app_test[i].fillna(app_train[i].mean(), inplace=True)\n    app_train[i].fillna(app_train[i].mean(), inplace=True)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:48.910234Z","iopub.execute_input":"2023-05-20T13:31:48.911188Z","iopub.status.idle":"2023-05-20T13:31:49.048717Z","shell.execute_reply.started":"2023-05-20T13:31:48.911124Z","shell.execute_reply":"2023-05-20T13:31:49.047610Z"},"trusted":true},"execution_count":17,"outputs":[]},{"cell_type":"code","source":"app_train['AMT_GOODS_PRICE'].fillna(app_train['AMT_GOODS_PRICE'].median(),inplace = True)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:49.050280Z","iopub.execute_input":"2023-05-20T13:31:49.050761Z","iopub.status.idle":"2023-05-20T13:31:49.067588Z","shell.execute_reply.started":"2023-05-20T13:31:49.050725Z","shell.execute_reply":"2023-05-20T13:31:49.066219Z"},"trusted":true},"execution_count":18,"outputs":[]},{"cell_type":"code","source":"all_numerical_cols = list(app_train.select_dtypes(exclude='object').columns)\n\ncont_cols = [col for col in all_numerical_cols if col != \"TARGET\" and col[:5]!='FLAG_']","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:49.069475Z","iopub.execute_input":"2023-05-20T13:31:49.070174Z","iopub.status.idle":"2023-05-20T13:31:49.134864Z","shell.execute_reply.started":"2023-05-20T13:31:49.070111Z","shell.execute_reply":"2023-05-20T13:31:49.133757Z"},"trusted":true},"execution_count":19,"outputs":[]},{"cell_type":"code","source":"app_train[(abs(app_train['DAYS_BIRTH']) < abs(app_train['DAYS_EMPLOYED'])) & (app_train['DAYS_EMPLOYED'] != 365243)]","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:49.136528Z","iopub.execute_input":"2023-05-20T13:31:49.136879Z","iopub.status.idle":"2023-05-20T13:31:49.170520Z","shell.execute_reply.started":"2023-05-20T13:31:49.136849Z","shell.execute_reply":"2023-05-20T13:31:49.169241Z"},"trusted":true},"execution_count":20,"outputs":[{"execution_count":20,"output_type":"execute_result","data":{"text/plain":"Empty DataFrame\nColumns: [SK_ID_CURR, TARGET, NAME_CONTRACT_TYPE, CODE_GENDER, FLAG_OWN_CAR, FLAG_OWN_REALTY, CNT_CHILDREN, AMT_INCOME_TOTAL, AMT_CREDIT, AMT_ANNUITY, AMT_GOODS_PRICE, NAME_TYPE_SUITE, NAME_INCOME_TYPE, NAME_EDUCATION_TYPE, NAME_FAMILY_STATUS, NAME_HOUSING_TYPE, REGION_POPULATION_RELATIVE, DAYS_BIRTH, DAYS_EMPLOYED, DAYS_REGISTRATION, DAYS_ID_PUBLISH, FLAG_MOBIL, FLAG_EMP_PHONE, FLAG_WORK_PHONE, FLAG_CONT_MOBILE, FLAG_PHONE, FLAG_EMAIL, OCCUPATION_TYPE, CNT_FAM_MEMBERS, REGION_RATING_CLIENT, REGION_RATING_CLIENT_W_CITY, WEEKDAY_APPR_PROCESS_START, HOUR_APPR_PROCESS_START, REG_REGION_NOT_LIVE_REGION, REG_REGION_NOT_WORK_REGION, LIVE_REGION_NOT_WORK_REGION, REG_CITY_NOT_LIVE_CITY, REG_CITY_NOT_WORK_CITY, LIVE_CITY_NOT_WORK_CITY, ORGANIZATION_TYPE, EXT_SOURCE_2, EXT_SOURCE_3, OBS_30_CNT_SOCIAL_CIRCLE, DEF_30_CNT_SOCIAL_CIRCLE, OBS_60_CNT_SOCIAL_CIRCLE, DEF_60_CNT_SOCIAL_CIRCLE, DAYS_LAST_PHONE_CHANGE, FLAG_DOCUMENT_2, FLAG_DOCUMENT_3, FLAG_DOCUMENT_4, FLAG_DOCUMENT_5, FLAG_DOCUMENT_6, FLAG_DOCUMENT_7, FLAG_DOCUMENT_8, FLAG_DOCUMENT_9, FLAG_DOCUMENT_10, FLAG_DOCUMENT_11, FLAG_DOCUMENT_12, FLAG_DOCUMENT_13, FLAG_DOCUMENT_14, FLAG_DOCUMENT_15, FLAG_DOCUMENT_16, FLAG_DOCUMENT_17, FLAG_DOCUMENT_18, FLAG_DOCUMENT_19, FLAG_DOCUMENT_20, FLAG_DOCUMENT_21, AMT_REQ_CREDIT_BUREAU_HOUR, AMT_REQ_CREDIT_BUREAU_DAY, AMT_REQ_CREDIT_BUREAU_WEEK, AMT_REQ_CREDIT_BUREAU_MON, AMT_REQ_CREDIT_BUREAU_QRT, AMT_REQ_CREDIT_BUREAU_YEAR]\nIndex: []\n\n[0 rows x 73 columns]","text/html":"<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>SK_ID_CURR</th>\n      <th>TARGET</th>\n      <th>NAME_CONTRACT_TYPE</th>\n      <th>CODE_GENDER</th>\n      <th>FLAG_OWN_CAR</th>\n      <th>FLAG_OWN_REALTY</th>\n      <th>CNT_CHILDREN</th>\n      <th>AMT_INCOME_TOTAL</th>\n      <th>AMT_CREDIT</th>\n      <th>AMT_ANNUITY</th>\n      <th>...</th>\n      <th>FLAG_DOCUMENT_18</th>\n      <th>FLAG_DOCUMENT_19</th>\n      <th>FLAG_DOCUMENT_20</th>\n      <th>FLAG_DOCUMENT_21</th>\n      <th>AMT_REQ_CREDIT_BUREAU_HOUR</th>\n      <th>AMT_REQ_CREDIT_BUREAU_DAY</th>\n      <th>AMT_REQ_CREDIT_BUREAU_WEEK</th>\n      <th>AMT_REQ_CREDIT_BUREAU_MON</th>\n      <th>AMT_REQ_CREDIT_BUREAU_QRT</th>\n      <th>AMT_REQ_CREDIT_BUREAU_YEAR</th>\n    </tr>\n  </thead>\n  <tbody>\n  </tbody>\n</table>\n<p>0 rows × 73 columns</p>\n</div>"},"metadata":{}}]},{"cell_type":"code","source":"proper_days_empolyed_df = app_train\nproper_days_empolyed_df['YEARS_EMPLOYED'] = proper_days_empolyed_df['DAYS_EMPLOYED']/-365.25\n","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:49.171745Z","iopub.execute_input":"2023-05-20T13:31:49.172092Z","iopub.status.idle":"2023-05-20T13:31:49.179130Z","shell.execute_reply.started":"2023-05-20T13:31:49.172040Z","shell.execute_reply":"2023-05-20T13:31:49.178185Z"},"trusted":true},"execution_count":21,"outputs":[]},{"cell_type":"code","source":"app_train['DAYS_EMPLOYED'].replace({365243:np.nan},inplace=True) \napp_test['DAYS_EMPLOYED'].replace({365243:np.nan},inplace=True) ","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:49.180556Z","iopub.execute_input":"2023-05-20T13:31:49.181041Z","iopub.status.idle":"2023-05-20T13:31:49.238079Z","shell.execute_reply.started":"2023-05-20T13:31:49.181007Z","shell.execute_reply":"2023-05-20T13:31:49.236986Z"},"trusted":true},"execution_count":22,"outputs":[]},{"cell_type":"code","source":"proper_days_empolyed_df = app_train\nproper_days_empolyed_df['YEARS_EMPLOYED'] = proper_days_empolyed_df['DAYS_EMPLOYED']/-365.25\n","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:49.239586Z","iopub.execute_input":"2023-05-20T13:31:49.239903Z","iopub.status.idle":"2023-05-20T13:31:49.246895Z","shell.execute_reply.started":"2023-05-20T13:31:49.239876Z","shell.execute_reply":"2023-05-20T13:31:49.245736Z"},"trusted":true},"execution_count":23,"outputs":[]},{"cell_type":"code","source":"app_train.groupby(['OCCUPATION_TYPE'])['DAYS_EMPLOYED'].mean()","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:49.247973Z","iopub.execute_input":"2023-05-20T13:31:49.248350Z","iopub.status.idle":"2023-05-20T13:31:49.329255Z","shell.execute_reply.started":"2023-05-20T13:31:49.248321Z","shell.execute_reply":"2023-05-20T13:31:49.328177Z"},"trusted":true},"execution_count":24,"outputs":[{"execution_count":24,"output_type":"execute_result","data":{"text/plain":"OCCUPATION_TYPE\nAccountants             -2394.102823\nCleaning staff          -2131.155665\nCooking staff           -2152.466868\nCore staff              -2797.755967\nDrivers                 -1939.034618\nHR staff                -2278.866785\nHigh skill tech staff   -2739.979086\nIT staff                -2095.570342\nLaborers                -2424.143152\nLow-skill Laborers      -1664.186813\nManagers                -2759.318937\nMedicine staff          -3750.265550\nPrivate service staff   -2238.281297\nRealty agents           -1785.003995\nSales staff             -1703.789421\nSecretaries             -2607.050575\nSecurity staff          -1904.809106\nWaiters/barmen staff    -1873.172849\nName: DAYS_EMPLOYED, dtype: float64"},"metadata":{}}]},{"cell_type":"code","source":"## create dataframe with total income > 1M\nsusp_df1 = app_train[app_train['AMT_INCOME_TOTAL']>1e+6][['AMT_INCOME_TOTAL','AMT_CREDIT','AMT_ANNUITY','CNT_CHILDREN', 'TARGET']].sort_values(by='AMT_INCOME_TOTAL', ascending=False)\n\n## create Credit/Income and Annuity/Income percentages\nsusp_df1['Credit/Income'] = susp_df1['AMT_CREDIT']/susp_df1['AMT_INCOME_TOTAL']\nsusp_df1['Annuity/Income'] = susp_df1['AMT_ANNUITY']/susp_df1['AMT_INCOME_TOTAL']\n\n## show only clients with difficuties\nsusp_df1[susp_df1['TARGET']==1].sort_values(by='Credit/Income', ascending=True)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:49.330437Z","iopub.execute_input":"2023-05-20T13:31:49.331266Z","iopub.status.idle":"2023-05-20T13:31:49.397670Z","shell.execute_reply.started":"2023-05-20T13:31:49.331236Z","shell.execute_reply":"2023-05-20T13:31:49.396570Z"},"trusted":true},"execution_count":25,"outputs":[{"execution_count":25,"output_type":"execute_result","data":{"text/plain":"        AMT_INCOME_TOTAL  AMT_CREDIT  AMT_ANNUITY  CNT_CHILDREN  TARGET  \\\n12840        117000000.0    562491.0      26194.5             1       1   \n248159         3150000.0    900000.0      48825.0             1       1   \n151018         1080000.0    371245.5      17437.5             0       1   \n167656         1575000.0    553806.0      28273.5             0       1   \n173663         1350000.0    491211.0      50463.0             3       1   \n41725          1890000.0    781920.0      61906.5             1       1   \n234728         1350000.0    576072.0      28017.0             0       1   \n248970         1890000.0    900000.0      57649.5             0       1   \n265884         1170000.0    983299.5      41661.0             1       1   \n234861         1260000.0   1097491.5      46629.0             0       1   \n38271          1125000.0   1006920.0      40063.5             0       1   \n102626         1305000.0   1339884.0      39307.5             0       1   \n196106         1350000.0   2517300.0      93420.0             2       1   \n\n        Credit/Income  Annuity/Income  \n12840        0.004808        0.000224  \n248159       0.285714        0.015500  \n151018       0.343746        0.016146  \n167656       0.351623        0.017951  \n173663       0.363860        0.037380  \n41725        0.413714        0.032755  \n234728       0.426720        0.020753  \n248970       0.476190        0.030502  \n265884       0.840427        0.035608  \n234861       0.871025        0.037007  \n38271        0.895040        0.035612  \n102626       1.026731        0.030121  \n196106       1.864667        0.069200  ","text/html":"<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>AMT_INCOME_TOTAL</th>\n      <th>AMT_CREDIT</th>\n      <th>AMT_ANNUITY</th>\n      <th>CNT_CHILDREN</th>\n      <th>TARGET</th>\n      <th>Credit/Income</th>\n      <th>Annuity/Income</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>12840</th>\n      <td>117000000.0</td>\n      <td>562491.0</td>\n      <td>26194.5</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0.004808</td>\n      <td>0.000224</td>\n    </tr>\n    <tr>\n      <th>248159</th>\n      <td>3150000.0</td>\n      <td>900000.0</td>\n      <td>48825.0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0.285714</td>\n      <td>0.015500</td>\n    </tr>\n    <tr>\n      <th>151018</th>\n      <td>1080000.0</td>\n      <td>371245.5</td>\n      <td>17437.5</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0.343746</td>\n      <td>0.016146</td>\n    </tr>\n    <tr>\n      <th>167656</th>\n      <td>1575000.0</td>\n      <td>553806.0</td>\n      <td>28273.5</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0.351623</td>\n      <td>0.017951</td>\n    </tr>\n    <tr>\n      <th>173663</th>\n      <td>1350000.0</td>\n      <td>491211.0</td>\n      <td>50463.0</td>\n      <td>3</td>\n      <td>1</td>\n      <td>0.363860</td>\n      <td>0.037380</td>\n    </tr>\n    <tr>\n      <th>41725</th>\n      <td>1890000.0</td>\n      <td>781920.0</td>\n      <td>61906.5</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0.413714</td>\n      <td>0.032755</td>\n    </tr>\n    <tr>\n      <th>234728</th>\n      <td>1350000.0</td>\n      <td>576072.0</td>\n      <td>28017.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0.426720</td>\n      <td>0.020753</td>\n    </tr>\n    <tr>\n      <th>248970</th>\n      <td>1890000.0</td>\n      <td>900000.0</td>\n      <td>57649.5</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0.476190</td>\n      <td>0.030502</td>\n    </tr>\n    <tr>\n      <th>265884</th>\n      <td>1170000.0</td>\n      <td>983299.5</td>\n      <td>41661.0</td>\n      <td>1</td>\n      <td>1</td>\n      <td>0.840427</td>\n      <td>0.035608</td>\n    </tr>\n    <tr>\n      <th>234861</th>\n      <td>1260000.0</td>\n      <td>1097491.5</td>\n      <td>46629.0</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0.871025</td>\n      <td>0.037007</td>\n    </tr>\n    <tr>\n      <th>38271</th>\n      <td>1125000.0</td>\n      <td>1006920.0</td>\n      <td>40063.5</td>\n      <td>0</td>\n      <td>1</td>\n      <td>0.895040</td>\n      <td>0.035612</td>\n    </tr>\n    <tr>\n      <th>102626</th>\n      <td>1305000.0</td>\n      <td>1339884.0</td>\n      <td>39307.5</td>\n      <td>0</td>\n      <td>1</td>\n      <td>1.026731</td>\n      <td>0.030121</td>\n    </tr>\n    <tr>\n      <th>196106</th>\n      <td>1350000.0</td>\n      <td>2517300.0</td>\n      <td>93420.0</td>\n      <td>2</td>\n      <td>1</td>\n      <td>1.864667</td>\n      <td>0.069200</td>\n    </tr>\n  </tbody>\n</table>\n</div>"},"metadata":{}}]},{"cell_type":"code","source":"app_train = app_train[app_train['AMT_INCOME_TOTAL'] != 117000000.0]\n","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:49.399208Z","iopub.execute_input":"2023-05-20T13:31:49.399844Z","iopub.status.idle":"2023-05-20T13:31:49.523335Z","shell.execute_reply.started":"2023-05-20T13:31:49.399813Z","shell.execute_reply":"2023-05-20T13:31:49.522194Z"},"trusted":true},"execution_count":26,"outputs":[]},{"cell_type":"code","source":"## extract dataframe with DAYS_BIRTH and TARGET only\nsusp_df2 = app_train[['DAYS_BIRTH','TARGET']]\n\n## create column represnts the age in years\nsusp_df2['YEARS_BIRTH'] = np.abs(susp_df2['DAYS_BIRTH']) / 365.25\n\n## show datafame\ndisplay(susp_df2.sort_values(by='YEARS_BIRTH', ascending=False))\n\n## show the value counts of those who are aged > 65 with respect to target\ndisplay(susp_df2[(susp_df2['YEARS_BIRTH']>65)]['TARGET'].value_counts())","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:49.524772Z","iopub.execute_input":"2023-05-20T13:31:49.525201Z","iopub.status.idle":"2023-05-20T13:31:49.604686Z","shell.execute_reply.started":"2023-05-20T13:31:49.525143Z","shell.execute_reply":"2023-05-20T13:31:49.603377Z"},"trusted":true},"execution_count":27,"outputs":[{"name":"stderr","text":"/tmp/ipykernel_34/200317661.py:5: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  susp_df2['YEARS_BIRTH'] = np.abs(susp_df2['DAYS_BIRTH']) / 365.25\n","output_type":"stream"},{"output_type":"display_data","data":{"text/plain":"        DAYS_BIRTH  TARGET  YEARS_BIRTH\n265026      -25229       0    69.073238\n63316       -25201       0    68.996578\n124430      -25201       0    68.996578\n143266      -25200       0    68.993840\n130108      -25197       0    68.985626\n...            ...     ...          ...\n220805       -7678       1    21.021218\n170384       -7676       0    21.015743\n53702        -7676       0    21.015743\n168135       -7673       0    21.007529\n235444       -7489       0    20.503765\n\n[307510 rows x 3 columns]","text/html":"<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>DAYS_BIRTH</th>\n      <th>TARGET</th>\n      <th>YEARS_BIRTH</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>265026</th>\n      <td>-25229</td>\n      <td>0</td>\n      <td>69.073238</td>\n    </tr>\n    <tr>\n      <th>63316</th>\n      <td>-25201</td>\n      <td>0</td>\n      <td>68.996578</td>\n    </tr>\n    <tr>\n      <th>124430</th>\n      <td>-25201</td>\n      <td>0</td>\n      <td>68.996578</td>\n    </tr>\n    <tr>\n      <th>143266</th>\n      <td>-25200</td>\n      <td>0</td>\n      <td>68.993840</td>\n    </tr>\n    <tr>\n      <th>130108</th>\n      <td>-25197</td>\n      <td>0</td>\n      <td>68.985626</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>220805</th>\n      <td>-7678</td>\n      <td>1</td>\n      <td>21.021218</td>\n    </tr>\n    <tr>\n      <th>170384</th>\n      <td>-7676</td>\n      <td>0</td>\n      <td>21.015743</td>\n    </tr>\n    <tr>\n      <th>53702</th>\n      <td>-7676</td>\n      <td>0</td>\n      <td>21.015743</td>\n    </tr>\n    <tr>\n      <th>168135</th>\n      <td>-7673</td>\n      <td>0</td>\n      <td>21.007529</td>\n    </tr>\n    <tr>\n      <th>235444</th>\n      <td>-7489</td>\n      <td>0</td>\n      <td>20.503765</td>\n    </tr>\n  </tbody>\n</table>\n<p>307510 rows × 3 columns</p>\n</div>"},"metadata":{}},{"output_type":"display_data","data":{"text/plain":"0    7588\n1     288\nName: TARGET, dtype: int64"},"metadata":{}}]},{"cell_type":"code","source":"cat_col = app_train.select_dtypes('object')\ncat_col.describe()","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:49.614863Z","iopub.execute_input":"2023-05-20T13:31:49.615247Z","iopub.status.idle":"2023-05-20T13:31:50.648599Z","shell.execute_reply.started":"2023-05-20T13:31:49.615217Z","shell.execute_reply":"2023-05-20T13:31:50.647443Z"},"trusted":true},"execution_count":28,"outputs":[{"execution_count":28,"output_type":"execute_result","data":{"text/plain":"       NAME_CONTRACT_TYPE CODE_GENDER FLAG_OWN_CAR FLAG_OWN_REALTY  \\\ncount              307510      307510       307510          307510   \nunique                  2           2            2               2   \ntop            Cash loans           F            N               Y   \nfreq               278231      202451       202923          213311   \n\n       NAME_TYPE_SUITE NAME_INCOME_TYPE            NAME_EDUCATION_TYPE  \\\ncount           307510           307510                         307510   \nunique               7                8                              5   \ntop      Unaccompanied          Working  Secondary / secondary special   \nfreq            249817           158773                         218390   \n\n       NAME_FAMILY_STATUS  NAME_HOUSING_TYPE OCCUPATION_TYPE  \\\ncount              307510             307510          211119   \nunique                  5                  6              18   \ntop               Married  House / apartment        Laborers   \nfreq               196433             272867           55185   \n\n       WEEKDAY_APPR_PROCESS_START       ORGANIZATION_TYPE  \ncount                      307510                  252136  \nunique                          7                      57  \ntop                       TUESDAY  Business Entity Type 3  \nfreq                        53900                   67991  ","text/html":"<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>NAME_CONTRACT_TYPE</th>\n      <th>CODE_GENDER</th>\n      <th>FLAG_OWN_CAR</th>\n      <th>FLAG_OWN_REALTY</th>\n      <th>NAME_TYPE_SUITE</th>\n      <th>NAME_INCOME_TYPE</th>\n      <th>NAME_EDUCATION_TYPE</th>\n      <th>NAME_FAMILY_STATUS</th>\n      <th>NAME_HOUSING_TYPE</th>\n      <th>OCCUPATION_TYPE</th>\n      <th>WEEKDAY_APPR_PROCESS_START</th>\n      <th>ORGANIZATION_TYPE</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>count</th>\n      <td>307510</td>\n      <td>307510</td>\n      <td>307510</td>\n      <td>307510</td>\n      <td>307510</td>\n      <td>307510</td>\n      <td>307510</td>\n      <td>307510</td>\n      <td>307510</td>\n      <td>211119</td>\n      <td>307510</td>\n      <td>252136</td>\n    </tr>\n    <tr>\n      <th>unique</th>\n      <td>2</td>\n      <td>2</td>\n      <td>2</td>\n      <td>2</td>\n      <td>7</td>\n      <td>8</td>\n      <td>5</td>\n      <td>5</td>\n      <td>6</td>\n      <td>18</td>\n      <td>7</td>\n      <td>57</td>\n    </tr>\n    <tr>\n      <th>top</th>\n      <td>Cash loans</td>\n      <td>F</td>\n      <td>N</td>\n      <td>Y</td>\n      <td>Unaccompanied</td>\n      <td>Working</td>\n      <td>Secondary / secondary special</td>\n      <td>Married</td>\n      <td>House / apartment</td>\n      <td>Laborers</td>\n      <td>TUESDAY</td>\n      <td>Business Entity Type 3</td>\n    </tr>\n    <tr>\n      <th>freq</th>\n      <td>278231</td>\n      <td>202451</td>\n      <td>202923</td>\n      <td>213311</td>\n      <td>249817</td>\n      <td>158773</td>\n      <td>218390</td>\n      <td>196433</td>\n      <td>272867</td>\n      <td>55185</td>\n      <td>53900</td>\n      <td>67991</td>\n    </tr>\n  </tbody>\n</table>\n</div>"},"metadata":{}}]},{"cell_type":"code","source":"app_train.groupby(['NAME_EDUCATION_TYPE'])['OCCUPATION_TYPE'].agg(pd.Series.mode)\n","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:50.651202Z","iopub.execute_input":"2023-05-20T13:31:50.652481Z","iopub.status.idle":"2023-05-20T13:31:50.755628Z","shell.execute_reply.started":"2023-05-20T13:31:50.652444Z","shell.execute_reply":"2023-05-20T13:31:50.754347Z"},"trusted":true},"execution_count":29,"outputs":[{"execution_count":29,"output_type":"execute_result","data":{"text/plain":"NAME_EDUCATION_TYPE\nAcademic degree                    Managers\nHigher education                 Core staff\nIncomplete higher                  Laborers\nLower secondary                    Laborers\nSecondary / secondary special      Laborers\nName: OCCUPATION_TYPE, dtype: object"},"metadata":{}}]},{"cell_type":"code","source":"app_train['OCCUPATION_TYPE'].isnull().sum()\napp_test['OCCUPATION_TYPE'].isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:50.757283Z","iopub.execute_input":"2023-05-20T13:31:50.757725Z","iopub.status.idle":"2023-05-20T13:31:50.799252Z","shell.execute_reply.started":"2023-05-20T13:31:50.757690Z","shell.execute_reply":"2023-05-20T13:31:50.797887Z"},"trusted":true},"execution_count":30,"outputs":[{"execution_count":30,"output_type":"execute_result","data":{"text/plain":"15605"},"metadata":{}}]},{"cell_type":"code","source":"app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Secondary / secondary special'] = app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Secondary / secondary special'].fillna('Laborers')\napp_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Higher education'] =  app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Higher education'].fillna('Core staff')\napp_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Incomplete higher'] = app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Incomplete higher'].fillna('Laborers')\napp_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Lower secondary'] = app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Lower secondary'].fillna('Laborers')\napp_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Academic degree'] = app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Academic degree'].fillna('Managers')\n\napp_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Secondary / secondary special'] = app_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Secondary / secondary special'].fillna('Laborers')\napp_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Higher education'] =  app_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Higher education'].fillna('Core staff')\napp_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Incomplete higher'] = app_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Incomplete higher'].fillna('Laborers')\napp_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Lower secondary'] = app_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Lower secondary'].fillna('Laborers')\napp_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Academic degree'] = app_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Academic degree'].fillna('Managers')","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:50.800536Z","iopub.execute_input":"2023-05-20T13:31:50.800859Z","iopub.status.idle":"2023-05-20T13:31:51.560567Z","shell.execute_reply.started":"2023-05-20T13:31:50.800833Z","shell.execute_reply":"2023-05-20T13:31:51.558644Z"},"trusted":true},"execution_count":31,"outputs":[{"name":"stderr","text":"/tmp/ipykernel_34/1817237716.py:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Secondary / secondary special'] = app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Secondary / secondary special'].fillna('Laborers')\n/tmp/ipykernel_34/1817237716.py:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Secondary / secondary special'] = app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Secondary / secondary special'].fillna('Laborers')\n/tmp/ipykernel_34/1817237716.py:2: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Higher education'] =  app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Higher education'].fillna('Core staff')\n/tmp/ipykernel_34/1817237716.py:2: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Higher education'] =  app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Higher education'].fillna('Core staff')\n/tmp/ipykernel_34/1817237716.py:3: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Incomplete higher'] = app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Incomplete higher'].fillna('Laborers')\n/tmp/ipykernel_34/1817237716.py:3: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Incomplete higher'] = app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Incomplete higher'].fillna('Laborers')\n/tmp/ipykernel_34/1817237716.py:4: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Lower secondary'] = app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Lower secondary'].fillna('Laborers')\n/tmp/ipykernel_34/1817237716.py:4: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Lower secondary'] = app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Lower secondary'].fillna('Laborers')\n/tmp/ipykernel_34/1817237716.py:5: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Academic degree'] = app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Academic degree'].fillna('Managers')\n/tmp/ipykernel_34/1817237716.py:5: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Academic degree'] = app_train['OCCUPATION_TYPE'][app_train['NAME_EDUCATION_TYPE']=='Academic degree'].fillna('Managers')\n/tmp/ipykernel_34/1817237716.py:7: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Secondary / secondary special'] = app_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Secondary / secondary special'].fillna('Laborers')\n/tmp/ipykernel_34/1817237716.py:8: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Higher education'] =  app_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Higher education'].fillna('Core staff')\n/tmp/ipykernel_34/1817237716.py:9: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Incomplete higher'] = app_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Incomplete higher'].fillna('Laborers')\n/tmp/ipykernel_34/1817237716.py:10: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Lower secondary'] = app_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Lower secondary'].fillna('Laborers')\n/tmp/ipykernel_34/1817237716.py:11: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Academic degree'] = app_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Academic degree'].fillna('Managers')\n","output_type":"stream"}]},{"cell_type":"code","source":"app_train.groupby(['OCCUPATION_TYPE'])['ORGANIZATION_TYPE'].agg(pd.Series.mode)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:51.562188Z","iopub.execute_input":"2023-05-20T13:31:51.562638Z","iopub.status.idle":"2023-05-20T13:31:51.673103Z","shell.execute_reply.started":"2023-05-20T13:31:51.562599Z","shell.execute_reply":"2023-05-20T13:31:51.671788Z"},"trusted":true},"execution_count":32,"outputs":[{"execution_count":32,"output_type":"execute_result","data":{"text/plain":"OCCUPATION_TYPE\nAccountants              Business Entity Type 3\nCleaning staff           Business Entity Type 3\nCooking staff            Business Entity Type 3\nCore staff               Business Entity Type 3\nDrivers                  Business Entity Type 3\nHR staff                 Business Entity Type 3\nHigh skill tech staff    Business Entity Type 3\nIT staff                 Business Entity Type 3\nLaborers                 Business Entity Type 3\nLow-skill Laborers       Business Entity Type 3\nManagers                 Business Entity Type 3\nMedicine staff                         Medicine\nPrivate service staff             Self-employed\nRealty agents                     Self-employed\nSales staff                       Self-employed\nSecretaries                            Medicine\nSecurity staff                         Security\nWaiters/barmen staff     Business Entity Type 3\nName: ORGANIZATION_TYPE, dtype: object"},"metadata":{}}]},{"cell_type":"code","source":"app_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Accountants') |\n                               (app_train['OCCUPATION_TYPE'] == 'Cleaning staff') |\n                               (app_train['OCCUPATION_TYPE'] == 'Cooking staff') |\n                               (app_train['OCCUPATION_TYPE'] == 'Core staff')|\n                               (app_train['OCCUPATION_TYPE'] == 'Drivers')|\n                               (app_train['OCCUPATION_TYPE'] == 'HR staff')|\n                               (app_train['OCCUPATION_TYPE'] == 'High skill tech staff')|\n                               (app_train['OCCUPATION_TYPE'] == 'IT staff')|\n                               (app_train['OCCUPATION_TYPE'] == 'Laborers')|\n                               (app_train['OCCUPATION_TYPE'] == 'Low-skill Laborers')|\n                               (app_train['OCCUPATION_TYPE'] == 'Managers')] = app_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Accountants') |\n                               (app_train['OCCUPATION_TYPE'] == 'Cleaning staff') |\n                                                                                                             (app_train['OCCUPATION_TYPE'] == 'Cooking staff') |\n                                                                                                             (app_train['OCCUPATION_TYPE'] == 'Core staff')|\n                                                                                                             (app_train['OCCUPATION_TYPE'] == 'Drivers')|\n                                                                                                             (app_train['OCCUPATION_TYPE'] == 'HR staff')|\n                                                                                                             (app_train['OCCUPATION_TYPE'] == 'High skill tech staff')|\n                                                                                                             (app_train['OCCUPATION_TYPE'] == 'IT staff')|\n                                                                                                             (app_train['OCCUPATION_TYPE'] == 'Laborers')|\n                                                                                                             (app_train['OCCUPATION_TYPE'] == 'Low-skill Laborers')|\n                                                                                                              (app_train['OCCUPATION_TYPE'] == 'Managers')].fillna('Business Entity Type 3')\n\napp_test['ORGANIZATION_TYPE'][(app_test['OCCUPATION_TYPE'] == 'Accountants') |\n                               (app_test['OCCUPATION_TYPE'] == 'Cleaning staff') |\n                               (app_test['OCCUPATION_TYPE'] == 'Cooking staff') |\n                               (app_test['OCCUPATION_TYPE'] == 'Core staff')|\n                               (app_test['OCCUPATION_TYPE'] == 'Drivers')|\n                               (app_test['OCCUPATION_TYPE'] == 'HR staff')|\n                               (app_test['OCCUPATION_TYPE'] == 'High skill tech staff')|\n                              (app_test['OCCUPATION_TYPE'] == 'IT staff')|\n                               (app_test['OCCUPATION_TYPE'] == 'Laborers')|\n                               (app_test['OCCUPATION_TYPE'] == 'Low-skill Laborers')|\n                               (app_test['OCCUPATION_TYPE'] == 'Managers')] = app_test['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Accountants') |\n                                                                                                            (app_test['OCCUPATION_TYPE'] == 'Cleaning staff') |\n                                                                                                            (app_test['OCCUPATION_TYPE'] == 'Cooking staff') |\n                                                                                                            (app_test['OCCUPATION_TYPE'] == 'Core staff')|\n                                                                                                            (app_test['OCCUPATION_TYPE'] == 'Drivers')|\n                                                                                                            (app_test['OCCUPATION_TYPE'] == 'HR staff')|\n                                                                                                            (app_test['OCCUPATION_TYPE'] == 'High skill tech staff')|\n                                                                                                            (app_test['OCCUPATION_TYPE'] == 'IT staff')|\n                                                                                                            (app_test['OCCUPATION_TYPE'] == 'Laborers')|\n                                                                                                            (app_test['OCCUPATION_TYPE'] == 'Low-skill Laborers')|\n                                                                                                            (app_test['OCCUPATION_TYPE'] == 'Managers')].fillna('Business Entity Type 3')\n\n\napp_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Medicine staff')|\n                              (app_train['OCCUPATION_TYPE'] == 'Secretaries')] = app_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Medicine staff')|\n                                                                                                                  (app_train['OCCUPATION_TYPE'] == 'Secretaries')].fillna('Medicine')\napp_test['ORGANIZATION_TYPE'][(app_test['OCCUPATION_TYPE'] == 'Medicine staff')|\n                              (app_test['OCCUPATION_TYPE'] == 'Secretaries')] = app_test['ORGANIZATION_TYPE'][(app_test['OCCUPATION_TYPE'] == 'Medicine staff')|\n                                                                                                                  (app_test['OCCUPATION_TYPE'] == 'Secretaries')].fillna('Medicine')\napp_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Private service staff')|\n                               (app_train['OCCUPATION_TYPE'] == 'Realty agents')|\n                               (app_train['OCCUPATION_TYPE'] == 'Sales staff')] = app_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Private service staff')|\n                             (app_train['OCCUPATION_TYPE'] == 'Realty agents')|\n                                                                                                                 (app_train['OCCUPATION_TYPE'] == 'Sales staff')].fillna('Self-employed')\napp_test['ORGANIZATION_TYPE'][(app_test['OCCUPATION_TYPE'] == 'Private service staff')|\n                               (app_test['OCCUPATION_TYPE'] == 'Realty agents')|\n                               (app_test['OCCUPATION_TYPE'] == 'Sales staff')] = app_test['ORGANIZATION_TYPE'][(app_test['OCCUPATION_TYPE'] == 'Private service staff')|\n                                                                                                                 (app_test['OCCUPATION_TYPE'] == 'Realty agents')|\n                                                                                                                 (app_test['OCCUPATION_TYPE'] == 'Sales staff')].fillna('Self-employed')\n\napp_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Security staff')] = app_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Security staff')].fillna('Security')\napp_test['ORGANIZATION_TYPE'][(app_test['OCCUPATION_TYPE'] == 'Security staff')] = app_test['ORGANIZATION_TYPE'][(app_test['OCCUPATION_TYPE'] == 'Security staff')].fillna('Security')\n","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:51.674754Z","iopub.execute_input":"2023-05-20T13:31:51.675082Z","iopub.status.idle":"2023-05-20T13:31:54.946220Z","shell.execute_reply.started":"2023-05-20T13:31:51.675055Z","shell.execute_reply":"2023-05-20T13:31:54.945034Z"},"trusted":true},"execution_count":33,"outputs":[{"name":"stderr","text":"/tmp/ipykernel_34/1284962101.py:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Accountants') |\n/tmp/ipykernel_34/1284962101.py:1: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Accountants') |\n/tmp/ipykernel_34/1284962101.py:23: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_test['ORGANIZATION_TYPE'][(app_test['OCCUPATION_TYPE'] == 'Accountants') |\n/tmp/ipykernel_34/1284962101.py:46: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Medicine staff')|\n/tmp/ipykernel_34/1284962101.py:46: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Medicine staff')|\n/tmp/ipykernel_34/1284962101.py:49: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_test['ORGANIZATION_TYPE'][(app_test['OCCUPATION_TYPE'] == 'Medicine staff')|\n/tmp/ipykernel_34/1284962101.py:52: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Private service staff')|\n/tmp/ipykernel_34/1284962101.py:52: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Private service staff')|\n/tmp/ipykernel_34/1284962101.py:57: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_test['ORGANIZATION_TYPE'][(app_test['OCCUPATION_TYPE'] == 'Private service staff')|\n/tmp/ipykernel_34/1284962101.py:63: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Security staff')] = app_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Security staff')].fillna('Security')\n/tmp/ipykernel_34/1284962101.py:63: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Security staff')] = app_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Security staff')].fillna('Security')\n/tmp/ipykernel_34/1284962101.py:64: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_test['ORGANIZATION_TYPE'][(app_test['OCCUPATION_TYPE'] == 'Security staff')] = app_test['ORGANIZATION_TYPE'][(app_test['OCCUPATION_TYPE'] == 'Security staff')].fillna('Security')\n","output_type":"stream"}]},{"cell_type":"code","source":"app_test['ORGANIZATION_TYPE'] = app_test['ORGANIZATION_TYPE'].fillna(app_test['ORGANIZATION_TYPE'].mode()[0])","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:54.947527Z","iopub.execute_input":"2023-05-20T13:31:54.947839Z","iopub.status.idle":"2023-05-20T13:31:54.974412Z","shell.execute_reply.started":"2023-05-20T13:31:54.947813Z","shell.execute_reply":"2023-05-20T13:31:54.973234Z"},"trusted":true},"execution_count":34,"outputs":[]},{"cell_type":"code","source":"app_test['EXT_SOURCE_3'] = app_test['EXT_SOURCE_3'].fillna(app_train.groupby(['OCCUPATION_TYPE'])['EXT_SOURCE_3'].transform('mean'))\napp_train['EXT_SOURCE_3'] = app_train['EXT_SOURCE_3'].fillna(app_train.groupby(['OCCUPATION_TYPE'])['EXT_SOURCE_3'].transform('mean'))","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:54.975857Z","iopub.execute_input":"2023-05-20T13:31:54.976259Z","iopub.status.idle":"2023-05-20T13:31:55.083771Z","shell.execute_reply.started":"2023-05-20T13:31:54.976218Z","shell.execute_reply":"2023-05-20T13:31:55.082671Z"},"trusted":true},"execution_count":35,"outputs":[{"name":"stderr","text":"/tmp/ipykernel_34/1368104461.py:2: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['EXT_SOURCE_3'] = app_train['EXT_SOURCE_3'].fillna(app_train.groupby(['OCCUPATION_TYPE'])['EXT_SOURCE_3'].transform('mean'))\n","output_type":"stream"}]},{"cell_type":"code","source":"app_test['DAYS_EMPLOYED'] = app_test['DAYS_EMPLOYED'].fillna(app_train.groupby(['OCCUPATION_TYPE'])['DAYS_EMPLOYED'].transform('mean'))\napp_train['DAYS_EMPLOYED'] = app_train['DAYS_EMPLOYED'].fillna(app_train.groupby(['OCCUPATION_TYPE'])['DAYS_EMPLOYED'].transform('mean'))","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:55.085250Z","iopub.execute_input":"2023-05-20T13:31:55.085687Z","iopub.status.idle":"2023-05-20T13:31:55.190547Z","shell.execute_reply.started":"2023-05-20T13:31:55.085650Z","shell.execute_reply":"2023-05-20T13:31:55.189369Z"},"trusted":true},"execution_count":36,"outputs":[{"name":"stderr","text":"/tmp/ipykernel_34/1216194966.py:2: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  app_train['DAYS_EMPLOYED'] = app_train['DAYS_EMPLOYED'].fillna(app_train.groupby(['OCCUPATION_TYPE'])['DAYS_EMPLOYED'].transform('mean'))\n","output_type":"stream"}]},{"cell_type":"code","source":"proper_days_empolyed_df = app_train\nproper_days_empolyed_df['YEARS_EMPLOYED'] = proper_days_empolyed_df['DAYS_EMPLOYED']/-365.25","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:55.192017Z","iopub.execute_input":"2023-05-20T13:31:55.192859Z","iopub.status.idle":"2023-05-20T13:31:55.231641Z","shell.execute_reply.started":"2023-05-20T13:31:55.192829Z","shell.execute_reply":"2023-05-20T13:31:55.230479Z"},"trusted":true},"execution_count":37,"outputs":[]},{"cell_type":"code","source":"app_test['NAME_TYPE_SUITE'].replace({'Other_A':'Other','Other_B':'Other','Group of people':'Other'},inplace=True)\napp_train['NAME_TYPE_SUITE'].replace({'Other_A':'Other','Other_B':'Other','Group of people':'Other'},inplace=True)\n\napp_test['NAME_INCOME_TYPE'].replace({'Unemployed':'Other','Student':'Other','Maternity leave':'Other'},inplace=True)\napp_train['NAME_INCOME_TYPE'].replace({'Unemployed':'Other','Student':'Other','Maternity leave':'Other'},inplace=True)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:55.234321Z","iopub.execute_input":"2023-05-20T13:31:55.235212Z","iopub.status.idle":"2023-05-20T13:31:55.434371Z","shell.execute_reply.started":"2023-05-20T13:31:55.235171Z","shell.execute_reply":"2023-05-20T13:31:55.433495Z"},"trusted":true},"execution_count":38,"outputs":[]},{"cell_type":"code","source":"app_train['ORGANIZATION_TYPE'].value_counts(normalize = True)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:55.436251Z","iopub.execute_input":"2023-05-20T13:31:55.437101Z","iopub.status.idle":"2023-05-20T13:31:55.501346Z","shell.execute_reply.started":"2023-05-20T13:31:55.437061Z","shell.execute_reply":"2023-05-20T13:31:55.500108Z"},"trusted":true},"execution_count":39,"outputs":[{"execution_count":39,"output_type":"execute_result","data":{"text/plain":"Business Entity Type 3    0.401174\nSelf-employed             0.124913\nOther                     0.054252\nMedicine                  0.036399\nBusiness Entity Type 2    0.034318\nGovernment                0.033833\nSchool                    0.028919\nTrade: type 7             0.025466\nKindergarten              0.022373\nConstruction              0.021856\nBusiness Entity Type 1    0.019460\nTransport: type 4         0.017554\nTrade: type 3             0.011356\nIndustry: type 9          0.010952\nIndustry: type 3          0.010660\nSecurity                  0.010559\nHousing                   0.009619\nIndustry: type 11         0.008793\nMilitary                  0.008566\nBank                      0.008153\nAgriculture               0.007980\nPolice                    0.007613\nTransport: type 2         0.007167\nPostal                    0.007014\nSecurity Ministries       0.006419\nTrade: type 2             0.006179\nRestaurant                0.005889\nServices                  0.005122\nUniversity                0.004315\nIndustry: type 7          0.004250\nTransport: type 3         0.003860\nIndustry: type 1          0.003379\nHotel                     0.003141\nElectricity               0.003089\nIndustry: type 4          0.002852\nTrade: type 6             0.002052\nIndustry: type 5          0.001948\nInsurance                 0.001941\nTelecom                   0.001876\nEmergency                 0.001821\nIndustry: type 2          0.001489\nAdvertising               0.001395\nRealtor                   0.001288\nCulture                   0.001232\nIndustry: type 12         0.001200\nTrade: type 1             0.001132\nMobile                    0.001031\nLegal Services            0.000992\nCleaning                  0.000846\nTransport: type 1         0.000654\nIndustry: type 6          0.000364\nIndustry: type 10         0.000354\nReligion                  0.000276\nIndustry: type 13         0.000218\nTrade: type 4             0.000208\nTrade: type 5             0.000159\nIndustry: type 8          0.000078\nName: ORGANIZATION_TYPE, dtype: float64"},"metadata":{}}]},{"cell_type":"code","source":"others = app_train['ORGANIZATION_TYPE'].value_counts().index[15:]\nlabel = 'Others'\napp_train['ORGANIZATION_TYPE'] = app_train['ORGANIZATION_TYPE'].replace(others, label)\napp_test['ORGANIZATION_TYPE'] = app_test['ORGANIZATION_TYPE'].replace(others, label)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:55.502602Z","iopub.execute_input":"2023-05-20T13:31:55.502923Z","iopub.status.idle":"2023-05-20T13:31:56.509256Z","shell.execute_reply.started":"2023-05-20T13:31:55.502892Z","shell.execute_reply":"2023-05-20T13:31:56.508173Z"},"trusted":true},"execution_count":40,"outputs":[]},{"cell_type":"code","source":"app_train['ORGANIZATION_TYPE'].unique()\n","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:56.510708Z","iopub.execute_input":"2023-05-20T13:31:56.511016Z","iopub.status.idle":"2023-05-20T13:31:56.549295Z","shell.execute_reply.started":"2023-05-20T13:31:56.510991Z","shell.execute_reply":"2023-05-20T13:31:56.548208Z"},"trusted":true},"execution_count":41,"outputs":[{"execution_count":41,"output_type":"execute_result","data":{"text/plain":"array(['Business Entity Type 3', 'School', 'Government', 'Others',\n       'Other', 'Medicine', 'Business Entity Type 2', 'Self-employed',\n       'Construction', 'Kindergarten', 'Trade: type 7',\n       'Transport: type 4', 'Business Entity Type 1', 'Trade: type 3',\n       'Industry: type 3', 'Industry: type 9'], dtype=object)"},"metadata":{}}]},{"cell_type":"code","source":"users_nan = (app_train.isnull().sum() / app_train.shape[0]) * 100\nusers_nan[users_nan > 0].sort_values(ascending=False)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:56.550454Z","iopub.execute_input":"2023-05-20T13:31:56.550773Z","iopub.status.idle":"2023-05-20T13:31:57.723469Z","shell.execute_reply.started":"2023-05-20T13:31:56.550746Z","shell.execute_reply":"2023-05-20T13:31:57.722427Z"},"trusted":true},"execution_count":42,"outputs":[{"execution_count":42,"output_type":"execute_result","data":{"text/plain":"Series([], dtype: float64)"},"metadata":{}}]},{"cell_type":"code","source":"users_nan = (app_test.isnull().sum() / app_test.shape[0]) * 100\nusers_nan[users_nan > 0].sort_values(ascending=False)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:57.725183Z","iopub.execute_input":"2023-05-20T13:31:57.725953Z","iopub.status.idle":"2023-05-20T13:31:57.925230Z","shell.execute_reply.started":"2023-05-20T13:31:57.725913Z","shell.execute_reply":"2023-05-20T13:31:57.924092Z"},"trusted":true},"execution_count":43,"outputs":[{"execution_count":43,"output_type":"execute_result","data":{"text/plain":"Series([], dtype: float64)"},"metadata":{}}]},{"cell_type":"code","source":"app_train.drop(['YEARS_EMPLOYED'], axis = 1,inplace=True)\n","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:57.927062Z","iopub.execute_input":"2023-05-20T13:31:57.927525Z","iopub.status.idle":"2023-05-20T13:31:58.035594Z","shell.execute_reply.started":"2023-05-20T13:31:57.927486Z","shell.execute_reply":"2023-05-20T13:31:58.034266Z"},"trusted":true},"execution_count":44,"outputs":[]},{"cell_type":"code","source":"print(app_train['TARGET'].isnull().sum())\n","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:58.037233Z","iopub.execute_input":"2023-05-20T13:31:58.038015Z","iopub.status.idle":"2023-05-20T13:31:58.047706Z","shell.execute_reply.started":"2023-05-20T13:31:58.037972Z","shell.execute_reply":"2023-05-20T13:31:58.046882Z"},"trusted":true},"execution_count":45,"outputs":[{"name":"stdout","text":"0\n","output_type":"stream"}]},{"cell_type":"code","source":"app_train = app_train.drop(columns=['CNT_FAM_MEMBERS','LIVE_REGION_NOT_WORK_REGION', 'REG_REGION_NOT_WORK_REGION', 'OBS_60_CNT_SOCIAL_CIRCLE'])\napp_test = app_test.drop(columns=['CNT_FAM_MEMBERS','LIVE_REGION_NOT_WORK_REGION', 'REG_REGION_NOT_WORK_REGION', 'OBS_60_CNT_SOCIAL_CIRCLE'])","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:58.048606Z","iopub.execute_input":"2023-05-20T13:31:58.048903Z","iopub.status.idle":"2023-05-20T13:31:58.151234Z","shell.execute_reply.started":"2023-05-20T13:31:58.048879Z","shell.execute_reply":"2023-05-20T13:31:58.150364Z"},"trusted":true},"execution_count":46,"outputs":[]},{"cell_type":"code","source":"cols_to_remove = ['AMT_CREDIT', 'CNT_FAM_MEMBERS', 'REG_REGION_NOT_WORK_REGION', 'LIVE_REGION_NOT_WORK_REGION', 'OBS_60_CNT_SOCIAL_CIRCLE','SK_ID_CURR']\ncont_cols = list(set(cont_cols) - set(cols_to_remove))\ncont_cols ","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:58.152637Z","iopub.execute_input":"2023-05-20T13:31:58.153738Z","iopub.status.idle":"2023-05-20T13:31:58.162682Z","shell.execute_reply.started":"2023-05-20T13:31:58.153698Z","shell.execute_reply":"2023-05-20T13:31:58.161609Z"},"trusted":true},"execution_count":47,"outputs":[{"execution_count":47,"output_type":"execute_result","data":{"text/plain":"['REGION_RATING_CLIENT',\n 'AMT_GOODS_PRICE',\n 'OBS_30_CNT_SOCIAL_CIRCLE',\n 'AMT_REQ_CREDIT_BUREAU_QRT',\n 'AMT_REQ_CREDIT_BUREAU_YEAR',\n 'DEF_60_CNT_SOCIAL_CIRCLE',\n 'REGION_RATING_CLIENT_W_CITY',\n 'DEF_30_CNT_SOCIAL_CIRCLE',\n 'REGION_POPULATION_RELATIVE',\n 'AMT_REQ_CREDIT_BUREAU_DAY',\n 'AMT_ANNUITY',\n 'DAYS_BIRTH',\n 'DAYS_REGISTRATION',\n 'EXT_SOURCE_3',\n 'DAYS_EMPLOYED',\n 'AMT_REQ_CREDIT_BUREAU_WEEK',\n 'REG_CITY_NOT_LIVE_CITY',\n 'DAYS_ID_PUBLISH',\n 'AMT_REQ_CREDIT_BUREAU_HOUR',\n 'AMT_INCOME_TOTAL',\n 'AMT_REQ_CREDIT_BUREAU_MON',\n 'DAYS_LAST_PHONE_CHANGE',\n 'EXT_SOURCE_2',\n 'REG_REGION_NOT_LIVE_REGION',\n 'REG_CITY_NOT_WORK_CITY',\n 'LIVE_CITY_NOT_WORK_CITY',\n 'CNT_CHILDREN',\n 'HOUR_APPR_PROCESS_START']"},"metadata":{}}]},{"cell_type":"code","source":"#Для этого использовался метод межквартильного размаха (IQR), который вычисляет разницу между 75-м и 25-м процентилями значений столбца. \n#Затем значения, выходящие за пределы диапазона от Q1-1.5IQR до Q3+1.5IQR, были заменены на медианные значения. \n#Это позволило удалить выбросы, которые могли бы исказить результаты анализа\ndef impute_outliers_IQR(df):\n\n    q1=df.quantile(0.25)\n    q3=df.quantile(0.75)\n\n    IQR=q3-q1\n\n    upper = df[~(df>(q3+1.5*IQR))].max()\n    lower = df[~(df<(q1-1.5*IQR))].min()\n\n    df = np.where(df > upper, df.quantile(0.8), np.where(df < lower, df.quantile(0.2),df))\n\n    return df","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:58.164060Z","iopub.execute_input":"2023-05-20T13:31:58.164735Z","iopub.status.idle":"2023-05-20T13:31:58.181015Z","shell.execute_reply.started":"2023-05-20T13:31:58.164703Z","shell.execute_reply":"2023-05-20T13:31:58.179873Z"},"trusted":true},"execution_count":48,"outputs":[]},{"cell_type":"code","source":"for i in cont_cols:\n    app_train[i] = impute_outliers_IQR(app_train[i])\n    app_test[i] = impute_outliers_IQR(app_test[i])","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:58.182750Z","iopub.execute_input":"2023-05-20T13:31:58.183609Z","iopub.status.idle":"2023-05-20T13:31:59.695503Z","shell.execute_reply.started":"2023-05-20T13:31:58.183567Z","shell.execute_reply":"2023-05-20T13:31:59.694372Z"},"trusted":true},"execution_count":49,"outputs":[]},{"cell_type":"code","source":"app_train['LTV'] = app_train['AMT_CREDIT']/app_train['AMT_GOODS_PRICE']\napp_train['DTI'] = app_train['AMT_ANNUITY']/app_train['AMT_INCOME_TOTAL']\napp_train['Employed/Birth'] = app_train['DAYS_EMPLOYED']/app_train['DAYS_BIRTH'] \napp_train['Flag_Greater_30'] = (app_train['DAYS_BIRTH']/-365.25).apply(lambda x: 1 if x > 30 else 0)\napp_train['Flag_Employment_Greater_5'] = (app_train['DAYS_EMPLOYED']/-365.25).apply(lambda x: 1 if x > 5 else 0)\n\napp_test['LTV'] = app_test['AMT_CREDIT']/app_test['AMT_GOODS_PRICE']\napp_test['DTI'] = app_test['AMT_ANNUITY']/app_test['AMT_INCOME_TOTAL']\napp_test['Employed/Birth'] = app_test['DAYS_EMPLOYED']/app_test['DAYS_BIRTH']\napp_test['Flag_Greater_30'] = (app_test['DAYS_BIRTH']/-365.25).apply(lambda x: 1 if x > 30 else 0)\napp_test['Flag_Employment_Greater_5'] = (app_test['DAYS_EMPLOYED']/-365.25).apply(lambda x: 1 if x > 5 else 0)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:31:59.697231Z","iopub.execute_input":"2023-05-20T13:31:59.697622Z","iopub.status.idle":"2023-05-20T13:32:00.311447Z","shell.execute_reply.started":"2023-05-20T13:31:59.697588Z","shell.execute_reply":"2023-05-20T13:32:00.310304Z"},"trusted":true},"execution_count":50,"outputs":[]},{"cell_type":"code","source":"# for pre-processing\n\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom category_encoders import TargetEncoder \nfrom sklearn.model_selection import train_test_split, GridSearchCV, RandomizedSearchCV\n\n# for machine learning modelling\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier\nfrom sklearn.metrics import roc_auc_score, confusion_matrix","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:32:00.312874Z","iopub.execute_input":"2023-05-20T13:32:00.313206Z","iopub.status.idle":"2023-05-20T13:32:01.567866Z","shell.execute_reply.started":"2023-05-20T13:32:00.313179Z","shell.execute_reply":"2023-05-20T13:32:01.566680Z"},"trusted":true},"execution_count":51,"outputs":[]},{"cell_type":"code","source":"app_train[cat_col.columns]\n","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:32:01.569400Z","iopub.execute_input":"2023-05-20T13:32:01.570062Z","iopub.status.idle":"2023-05-20T13:32:01.829177Z","shell.execute_reply.started":"2023-05-20T13:32:01.570028Z","shell.execute_reply":"2023-05-20T13:32:01.828041Z"},"trusted":true},"execution_count":52,"outputs":[{"execution_count":52,"output_type":"execute_result","data":{"text/plain":"       NAME_CONTRACT_TYPE CODE_GENDER FLAG_OWN_CAR FLAG_OWN_REALTY  \\\n0              Cash loans           M            N               Y   \n1              Cash loans           F            N               N   \n2         Revolving loans           M            Y               Y   \n3              Cash loans           F            N               Y   \n4              Cash loans           M            N               Y   \n...                   ...         ...          ...             ...   \n307506         Cash loans           M            N               N   \n307507         Cash loans           F            N               Y   \n307508         Cash loans           F            N               Y   \n307509         Cash loans           F            N               Y   \n307510         Cash loans           F            N               N   \n\n       NAME_TYPE_SUITE      NAME_INCOME_TYPE            NAME_EDUCATION_TYPE  \\\n0        Unaccompanied               Working  Secondary / secondary special   \n1               Family         State servant               Higher education   \n2        Unaccompanied               Working  Secondary / secondary special   \n3        Unaccompanied               Working  Secondary / secondary special   \n4        Unaccompanied               Working  Secondary / secondary special   \n...                ...                   ...                            ...   \n307506   Unaccompanied               Working  Secondary / secondary special   \n307507   Unaccompanied             Pensioner  Secondary / secondary special   \n307508   Unaccompanied               Working               Higher education   \n307509   Unaccompanied  Commercial associate  Secondary / secondary special   \n307510   Unaccompanied  Commercial associate               Higher education   \n\n          NAME_FAMILY_STATUS  NAME_HOUSING_TYPE OCCUPATION_TYPE  \\\n0       Single / not married  House / apartment        Laborers   \n1                    Married  House / apartment      Core staff   \n2       Single / not married  House / apartment        Laborers   \n3             Civil marriage  House / apartment        Laborers   \n4       Single / not married  House / apartment      Core staff   \n...                      ...                ...             ...   \n307506             Separated       With parents     Sales staff   \n307507                 Widow  House / apartment        Laborers   \n307508             Separated  House / apartment        Managers   \n307509               Married  House / apartment        Laborers   \n307510               Married  House / apartment        Laborers   \n\n       WEEKDAY_APPR_PROCESS_START       ORGANIZATION_TYPE  \n0                       WEDNESDAY  Business Entity Type 3  \n1                          MONDAY                  School  \n2                          MONDAY              Government  \n3                       WEDNESDAY  Business Entity Type 3  \n4                        THURSDAY                  Others  \n...                           ...                     ...  \n307506                   THURSDAY                  Others  \n307507                     MONDAY  Business Entity Type 3  \n307508                   THURSDAY                  School  \n307509                  WEDNESDAY  Business Entity Type 1  \n307510                   THURSDAY  Business Entity Type 3  \n\n[307510 rows x 12 columns]","text/html":"<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>NAME_CONTRACT_TYPE</th>\n      <th>CODE_GENDER</th>\n      <th>FLAG_OWN_CAR</th>\n      <th>FLAG_OWN_REALTY</th>\n      <th>NAME_TYPE_SUITE</th>\n      <th>NAME_INCOME_TYPE</th>\n      <th>NAME_EDUCATION_TYPE</th>\n      <th>NAME_FAMILY_STATUS</th>\n      <th>NAME_HOUSING_TYPE</th>\n      <th>OCCUPATION_TYPE</th>\n      <th>WEEKDAY_APPR_PROCESS_START</th>\n      <th>ORGANIZATION_TYPE</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>Cash loans</td>\n      <td>M</td>\n      <td>N</td>\n      <td>Y</td>\n      <td>Unaccompanied</td>\n      <td>Working</td>\n      <td>Secondary / secondary special</td>\n      <td>Single / not married</td>\n      <td>House / apartment</td>\n      <td>Laborers</td>\n      <td>WEDNESDAY</td>\n      <td>Business Entity Type 3</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>Cash loans</td>\n      <td>F</td>\n      <td>N</td>\n      <td>N</td>\n      <td>Family</td>\n      <td>State servant</td>\n      <td>Higher education</td>\n      <td>Married</td>\n      <td>House / apartment</td>\n      <td>Core staff</td>\n      <td>MONDAY</td>\n      <td>School</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>Revolving loans</td>\n      <td>M</td>\n      <td>Y</td>\n      <td>Y</td>\n      <td>Unaccompanied</td>\n      <td>Working</td>\n      <td>Secondary / secondary special</td>\n      <td>Single / not married</td>\n      <td>House / apartment</td>\n      <td>Laborers</td>\n      <td>MONDAY</td>\n      <td>Government</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>Cash loans</td>\n      <td>F</td>\n      <td>N</td>\n      <td>Y</td>\n      <td>Unaccompanied</td>\n      <td>Working</td>\n      <td>Secondary / secondary special</td>\n      <td>Civil marriage</td>\n      <td>House / apartment</td>\n      <td>Laborers</td>\n      <td>WEDNESDAY</td>\n      <td>Business Entity Type 3</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>Cash loans</td>\n      <td>M</td>\n      <td>N</td>\n      <td>Y</td>\n      <td>Unaccompanied</td>\n      <td>Working</td>\n      <td>Secondary / secondary special</td>\n      <td>Single / not married</td>\n      <td>House / apartment</td>\n      <td>Core staff</td>\n      <td>THURSDAY</td>\n      <td>Others</td>\n    </tr>\n    <tr>\n      <th>...</th>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n      <td>...</td>\n    </tr>\n    <tr>\n      <th>307506</th>\n      <td>Cash loans</td>\n      <td>M</td>\n      <td>N</td>\n      <td>N</td>\n      <td>Unaccompanied</td>\n      <td>Working</td>\n      <td>Secondary / secondary special</td>\n      <td>Separated</td>\n      <td>With parents</td>\n      <td>Sales staff</td>\n      <td>THURSDAY</td>\n      <td>Others</td>\n    </tr>\n    <tr>\n      <th>307507</th>\n      <td>Cash loans</td>\n      <td>F</td>\n      <td>N</td>\n      <td>Y</td>\n      <td>Unaccompanied</td>\n      <td>Pensioner</td>\n      <td>Secondary / secondary special</td>\n      <td>Widow</td>\n      <td>House / apartment</td>\n      <td>Laborers</td>\n      <td>MONDAY</td>\n      <td>Business Entity Type 3</td>\n    </tr>\n    <tr>\n      <th>307508</th>\n      <td>Cash loans</td>\n      <td>F</td>\n      <td>N</td>\n      <td>Y</td>\n      <td>Unaccompanied</td>\n      <td>Working</td>\n      <td>Higher education</td>\n      <td>Separated</td>\n      <td>House / apartment</td>\n      <td>Managers</td>\n      <td>THURSDAY</td>\n      <td>School</td>\n    </tr>\n    <tr>\n      <th>307509</th>\n      <td>Cash loans</td>\n      <td>F</td>\n      <td>N</td>\n      <td>Y</td>\n      <td>Unaccompanied</td>\n      <td>Commercial associate</td>\n      <td>Secondary / secondary special</td>\n      <td>Married</td>\n      <td>House / apartment</td>\n      <td>Laborers</td>\n      <td>WEDNESDAY</td>\n      <td>Business Entity Type 1</td>\n    </tr>\n    <tr>\n      <th>307510</th>\n      <td>Cash loans</td>\n      <td>F</td>\n      <td>N</td>\n      <td>N</td>\n      <td>Unaccompanied</td>\n      <td>Commercial associate</td>\n      <td>Higher education</td>\n      <td>Married</td>\n      <td>House / apartment</td>\n      <td>Laborers</td>\n      <td>THURSDAY</td>\n      <td>Business Entity Type 3</td>\n    </tr>\n  </tbody>\n</table>\n<p>307510 rows × 12 columns</p>\n</div>"},"metadata":{}}]},{"cell_type":"code","source":"enc = TargetEncoder()\napp_train[cat_col.columns] = enc.fit_transform(app_train[cat_col.columns], app_train['TARGET'])","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:32:01.830416Z","iopub.execute_input":"2023-05-20T13:32:01.830751Z","iopub.status.idle":"2023-05-20T13:32:09.292612Z","shell.execute_reply.started":"2023-05-20T13:32:01.830722Z","shell.execute_reply":"2023-05-20T13:32:09.291189Z"},"trusted":true},"execution_count":53,"outputs":[]},{"cell_type":"code","source":"app_test[cat_col.columns] = enc.transform(app_test[cat_col.columns])","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:32:09.294260Z","iopub.execute_input":"2023-05-20T13:32:09.294612Z","iopub.status.idle":"2023-05-20T13:32:09.649759Z","shell.execute_reply.started":"2023-05-20T13:32:09.294582Z","shell.execute_reply":"2023-05-20T13:32:09.648611Z"},"trusted":true},"execution_count":54,"outputs":[]},{"cell_type":"code","source":"X = app_train.drop(columns=['TARGET','SK_ID_CURR'])\ny = app_train['TARGET']","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:32:09.650994Z","iopub.execute_input":"2023-05-20T13:32:09.651347Z","iopub.status.idle":"2023-05-20T13:32:09.716602Z","shell.execute_reply.started":"2023-05-20T13:32:09.651317Z","shell.execute_reply":"2023-05-20T13:32:09.715380Z"},"trusted":true},"execution_count":55,"outputs":[]},{"cell_type":"code","source":"X_train, X_val, y_train, y_val = train_test_split(X, y, train_size=0.8, stratify=y, random_state=42)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:32:09.717870Z","iopub.execute_input":"2023-05-20T13:32:09.718228Z","iopub.status.idle":"2023-05-20T13:32:10.128936Z","shell.execute_reply.started":"2023-05-20T13:32:09.718200Z","shell.execute_reply":"2023-05-20T13:32:10.127890Z"},"trusted":true},"execution_count":56,"outputs":[]},{"cell_type":"code","source":"# create a function for trained models evaluation\ndef evaluate_model(model):\n    # prediction\n    train_pred = model.predict(X_train)\n    test_pred = model.predict(X_val)\n    \n    train_pred_proba = model.predict_proba(X_train)\n    test_pred_proba = model.predict_proba(X_val)\n    \n    # evaluations\n    print('Training & Validation ROC AUC Scores:\\n', '-'*40)\n    print('Training   roc auc score= {:.4f}'.format(roc_auc_score(y_train, train_pred_proba[:, 1])))\n    print('Validation roc auc score= {:.4f}'.format(roc_auc_score(y_val, test_pred_proba[:, 1])))\n    print('')\n    print('Training & Validation Confusion Metrices:')\n    print('Training   confusion matrix:\\n', confusion_matrix(y_train, train_pred))\n    print('Validation confusion matrix:\\n', confusion_matrix(y_val, test_pred))","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:32:10.130292Z","iopub.execute_input":"2023-05-20T13:32:10.130697Z","iopub.status.idle":"2023-05-20T13:32:10.138914Z","shell.execute_reply.started":"2023-05-20T13:32:10.130661Z","shell.execute_reply":"2023-05-20T13:32:10.138142Z"},"trusted":true},"execution_count":57,"outputs":[]},{"cell_type":"code","source":"#В этом коде мы импортируем модуль RandomForestClassifier из библиотеки sklearn.ensemble и создаем объект модели rf. \n#Затем мы обучаем модель на тренировочных данных с помощью метода fit. \n#После этого мы используем модель для предсказания классов на тестовых данных с помощью метода predict. \n#Наконец, мы оцениваем качество модели на тестовых данных с помощью метрик classification_report и confusion_matrix из библиотеки sklearn.metrics.\nrf = RandomForestClassifier(n_estimators=70, max_depth=15, random_state=42)\nrf2 = RandomForestClassifier(n_estimators=100, max_depth=15, random_state=5)\nrf3 = RandomForestClassifier(n_estimators=75, max_depth=15, random_state=30)\nrf4 = RandomForestClassifier(n_estimators=80, max_depth=15, random_state=4)\nrf5 = RandomForestClassifier(n_estimators=110, max_depth=15, random_state=12)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:32:10.140207Z","iopub.execute_input":"2023-05-20T13:32:10.140749Z","iopub.status.idle":"2023-05-20T13:32:10.159266Z","shell.execute_reply.started":"2023-05-20T13:32:10.140719Z","shell.execute_reply":"2023-05-20T13:32:10.158427Z"},"trusted":true},"execution_count":58,"outputs":[]},{"cell_type":"code","source":"rf.fit(X_train, y_train)\n","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:32:10.160630Z","iopub.execute_input":"2023-05-20T13:32:10.161145Z","iopub.status.idle":"2023-05-20T13:33:09.115510Z","shell.execute_reply.started":"2023-05-20T13:32:10.161115Z","shell.execute_reply":"2023-05-20T13:33:09.114353Z"},"trusted":true},"execution_count":59,"outputs":[{"execution_count":59,"output_type":"execute_result","data":{"text/plain":"RandomForestClassifier(max_depth=15, n_estimators=70, random_state=42)","text/html":"<style>#sk-container-id-1 {color: black;background-color: white;}#sk-container-id-1 pre{padding: 0;}#sk-container-id-1 div.sk-toggleable {background-color: white;}#sk-container-id-1 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-1 label.sk-toggleable__label-arrow:before {content: \"\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-1 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-1 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-1 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-1 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-1 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-1 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"\";}#sk-container-id-1 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-1 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-1 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-1 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-1 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-1 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-1 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-1 div.sk-item {position: relative;z-index: 1;}#sk-container-id-1 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-1 div.sk-item::before, #sk-container-id-1 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-1 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-1 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-1 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-1 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-1 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-1 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-1 div.sk-label-container {text-align: center;}#sk-container-id-1 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-1 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-1\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>RandomForestClassifier(max_depth=15, n_estimators=70, random_state=42)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-1\" type=\"checkbox\" checked><label for=\"sk-estimator-id-1\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">RandomForestClassifier</label><div class=\"sk-toggleable__content\"><pre>RandomForestClassifier(max_depth=15, n_estimators=70, random_state=42)</pre></div></div></div></div></div>"},"metadata":{}}]},{"cell_type":"code","source":"evaluate_model(rf)\n","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:33:09.117294Z","iopub.execute_input":"2023-05-20T13:33:09.118112Z","iopub.status.idle":"2023-05-20T13:33:20.276294Z","shell.execute_reply.started":"2023-05-20T13:33:09.118071Z","shell.execute_reply":"2023-05-20T13:33:20.275200Z"},"trusted":true},"execution_count":60,"outputs":[{"name":"stdout","text":"Training & Validation ROC AUC Scores:\n ----------------------------------------\nTraining   roc auc score= 0.9599\nValidation roc auc score= 0.7316\n\nTraining & Validation Confusion Metrices:\nTraining   confusion matrix:\n [[226149      0]\n [ 19299    560]]\nValidation confusion matrix:\n [[56537     0]\n [ 4964     1]]\n","output_type":"stream"}]},{"cell_type":"code","source":"rf.fit(X_train, y_train)\nrf2.fit(X_train, y_train)\nrf3.fit(X_train, y_train)\nrf4.fit(X_train, y_train)\nrf5.fit(X_train, y_train)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:33:20.277500Z","iopub.execute_input":"2023-05-20T13:33:20.277821Z","iopub.status.idle":"2023-05-20T13:39:25.031720Z","shell.execute_reply.started":"2023-05-20T13:33:20.277794Z","shell.execute_reply":"2023-05-20T13:39:25.030569Z"},"trusted":true},"execution_count":61,"outputs":[{"execution_count":61,"output_type":"execute_result","data":{"text/plain":"RandomForestClassifier(max_depth=15, n_estimators=110, random_state=12)","text/html":"<style>#sk-container-id-2 {color: black;background-color: white;}#sk-container-id-2 pre{padding: 0;}#sk-container-id-2 div.sk-toggleable {background-color: white;}#sk-container-id-2 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-2 label.sk-toggleable__label-arrow:before {content: \"\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-2 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-2 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-2 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-2 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-2 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-2 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"\";}#sk-container-id-2 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-2 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-2 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-2 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-2 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-2 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-2 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-2 div.sk-item {position: relative;z-index: 1;}#sk-container-id-2 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-2 div.sk-item::before, #sk-container-id-2 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-2 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-2 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-2 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-2 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-2 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-2 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-2 div.sk-label-container {text-align: center;}#sk-container-id-2 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-2 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-2\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>RandomForestClassifier(max_depth=15, n_estimators=110, random_state=12)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-2\" type=\"checkbox\" checked><label for=\"sk-estimator-id-2\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">RandomForestClassifier</label><div class=\"sk-toggleable__content\"><pre>RandomForestClassifier(max_depth=15, n_estimators=110, random_state=12)</pre></div></div></div></div></div>"},"metadata":{}}]},{"cell_type":"code","source":"y_pred = rf.predict_proba(X_val)\ny_pred2 = rf2.predict_proba(X_val)\ny_pred3 = rf3.predict_proba(X_val)\ny_pred4 = rf4.predict_proba(X_val)\ny_pred5 = rf5.predict_proba(X_val)\n\ny_final = (y_pred+y_pred2+y_pred3+y_pred4+y_pred5)/5","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:39:25.032979Z","iopub.execute_input":"2023-05-20T13:39:25.033314Z","iopub.status.idle":"2023-05-20T13:39:32.327674Z","shell.execute_reply.started":"2023-05-20T13:39:25.033287Z","shell.execute_reply":"2023-05-20T13:39:32.326682Z"},"trusted":true},"execution_count":62,"outputs":[]},{"cell_type":"code","source":"roc_auc_score(y_val,y_final[:, 1])","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:39:32.328806Z","iopub.execute_input":"2023-05-20T13:39:32.329762Z","iopub.status.idle":"2023-05-20T13:39:32.359062Z","shell.execute_reply.started":"2023-05-20T13:39:32.329729Z","shell.execute_reply":"2023-05-20T13:39:32.357891Z"},"trusted":true},"execution_count":63,"outputs":[{"execution_count":63,"output_type":"execute_result","data":{"text/plain":"0.737333643907159"},"metadata":{}}]},{"cell_type":"code","source":"#была обнаружена проблема несбалансированных классов в задаче бинарной классификации. В данных было намного больше объектов с положительным классом (клиенты, вернувшие кредит вовремя) по сравнению с отрицательным классом (клиенты, не вернувшие кредит вовремя).\n#В данном проекте параметр class_weight был установлен в значение \"balanced\". Это значение автоматически вычисляет веса классов, основываясь на их соотношении в данных, и присваивает больший вес редкому классу. \nparam_grid = {'criterion' : ['gini'],\n             'class_weight' : ['balanced_subsample','balanced',None],\n             'max_features' : ['sqrt', 'log2']}\n\nrf2 = RandomForestClassifier(n_estimators=100, max_depth=15, random_state=42)\n\ngrid_cv = RandomizedSearchCV(rf2,param_grid, cv=5,  scoring = 'roc_auc')\n\ngrid_cv.fit(X_train, y_train)\n\ny_pred = grid_cv.predict_proba(X_val)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T13:39:32.360442Z","iopub.execute_input":"2023-05-20T13:39:32.360878Z","iopub.status.idle":"2023-05-20T14:11:50.817174Z","shell.execute_reply.started":"2023-05-20T13:39:32.360850Z","shell.execute_reply":"2023-05-20T14:11:50.815967Z"},"trusted":true},"execution_count":64,"outputs":[{"name":"stderr","text":"/opt/conda/lib/python3.10/site-packages/sklearn/model_selection/_search.py:305: UserWarning: The total space of parameters 6 is smaller than n_iter=10. Running 6 iterations. For exhaustive searches, use GridSearchCV.\n  warnings.warn(\n","output_type":"stream"}]},{"cell_type":"code","source":"roc_auc_score(y_val, y_pred[:, 1])\n","metadata":{"execution":{"iopub.status.busy":"2023-05-20T14:11:50.818505Z","iopub.execute_input":"2023-05-20T14:11:50.818939Z","iopub.status.idle":"2023-05-20T14:11:50.849078Z","shell.execute_reply.started":"2023-05-20T14:11:50.818903Z","shell.execute_reply":"2023-05-20T14:11:50.848229Z"},"trusted":true},"execution_count":65,"outputs":[{"execution_count":65,"output_type":"execute_result","data":{"text/plain":"0.7325700726850695"},"metadata":{}}]},{"cell_type":"code","source":"grid_cv.best_params_ ","metadata":{"execution":{"iopub.status.busy":"2023-05-20T14:11:50.850148Z","iopub.execute_input":"2023-05-20T14:11:50.851110Z","iopub.status.idle":"2023-05-20T14:11:50.858417Z","shell.execute_reply.started":"2023-05-20T14:11:50.851067Z","shell.execute_reply":"2023-05-20T14:11:50.857314Z"},"trusted":true},"execution_count":66,"outputs":[{"execution_count":66,"output_type":"execute_result","data":{"text/plain":"{'max_features': 'sqrt', 'criterion': 'gini', 'class_weight': None}"},"metadata":{}}]},{"cell_type":"code","source":"rf = RandomForestClassifier(max_features= 'sqrt', criterion ='gini', n_estimators=70, max_depth=15, random_state=42)\nrf2 = RandomForestClassifier(max_features= 'sqrt', criterion ='gini',n_estimators=100, max_depth=15, random_state=5)\nrf3 = RandomForestClassifier(max_features= 'sqrt', criterion ='gini', n_estimators=75, max_depth=15, random_state=30)\nrf4 = RandomForestClassifier(max_features= 'sqrt', criterion ='gini', n_estimators=80, max_depth=15, random_state=4)\nrf5 = RandomForestClassifier(max_features= 'sqrt', criterion ='gini', n_estimators=100, max_depth=15, random_state=12)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T14:11:50.859969Z","iopub.execute_input":"2023-05-20T14:11:50.860918Z","iopub.status.idle":"2023-05-20T14:11:50.875775Z","shell.execute_reply.started":"2023-05-20T14:11:50.860885Z","shell.execute_reply":"2023-05-20T14:11:50.874346Z"},"trusted":true},"execution_count":67,"outputs":[]},{"cell_type":"code","source":"rf.fit(X_train, y_train)\nrf2.fit(X_train, y_train)\nrf3.fit(X_train, y_train)\nrf4.fit(X_train, y_train)\nrf5.fit(X_train, y_train)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T14:11:50.877205Z","iopub.execute_input":"2023-05-20T14:11:50.877613Z","iopub.status.idle":"2023-05-20T14:18:18.347330Z","shell.execute_reply.started":"2023-05-20T14:11:50.877581Z","shell.execute_reply":"2023-05-20T14:18:18.346181Z"},"trusted":true},"execution_count":68,"outputs":[{"execution_count":68,"output_type":"execute_result","data":{"text/plain":"RandomForestClassifier(max_depth=15, random_state=12)","text/html":"<style>#sk-container-id-3 {color: black;background-color: white;}#sk-container-id-3 pre{padding: 0;}#sk-container-id-3 div.sk-toggleable {background-color: white;}#sk-container-id-3 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-3 label.sk-toggleable__label-arrow:before {content: \"\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-3 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-3 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-3 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-3 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-3 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-3 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"\";}#sk-container-id-3 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-3 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-3 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-3 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-3 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-3 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-3 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-3 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-3 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-3 div.sk-item {position: relative;z-index: 1;}#sk-container-id-3 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-3 div.sk-item::before, #sk-container-id-3 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-3 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-3 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-3 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-3 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-3 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-3 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-3 div.sk-label-container {text-align: center;}#sk-container-id-3 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-3 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-3\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>RandomForestClassifier(max_depth=15, random_state=12)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-3\" type=\"checkbox\" checked><label for=\"sk-estimator-id-3\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">RandomForestClassifier</label><div class=\"sk-toggleable__content\"><pre>RandomForestClassifier(max_depth=15, random_state=12)</pre></div></div></div></div></div>"},"metadata":{}}]},{"cell_type":"code","source":"y_pred = rf.predict_proba(X_val)\ny_pred2 = rf2.predict_proba(X_val)\ny_pred3 = rf3.predict_proba(X_val)\ny_pred4 = rf4.predict_proba(X_val)\ny_pred5 = rf5.predict_proba(X_val)\n\ny_final = (y_pred+y_pred2+y_pred3+y_pred4+y_pred5)/5","metadata":{"execution":{"iopub.status.busy":"2023-05-20T14:18:18.349232Z","iopub.execute_input":"2023-05-20T14:18:18.349712Z","iopub.status.idle":"2023-05-20T14:18:25.411558Z","shell.execute_reply.started":"2023-05-20T14:18:18.349673Z","shell.execute_reply":"2023-05-20T14:18:25.410246Z"},"trusted":true},"execution_count":69,"outputs":[]},{"cell_type":"code","source":"roc_auc_score(y_val, y_final[:, 1])\n","metadata":{"execution":{"iopub.status.busy":"2023-05-20T14:18:25.412934Z","iopub.execute_input":"2023-05-20T14:18:25.413279Z","iopub.status.idle":"2023-05-20T14:18:25.442617Z","shell.execute_reply.started":"2023-05-20T14:18:25.413252Z","shell.execute_reply":"2023-05-20T14:18:25.441413Z"},"trusted":true},"execution_count":70,"outputs":[{"execution_count":70,"output_type":"execute_result","data":{"text/plain":"0.7373858052051254"},"metadata":{}}]},{"cell_type":"code","source":"test_set_dropID = app_test.drop(columns=['SK_ID_CURR'])\n\ny_pred = rf.predict_proba(test_set_dropID)\ny_pred2 = rf2.predict_proba(test_set_dropID)\ny_pred3 = rf3.predict_proba(test_set_dropID)\ny_pred4 = rf4.predict_proba(test_set_dropID)\ny_pred5 = rf5.predict_proba(test_set_dropID)\n\ntest_proba = (y_pred+y_pred2+y_pred3+y_pred4+y_pred5)/5\n\ntest_proba","metadata":{"execution":{"iopub.status.busy":"2023-05-20T14:18:25.444347Z","iopub.execute_input":"2023-05-20T14:18:25.444762Z","iopub.status.idle":"2023-05-20T14:18:30.865562Z","shell.execute_reply.started":"2023-05-20T14:18:25.444726Z","shell.execute_reply":"2023-05-20T14:18:30.864401Z"},"trusted":true},"execution_count":71,"outputs":[{"execution_count":71,"output_type":"execute_result","data":{"text/plain":"array([[0.9079806 , 0.0920194 ],\n       [0.86266915, 0.13733085],\n       [0.97561494, 0.02438506],\n       ...,\n       [0.92741973, 0.07258027],\n       [0.96528341, 0.03471659],\n       [0.85394154, 0.14605846]])"},"metadata":{}}]},{"cell_type":"code","source":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom imblearn.over_sampling import RandomOverSampler\nfrom imblearn.under_sampling import RandomUnderSampler\nfrom imblearn.pipeline import Pipeline\n\n# Выделение целевой переменной и признаков\ny = app_train['TARGET']\nX = app_train.drop(['TARGET', 'SK_ID_CURR'], axis=1)\n\n# Предобработка данных\nX = pd.get_dummies(X, dummy_na=True)\n\n# Разделение данных на обучающую и тестовую выборки\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\n# Масштабирование признаков\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\n\n# Балансировка классов\nover_sampler = RandomOverSampler(sampling_strategy=0.5, random_state=42)\nunder_sampler = RandomUnderSampler(sampling_strategy=0.5, random_state=42)\nsteps = [('o', over_sampler), ('u', under_sampler)]\npipeline = Pipeline(steps=steps)\nX_train, y_train = pipeline.fit_resample(X_train, y_train)\n\n# Создание и обучение модели логистической регрессии\nlr = LogisticRegression(random_state=42, max_iter=1000)\nlr.fit(X_train, y_train)\n\n# Оценка качества модели\ny_pred = lr.predict(X_test)\nscore = lr.score(X_test, y_test)\nprint(f\"Accuracy: {score:.2f}\")\n\n","metadata":{"execution":{"iopub.status.busy":"2023-05-20T14:18:30.866840Z","iopub.execute_input":"2023-05-20T14:18:30.867184Z","iopub.status.idle":"2023-05-20T14:18:35.987259Z","shell.execute_reply.started":"2023-05-20T14:18:30.867141Z","shell.execute_reply":"2023-05-20T14:18:35.985576Z"},"trusted":true},"execution_count":72,"outputs":[{"name":"stdout","text":"Accuracy: 0.84\n","output_type":"stream"}]},{"cell_type":"code","source":"from sklearn.preprocessing import MinMaxScaler\nfrom sklearn.impute import SimpleImputer\n\n# Уберем таргет из тренировочных данных\nif 'TARGET' in app_train:\n    train = app_train.drop(labels = ['TARGET'], axis=1)\nelse:\n    train = app_train.copy()\nfeatures = list(train.columns)\n\n# копируем тестовые данные\ntest = app_test.copy()\n\n# заполним недостающее по медиане\nimputer = SimpleImputer(strategy = 'median')\n\n# Нормализация\nscaler = MinMaxScaler(feature_range = (0, 1))\n\n# заполнение тренировочной выборки\nimputer.fit(train)\n\n# Трансофрмация тренировочной и тестовой выборок\ntrain = imputer.transform(train)\ntest = imputer.transform(app_test)\n\n# то же самое с нормализацией\nscaler.fit(train)\ntrain = scaler.transform(train)\ntest = scaler.transform(test)\n\nprint('Формат тренировочной выборки: ', train.shape)\nprint('Формат тестовой выборки: ', test.shape)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T14:18:35.994257Z","iopub.execute_input":"2023-05-20T14:18:36.000219Z","iopub.status.idle":"2023-05-20T14:18:39.477868Z","shell.execute_reply.started":"2023-05-20T14:18:36.000123Z","shell.execute_reply":"2023-05-20T14:18:39.476591Z"},"trusted":true},"execution_count":73,"outputs":[{"name":"stdout","text":"Формат тренировочной выборки:  (307510, 73)\nФормат тестовой выборки:  (48744, 73)\n","output_type":"stream"}]},{"cell_type":"code","source":"#сохраним лейблы, их же нет в тестовой выборке и при выравнивании они потеряются. \ntrain_labels = app_train['TARGET']\n","metadata":{"execution":{"iopub.status.busy":"2023-05-20T14:18:39.479177Z","iopub.execute_input":"2023-05-20T14:18:39.479523Z","iopub.status.idle":"2023-05-20T14:18:39.485527Z","shell.execute_reply.started":"2023-05-20T14:18:39.479495Z","shell.execute_reply":"2023-05-20T14:18:39.484180Z"},"trusted":true},"execution_count":74,"outputs":[]},{"cell_type":"code","source":"from sklearn.linear_model import LogisticRegression\n\nlog_reg = LogisticRegression(C = 0.0001)\n\n# Тренируем модель\nlog_reg.fit(train, train_labels)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T14:18:39.487213Z","iopub.execute_input":"2023-05-20T14:18:39.487559Z","iopub.status.idle":"2023-05-20T14:18:41.025224Z","shell.execute_reply.started":"2023-05-20T14:18:39.487524Z","shell.execute_reply":"2023-05-20T14:18:41.023847Z"},"trusted":true},"execution_count":75,"outputs":[{"execution_count":75,"output_type":"execute_result","data":{"text/plain":"LogisticRegression(C=0.0001)","text/html":"<style>#sk-container-id-4 {color: black;background-color: white;}#sk-container-id-4 pre{padding: 0;}#sk-container-id-4 div.sk-toggleable {background-color: white;}#sk-container-id-4 label.sk-toggleable__label {cursor: pointer;display: block;width: 100%;margin-bottom: 0;padding: 0.3em;box-sizing: border-box;text-align: center;}#sk-container-id-4 label.sk-toggleable__label-arrow:before {content: \"\";float: left;margin-right: 0.25em;color: #696969;}#sk-container-id-4 label.sk-toggleable__label-arrow:hover:before {color: black;}#sk-container-id-4 div.sk-estimator:hover label.sk-toggleable__label-arrow:before {color: black;}#sk-container-id-4 div.sk-toggleable__content {max-height: 0;max-width: 0;overflow: hidden;text-align: left;background-color: #f0f8ff;}#sk-container-id-4 div.sk-toggleable__content pre {margin: 0.2em;color: black;border-radius: 0.25em;background-color: #f0f8ff;}#sk-container-id-4 input.sk-toggleable__control:checked~div.sk-toggleable__content {max-height: 200px;max-width: 100%;overflow: auto;}#sk-container-id-4 input.sk-toggleable__control:checked~label.sk-toggleable__label-arrow:before {content: \"\";}#sk-container-id-4 div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-4 div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-4 input.sk-hidden--visually {border: 0;clip: rect(1px 1px 1px 1px);clip: rect(1px, 1px, 1px, 1px);height: 1px;margin: -1px;overflow: hidden;padding: 0;position: absolute;width: 1px;}#sk-container-id-4 div.sk-estimator {font-family: monospace;background-color: #f0f8ff;border: 1px dotted black;border-radius: 0.25em;box-sizing: border-box;margin-bottom: 0.5em;}#sk-container-id-4 div.sk-estimator:hover {background-color: #d4ebff;}#sk-container-id-4 div.sk-parallel-item::after {content: \"\";width: 100%;border-bottom: 1px solid gray;flex-grow: 1;}#sk-container-id-4 div.sk-label:hover label.sk-toggleable__label {background-color: #d4ebff;}#sk-container-id-4 div.sk-serial::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: 0;}#sk-container-id-4 div.sk-serial {display: flex;flex-direction: column;align-items: center;background-color: white;padding-right: 0.2em;padding-left: 0.2em;position: relative;}#sk-container-id-4 div.sk-item {position: relative;z-index: 1;}#sk-container-id-4 div.sk-parallel {display: flex;align-items: stretch;justify-content: center;background-color: white;position: relative;}#sk-container-id-4 div.sk-item::before, #sk-container-id-4 div.sk-parallel-item::before {content: \"\";position: absolute;border-left: 1px solid gray;box-sizing: border-box;top: 0;bottom: 0;left: 50%;z-index: -1;}#sk-container-id-4 div.sk-parallel-item {display: flex;flex-direction: column;z-index: 1;position: relative;background-color: white;}#sk-container-id-4 div.sk-parallel-item:first-child::after {align-self: flex-end;width: 50%;}#sk-container-id-4 div.sk-parallel-item:last-child::after {align-self: flex-start;width: 50%;}#sk-container-id-4 div.sk-parallel-item:only-child::after {width: 0;}#sk-container-id-4 div.sk-dashed-wrapped {border: 1px dashed gray;margin: 0 0.4em 0.5em 0.4em;box-sizing: border-box;padding-bottom: 0.4em;background-color: white;}#sk-container-id-4 div.sk-label label {font-family: monospace;font-weight: bold;display: inline-block;line-height: 1.2em;}#sk-container-id-4 div.sk-label-container {text-align: center;}#sk-container-id-4 div.sk-container {/* jupyter's `normalize.less` sets `[hidden] { display: none; }` but bootstrap.min.css set `[hidden] { display: none !important; }` so we also need the `!important` here to be able to override the default hidden behavior on the sphinx rendered scikit-learn.org. See: https://github.com/scikit-learn/scikit-learn/issues/21755 */display: inline-block !important;position: relative;}#sk-container-id-4 div.sk-text-repr-fallback {display: none;}</style><div id=\"sk-container-id-4\" class=\"sk-top-container\"><div class=\"sk-text-repr-fallback\"><pre>LogisticRegression(C=0.0001)</pre><b>In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook. <br />On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.</b></div><div class=\"sk-container\" hidden><div class=\"sk-item\"><div class=\"sk-estimator sk-toggleable\"><input class=\"sk-toggleable__control sk-hidden--visually\" id=\"sk-estimator-id-4\" type=\"checkbox\" checked><label for=\"sk-estimator-id-4\" class=\"sk-toggleable__label sk-toggleable__label-arrow\">LogisticRegression</label><div class=\"sk-toggleable__content\"><pre>LogisticRegression(C=0.0001)</pre></div></div></div></div></div>"},"metadata":{}}]},{"cell_type":"code","source":"log_reg_pred = log_reg.predict_proba(test)[:, 1]","metadata":{"execution":{"iopub.status.busy":"2023-05-20T14:18:41.027496Z","iopub.execute_input":"2023-05-20T14:18:41.028122Z","iopub.status.idle":"2023-05-20T14:18:41.049477Z","shell.execute_reply.started":"2023-05-20T14:18:41.028067Z","shell.execute_reply":"2023-05-20T14:18:41.045337Z"},"trusted":true},"execution_count":76,"outputs":[]},{"cell_type":"code","source":"submit = app_test[['SK_ID_CURR']]\nsubmit['TARGET'] = log_reg_pred\n\nsubmit.head()","metadata":{"execution":{"iopub.status.busy":"2023-05-20T14:18:41.056355Z","iopub.execute_input":"2023-05-20T14:18:41.062026Z","iopub.status.idle":"2023-05-20T14:18:41.102101Z","shell.execute_reply.started":"2023-05-20T14:18:41.061968Z","shell.execute_reply":"2023-05-20T14:18:41.100425Z"},"trusted":true},"execution_count":77,"outputs":[{"name":"stderr","text":"/tmp/ipykernel_34/3970473317.py:2: SettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\nSee the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy\n  submit['TARGET'] = log_reg_pred\n","output_type":"stream"},{"execution_count":77,"output_type":"execute_result","data":{"text/plain":"   SK_ID_CURR    TARGET\n0      100001  0.069575\n1      100005  0.094681\n2      100013  0.060506\n3      100028  0.068598\n4      100038  0.093596","text/html":"<div>\n<style scoped>\n    .dataframe tbody tr th:only-of-type {\n        vertical-align: middle;\n    }\n\n    .dataframe tbody tr th {\n        vertical-align: top;\n    }\n\n    .dataframe thead th {\n        text-align: right;\n    }\n</style>\n<table border=\"1\" class=\"dataframe\">\n  <thead>\n    <tr style=\"text-align: right;\">\n      <th></th>\n      <th>SK_ID_CURR</th>\n      <th>TARGET</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <th>0</th>\n      <td>100001</td>\n      <td>0.069575</td>\n    </tr>\n    <tr>\n      <th>1</th>\n      <td>100005</td>\n      <td>0.094681</td>\n    </tr>\n    <tr>\n      <th>2</th>\n      <td>100013</td>\n      <td>0.060506</td>\n    </tr>\n    <tr>\n      <th>3</th>\n      <td>100028</td>\n      <td>0.068598</td>\n    </tr>\n    <tr>\n      <th>4</th>\n      <td>100038</td>\n      <td>0.093596</td>\n    </tr>\n  </tbody>\n</table>\n</div>"},"metadata":{}}]},{"cell_type":"code","source":"from sklearn.metrics import roc_auc_score\n\nroc_auc = roc_auc_score(y_test, y_pred)\nprint(f'ROC AUC: {roc_auc:.4f}')","metadata":{"execution":{"iopub.status.busy":"2023-05-20T14:18:41.113664Z","iopub.execute_input":"2023-05-20T14:18:41.117055Z","iopub.status.idle":"2023-05-20T14:18:41.147320Z","shell.execute_reply.started":"2023-05-20T14:18:41.116973Z","shell.execute_reply":"2023-05-20T14:18:41.146231Z"},"trusted":true},"execution_count":78,"outputs":[{"name":"stdout","text":"ROC AUC: 0.6330\n","output_type":"stream"}]},{"cell_type":"code","source":"def protected_division(x1, x2):\n    if x2 == 0:\n        return 1  # Защита от деления на ноль\n    else:\n        return x1 / x2\n\ndef protected_sqrt(x):\n    if x < 0:\n        return 0  # Защита от извлечения квадратного корня из отрицательного числа\n    else:\n        return np.sqrt(x)\n\ndef protected_log(x):\n    if x <= 0:\n        return 0  # Защита от логарифма от неположительного числа или нуля\n    else:\n        return np.log(x)\n","metadata":{"execution":{"iopub.status.busy":"2023-05-20T14:49:11.499330Z","iopub.execute_input":"2023-05-20T14:49:11.499710Z","iopub.status.idle":"2023-05-20T14:49:11.509280Z","shell.execute_reply.started":"2023-05-20T14:49:11.499682Z","shell.execute_reply":"2023-05-20T14:49:11.508028Z"},"trusted":true},"execution_count":91,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom deap import creator, base, tools, gp\n# Определение функций и операций для генерации новых признаков\npset = gp.PrimitiveSet(\"MAIN\", arity=2)\npset.addPrimitive(np.add, arity=2)\npset.addPrimitive(np.subtract, arity=2)\npset.addPrimitive(np.multiply, arity=2)\npset.addPrimitive(np.maximum, arity=2)\npset.addPrimitive(np.minimum, arity=2)\npset.addPrimitive(protected_division, arity=2)\npset.addPrimitive(protected_sqrt, arity=1)\npset.addPrimitive(protected_log, arity=1)\npset.addPrimitive(np.sin, arity=1)\npset.addPrimitive(np.cos, arity=1)\npset.addTerminal(0)\npset.addTerminal(1)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T14:47:45.250984Z","iopub.execute_input":"2023-05-20T14:47:45.251432Z","iopub.status.idle":"2023-05-20T14:47:45.261277Z","shell.execute_reply.started":"2023-05-20T14:47:45.251396Z","shell.execute_reply":"2023-05-20T14:47:45.260147Z"},"trusted":true},"execution_count":89,"outputs":[]},{"cell_type":"code","source":"# Создание класса для управления эволюцией\ncreator.create(\"FitnessMax\", base.Fitness, weights=(1.0,))\ncreator.create(\"Individual\", gp.PrimitiveTree, fitness=creator.FitnessMax)\n\n# Инициализация пакета инструментов\ntoolbox = base.Toolbox()\n\n# Определение функций и операций, которые могут быть использованы для создания новых признаков\ntoolbox.register(\"expr\", gp.genHalfAndHalf, pset=pset, min_=1, max_=3)\ntoolbox.register(\"individual\", tools.initIterate, creator.Individual, toolbox.expr)\ntoolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)\n\n# Определение операторов мутации, скрещивания и оценки фитнеса\ntoolbox.register(\"mate\", gp.cxOnePoint)\ntoolbox.register(\"mutate\", gp.mutUniform, expr=toolbox.expr, pset=pset)\ntoolbox.register(\"evaluate\", evaluate_fitness)\ntoolbox.register(\"select\", tools.selTournament, tournsize=3)","metadata":{"execution":{"iopub.status.busy":"2023-05-20T14:49:14.993461Z","iopub.execute_input":"2023-05-20T14:49:14.993876Z","iopub.status.idle":"2023-05-20T14:49:15.005150Z","shell.execute_reply.started":"2023-05-20T14:49:14.993845Z","shell.execute_reply":"2023-05-20T14:49:15.003875Z"},"trusted":true},"execution_count":92,"outputs":[{"name":"stderr","text":"/opt/conda/lib/python3.10/site-packages/deap/creator.py:138: RuntimeWarning: A class named 'FitnessMax' has already been created and it will be overwritten. Consider deleting previous creation of that class or rename it.\n  warnings.warn(\"A class named '{0}' has already been created and it \"\n/opt/conda/lib/python3.10/site-packages/deap/creator.py:138: RuntimeWarning: A class named 'Individual' has already been created and it will be overwritten. Consider deleting previous creation of that class or rename it.\n  warnings.warn(\"A class named '{0}' has already been created and it \"\n","output_type":"stream"}]},{"cell_type":"code","source":"# Определение функции преобразования ГП структуры в вектор признаков\ndef transform_gp_structure(individual, X):\n    expr = gp.compile(individual, pset)\n    return np.array([expr(*row) for row in X])\n\n# Определение функции оценки фитнеса (ваша собственная функция)\ndef evaluate_fitness(individual):\n    # Вычислите значения признаков на основе individual\n    X_train_gp = transform_gp_structure(individual, X_train)  # Вычисление новых признаков на обучающей выборке\n    rf_model_gp.fit(X_train_gp, y_train)  # Обучение модели случайного леса с новыми признаками\n    X_test_gp = transform_gp_structure(individual, X_test)  # Вычисление новых признаков на тестовой выборке\n    y_pred_gp = rf_model_gp.predict_proba(X_test_gp)[:, 1]  # Прогнозирование на тестовой выборке с новыми признаками\n    auc_gp = roc_auc_score(y_test, y_pred_gp)  # Оценка фитнеса (AUC-ROC)\n    return auc_gp,","metadata":{"execution":{"iopub.status.busy":"2023-05-20T14:58:23.425722Z","iopub.execute_input":"2023-05-20T14:58:23.426108Z","iopub.status.idle":"2023-05-20T14:58:23.435016Z","shell.execute_reply.started":"2023-05-20T14:58:23.426080Z","shell.execute_reply":"2023-05-20T14:58:23.433744Z"},"trusted":true},"execution_count":103,"outputs":[]},{"cell_type":"code","source":"pop_size = 100  # Размер популяции\nnum_generations = 50  # Количество поколений\n\n# Создание начальной популяции\npopulation = toolbox.population(n=pop_size)\n\n# Основной цикл эволюции\nfor generation in range(num_generations):\n    # Оценка фитнеса\n    fitnesses = map(evaluate_fitness, population)\n    for individual, fitness in zip(population, fitnesses):\n        individual.fitness.values = fitness\n\n    # Выбор следующего поколения\n    offspring = toolbox.select(population, len(population))\n\n    # Клонирование выбранных индивидуумов\n    offspring = list(map(toolbox.clone, offspring))\n\n    # Применение операторов скрещивания и мутации\n    for child1, child2 in zip(offspring[::2], offspring[1::2]):\n        if random.random() < crossover_prob:\n            toolbox.mate(child1, child2)\n            del child1.fitness.values\n            del child2.fitness.values\n\n    for mutant in offspring:\n        if random.random() < mutation_prob:\n            toolbox.mutate(mutant)\n            del mutant.fitness.values\n\n    # Замена старого поколения потомками\n    population[:] = offspring","metadata":{"execution":{"iopub.status.busy":"2023-05-20T14:58:26.121249Z","iopub.execute_input":"2023-05-20T14:58:26.121638Z","iopub.status.idle":"2023-05-20T14:58:26.216633Z","shell.execute_reply.started":"2023-05-20T14:58:26.121608Z","shell.execute_reply":"2023-05-20T14:58:26.215421Z"},"trusted":true},"execution_count":104,"outputs":[{"traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)","Cell \u001b[0;32mIn[104], line 11\u001b[0m\n\u001b[1;32m      8\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m generation \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(num_generations):\n\u001b[1;32m      9\u001b[0m     \u001b[38;5;66;03m# Оценка фитнеса\u001b[39;00m\n\u001b[1;32m     10\u001b[0m     fitnesses \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mmap\u001b[39m(evaluate_fitness, population)\n\u001b[0;32m---> 11\u001b[0m     \u001b[38;5;28;01mfor\u001b[39;00m individual, fitness \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mzip\u001b[39m(population, fitnesses):\n\u001b[1;32m     12\u001b[0m         individual\u001b[38;5;241m.\u001b[39mfitness\u001b[38;5;241m.\u001b[39mvalues \u001b[38;5;241m=\u001b[39m fitness\n\u001b[1;32m     14\u001b[0m     \u001b[38;5;66;03m# Выбор следующего поколения\u001b[39;00m\n","Cell \u001b[0;32mIn[103], line 9\u001b[0m, in \u001b[0;36mevaluate_fitness\u001b[0;34m(individual)\u001b[0m\n\u001b[1;32m      7\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mevaluate_fitness\u001b[39m(individual):\n\u001b[1;32m      8\u001b[0m     \u001b[38;5;66;03m# Вычислите значения признаков на основе individual\u001b[39;00m\n\u001b[0;32m----> 9\u001b[0m     X_train_gp \u001b[38;5;241m=\u001b[39m \u001b[43mtransform_gp_structure\u001b[49m\u001b[43m(\u001b[49m\u001b[43mindividual\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mX_train\u001b[49m\u001b[43m)\u001b[49m  \u001b[38;5;66;03m# Вычисление новых признаков на обучающей выборке\u001b[39;00m\n\u001b[1;32m     10\u001b[0m     rf_model_gp\u001b[38;5;241m.\u001b[39mfit(X_train_gp, y_train)  \u001b[38;5;66;03m# Обучение модели случайного леса с новыми признаками\u001b[39;00m\n\u001b[1;32m     11\u001b[0m     X_test_gp \u001b[38;5;241m=\u001b[39m transform_gp_structure(individual, X_test)  \u001b[38;5;66;03m# Вычисление новых признаков на тестовой выборке\u001b[39;00m\n","Cell \u001b[0;32mIn[103], line 4\u001b[0m, in \u001b[0;36mtransform_gp_structure\u001b[0;34m(individual, X)\u001b[0m\n\u001b[1;32m      2\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mtransform_gp_structure\u001b[39m(individual, X):\n\u001b[1;32m      3\u001b[0m     expr \u001b[38;5;241m=\u001b[39m gp\u001b[38;5;241m.\u001b[39mcompile(individual, pset)\n\u001b[0;32m----> 4\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m np\u001b[38;5;241m.\u001b[39marray([expr(\u001b[38;5;241m*\u001b[39mrow) \u001b[38;5;28;01mfor\u001b[39;00m row \u001b[38;5;129;01min\u001b[39;00m X])\n","Cell \u001b[0;32mIn[103], line 4\u001b[0m, in \u001b[0;36m<listcomp>\u001b[0;34m(.0)\u001b[0m\n\u001b[1;32m      2\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mtransform_gp_structure\u001b[39m(individual, X):\n\u001b[1;32m      3\u001b[0m     expr \u001b[38;5;241m=\u001b[39m gp\u001b[38;5;241m.\u001b[39mcompile(individual, pset)\n\u001b[0;32m----> 4\u001b[0m     \u001b[38;5;28;01mreturn\u001b[39;00m np\u001b[38;5;241m.\u001b[39marray([\u001b[43mexpr\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mrow\u001b[49m\u001b[43m)\u001b[49m \u001b[38;5;28;01mfor\u001b[39;00m row \u001b[38;5;129;01min\u001b[39;00m X])\n","\u001b[0;31mTypeError\u001b[0m: <lambda>() takes 2 positional arguments but 72 were given"],"ename":"TypeError","evalue":"<lambda>() takes 2 positional arguments but 72 were given","output_type":"error"}]}]}