{"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":"
\n\n
\n \n \n | \n SK_ID_CURR | \n TARGET | \n NAME_CONTRACT_TYPE | \n CODE_GENDER | \n FLAG_OWN_CAR | \n FLAG_OWN_REALTY | \n CNT_CHILDREN | \n AMT_INCOME_TOTAL | \n AMT_CREDIT | \n AMT_ANNUITY | \n ... | \n FLAG_DOCUMENT_18 | \n FLAG_DOCUMENT_19 | \n FLAG_DOCUMENT_20 | \n FLAG_DOCUMENT_21 | \n AMT_REQ_CREDIT_BUREAU_HOUR | \n AMT_REQ_CREDIT_BUREAU_DAY | \n AMT_REQ_CREDIT_BUREAU_WEEK | \n AMT_REQ_CREDIT_BUREAU_MON | \n AMT_REQ_CREDIT_BUREAU_QRT | \n AMT_REQ_CREDIT_BUREAU_YEAR | \n
\n \n \n \n
\n
0 rows × 73 columns
\n
"},"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":"\n\n
\n \n \n | \n AMT_INCOME_TOTAL | \n AMT_CREDIT | \n AMT_ANNUITY | \n CNT_CHILDREN | \n TARGET | \n Credit/Income | \n Annuity/Income | \n
\n \n \n \n | 12840 | \n 117000000.0 | \n 562491.0 | \n 26194.5 | \n 1 | \n 1 | \n 0.004808 | \n 0.000224 | \n
\n \n | 248159 | \n 3150000.0 | \n 900000.0 | \n 48825.0 | \n 1 | \n 1 | \n 0.285714 | \n 0.015500 | \n
\n \n | 151018 | \n 1080000.0 | \n 371245.5 | \n 17437.5 | \n 0 | \n 1 | \n 0.343746 | \n 0.016146 | \n
\n \n | 167656 | \n 1575000.0 | \n 553806.0 | \n 28273.5 | \n 0 | \n 1 | \n 0.351623 | \n 0.017951 | \n
\n \n | 173663 | \n 1350000.0 | \n 491211.0 | \n 50463.0 | \n 3 | \n 1 | \n 0.363860 | \n 0.037380 | \n
\n \n | 41725 | \n 1890000.0 | \n 781920.0 | \n 61906.5 | \n 1 | \n 1 | \n 0.413714 | \n 0.032755 | \n
\n \n | 234728 | \n 1350000.0 | \n 576072.0 | \n 28017.0 | \n 0 | \n 1 | \n 0.426720 | \n 0.020753 | \n
\n \n | 248970 | \n 1890000.0 | \n 900000.0 | \n 57649.5 | \n 0 | \n 1 | \n 0.476190 | \n 0.030502 | \n
\n \n | 265884 | \n 1170000.0 | \n 983299.5 | \n 41661.0 | \n 1 | \n 1 | \n 0.840427 | \n 0.035608 | \n
\n \n | 234861 | \n 1260000.0 | \n 1097491.5 | \n 46629.0 | \n 0 | \n 1 | \n 0.871025 | \n 0.037007 | \n
\n \n | 38271 | \n 1125000.0 | \n 1006920.0 | \n 40063.5 | \n 0 | \n 1 | \n 0.895040 | \n 0.035612 | \n
\n \n | 102626 | \n 1305000.0 | \n 1339884.0 | \n 39307.5 | \n 0 | \n 1 | \n 1.026731 | \n 0.030121 | \n
\n \n | 196106 | \n 1350000.0 | \n 2517300.0 | \n 93420.0 | \n 2 | \n 1 | \n 1.864667 | \n 0.069200 | \n
\n \n
\n
"},"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":"\n\n
\n \n \n | \n DAYS_BIRTH | \n TARGET | \n YEARS_BIRTH | \n
\n \n \n \n | 265026 | \n -25229 | \n 0 | \n 69.073238 | \n
\n \n | 63316 | \n -25201 | \n 0 | \n 68.996578 | \n
\n \n | 124430 | \n -25201 | \n 0 | \n 68.996578 | \n
\n \n | 143266 | \n -25200 | \n 0 | \n 68.993840 | \n
\n \n | 130108 | \n -25197 | \n 0 | \n 68.985626 | \n
\n \n | ... | \n ... | \n ... | \n ... | \n
\n \n | 220805 | \n -7678 | \n 1 | \n 21.021218 | \n
\n \n | 170384 | \n -7676 | \n 0 | \n 21.015743 | \n
\n \n | 53702 | \n -7676 | \n 0 | \n 21.015743 | \n
\n \n | 168135 | \n -7673 | \n 0 | \n 21.007529 | \n
\n \n | 235444 | \n -7489 | \n 0 | \n 20.503765 | \n
\n \n
\n
307510 rows × 3 columns
\n
"},"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":"\n\n
\n \n \n | \n NAME_CONTRACT_TYPE | \n CODE_GENDER | \n FLAG_OWN_CAR | \n FLAG_OWN_REALTY | \n NAME_TYPE_SUITE | \n NAME_INCOME_TYPE | \n NAME_EDUCATION_TYPE | \n NAME_FAMILY_STATUS | \n NAME_HOUSING_TYPE | \n OCCUPATION_TYPE | \n WEEKDAY_APPR_PROCESS_START | \n ORGANIZATION_TYPE | \n
\n \n \n \n | count | \n 307510 | \n 307510 | \n 307510 | \n 307510 | \n 307510 | \n 307510 | \n 307510 | \n 307510 | \n 307510 | \n 211119 | \n 307510 | \n 252136 | \n
\n \n | unique | \n 2 | \n 2 | \n 2 | \n 2 | \n 7 | \n 8 | \n 5 | \n 5 | \n 6 | \n 18 | \n 7 | \n 57 | \n
\n \n | top | \n Cash loans | \n F | \n N | \n Y | \n Unaccompanied | \n Working | \n Secondary / secondary special | \n Married | \n House / apartment | \n Laborers | \n TUESDAY | \n Business Entity Type 3 | \n
\n \n | freq | \n 278231 | \n 202451 | \n 202923 | \n 213311 | \n 249817 | \n 158773 | \n 218390 | \n 196433 | \n 272867 | \n 55185 | \n 53900 | \n 67991 | \n
\n \n
\n
"},"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":"\n\n
\n \n \n | \n NAME_CONTRACT_TYPE | \n CODE_GENDER | \n FLAG_OWN_CAR | \n FLAG_OWN_REALTY | \n NAME_TYPE_SUITE | \n NAME_INCOME_TYPE | \n NAME_EDUCATION_TYPE | \n NAME_FAMILY_STATUS | \n NAME_HOUSING_TYPE | \n OCCUPATION_TYPE | \n WEEKDAY_APPR_PROCESS_START | \n ORGANIZATION_TYPE | \n
\n \n \n \n | 0 | \n Cash loans | \n M | \n N | \n Y | \n Unaccompanied | \n Working | \n Secondary / secondary special | \n Single / not married | \n House / apartment | \n Laborers | \n WEDNESDAY | \n Business Entity Type 3 | \n
\n \n | 1 | \n Cash loans | \n F | \n N | \n N | \n Family | \n State servant | \n Higher education | \n Married | \n House / apartment | \n Core staff | \n MONDAY | \n School | \n
\n \n | 2 | \n Revolving loans | \n M | \n Y | \n Y | \n Unaccompanied | \n Working | \n Secondary / secondary special | \n Single / not married | \n House / apartment | \n Laborers | \n MONDAY | \n Government | \n
\n \n | 3 | \n Cash loans | \n F | \n N | \n Y | \n Unaccompanied | \n Working | \n Secondary / secondary special | \n Civil marriage | \n House / apartment | \n Laborers | \n WEDNESDAY | \n Business Entity Type 3 | \n
\n \n | 4 | \n Cash loans | \n M | \n N | \n Y | \n Unaccompanied | \n Working | \n Secondary / secondary special | \n Single / not married | \n House / apartment | \n Core staff | \n THURSDAY | \n Others | \n
\n \n | ... | \n ... | \n ... | \n ... | \n ... | \n ... | \n ... | \n ... | \n ... | \n ... | \n ... | \n ... | \n ... | \n
\n \n | 307506 | \n Cash loans | \n M | \n N | \n N | \n Unaccompanied | \n Working | \n Secondary / secondary special | \n Separated | \n With parents | \n Sales staff | \n THURSDAY | \n Others | \n
\n \n | 307507 | \n Cash loans | \n F | \n N | \n Y | \n Unaccompanied | \n Pensioner | \n Secondary / secondary special | \n Widow | \n House / apartment | \n Laborers | \n MONDAY | \n Business Entity Type 3 | \n
\n \n | 307508 | \n Cash loans | \n F | \n N | \n Y | \n Unaccompanied | \n Working | \n Higher education | \n Separated | \n House / apartment | \n Managers | \n THURSDAY | \n School | \n
\n \n | 307509 | \n Cash loans | \n F | \n N | \n Y | \n Unaccompanied | \n Commercial associate | \n Secondary / secondary special | \n Married | \n House / apartment | \n Laborers | \n WEDNESDAY | \n Business Entity Type 1 | \n
\n \n | 307510 | \n Cash loans | \n F | \n N | \n N | \n Unaccompanied | \n Commercial associate | \n Higher education | \n Married | \n House / apartment | \n Laborers | \n THURSDAY | \n Business Entity Type 3 | \n
\n \n
\n
307510 rows × 12 columns
\n
"},"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":"RandomForestClassifier(max_depth=15, n_estimators=70, random_state=42)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org. "},"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":"RandomForestClassifier(max_depth=15, n_estimators=110, random_state=12)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org. "},"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":"RandomForestClassifier(max_depth=15, random_state=12)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org. "},"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":"LogisticRegression(C=0.0001)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org. "},"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":"\n\n
\n \n \n | \n SK_ID_CURR | \n TARGET | \n
\n \n \n \n | 0 | \n 100001 | \n 0.069575 | \n
\n \n | 1 | \n 100005 | \n 0.094681 | \n
\n \n | 2 | \n 100013 | \n 0.060506 | \n
\n \n | 3 | \n 100028 | \n 0.068598 | \n
\n \n | 4 | \n 100038 | \n 0.093596 | \n
\n \n
\n
"},"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\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: () takes 2 positional arguments but 72 were given"],"ename":"TypeError","evalue":"() takes 2 positional arguments but 72 were given","output_type":"error"}]}]}