{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:23.708337Z", "iopub.status.busy": "2023-05-20T13:31:23.707889Z", "iopub.status.idle": "2023-05-20T13:31:24.615636Z", "shell.execute_reply": "2023-05-20T13:31:24.614494Z", "shell.execute_reply.started": "2023-05-20T13:31:23.708303Z" } }, "outputs": [], "source": [ "import numpy as np \n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "import seaborn as sns\n", "from scipy.stats import chi2_contingency " ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:24.618585Z", "iopub.status.busy": "2023-05-20T13:31:24.617951Z", "iopub.status.idle": "2023-05-20T13:31:32.801864Z", "shell.execute_reply": "2023-05-20T13:31:32.800838Z", "shell.execute_reply.started": "2023-05-20T13:31:24.618546Z" } }, "outputs": [], "source": [ "app_train = pd.read_csv('data/application_train.csv.zip')\n", "app_test=pd.read_csv('data/application_test.csv.zip')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:32.803708Z", "iopub.status.busy": "2023-05-20T13:31:32.803286Z", "iopub.status.idle": "2023-05-20T13:31:33.178020Z", "shell.execute_reply": "2023-05-20T13:31:33.176717Z", "shell.execute_reply.started": "2023-05-20T13:31:32.803673Z" } }, "outputs": [], "source": [ "print(app_train[['ORGANIZATION_TYPE','NAME_FAMILY_STATUS', 'CODE_GENDER']].isnull().sum())\n", "print('-'*40)\n", "print(app_test[['ORGANIZATION_TYPE','NAME_FAMILY_STATUS', 'CODE_GENDER']].isnull().sum())" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:33.181384Z", "iopub.status.busy": "2023-05-20T13:31:33.181034Z", "iopub.status.idle": "2023-05-20T13:31:34.800143Z", "shell.execute_reply": "2023-05-20T13:31:34.799026Z", "shell.execute_reply.started": "2023-05-20T13:31:33.181354Z" } }, "outputs": [], "source": [ "users_nan = (app_train.isnull().sum() / app_train.shape[0]) * 100\n", "users_nan[users_nan > 0].sort_values(ascending=False)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:34.803064Z", "iopub.status.busy": "2023-05-20T13:31:34.801805Z", "iopub.status.idle": "2023-05-20T13:31:37.424943Z", "shell.execute_reply": "2023-05-20T13:31:37.423842Z", "shell.execute_reply.started": "2023-05-20T13:31:34.803022Z" } }, "outputs": [], "source": [ "app_train.replace({'XNA': np.nan, 'XNP': np.nan, 'Unknown': np.nan}, inplace = True)\n", "app_test.replace({'XNA': np.nan, 'XNP': np.nan, 'Unknown': np.nan}, inplace = True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:37.426520Z", "iopub.status.busy": "2023-05-20T13:31:37.426208Z", "iopub.status.idle": "2023-05-20T13:31:37.781279Z", "shell.execute_reply": "2023-05-20T13:31:37.780147Z", "shell.execute_reply.started": "2023-05-20T13:31:37.426494Z" } }, "outputs": [], "source": [ "print(app_train[['ORGANIZATION_TYPE','NAME_FAMILY_STATUS', 'CODE_GENDER']].isnull().sum())\n", "print('-'*40)\n", "print(app_test[['ORGANIZATION_TYPE','NAME_FAMILY_STATUS', 'CODE_GENDER']].isnull().sum())" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:37.783262Z", "iopub.status.busy": "2023-05-20T13:31:37.782696Z", "iopub.status.idle": "2023-05-20T13:31:39.299745Z", "shell.execute_reply": "2023-05-20T13:31:39.298642Z", "shell.execute_reply.started": "2023-05-20T13:31:37.783232Z" } }, "outputs": [], "source": [ "users_nan = (app_train.isnull().sum() / app_train.shape[0]) * 100\n", "users_nan[users_nan > 0].sort_values(ascending=False)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:39.301945Z", "iopub.status.busy": "2023-05-20T13:31:39.301331Z", "iopub.status.idle": "2023-05-20T13:31:40.848654Z", "shell.execute_reply": "2023-05-20T13:31:40.847530Z", "shell.execute_reply.started": "2023-05-20T13:31:39.301915Z" } }, "outputs": [], "source": [ "app_test.drop(app_train.columns[app_train.isnull().mean()>0.4],axis=1, inplace=True)\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:40.850599Z", "iopub.status.busy": "2023-05-20T13:31:40.850202Z", "iopub.status.idle": "2023-05-20T13:31:42.468788Z", "shell.execute_reply": "2023-05-20T13:31:42.467742Z", "shell.execute_reply.started": "2023-05-20T13:31:40.850564Z" } }, "outputs": [], "source": [ "app_train.drop(app_train.columns[app_train.isnull().mean()>0.4],axis=1, inplace=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:42.474671Z", "iopub.status.busy": "2023-05-20T13:31:42.474330Z", "iopub.status.idle": "2023-05-20T13:31:42.481468Z", "shell.execute_reply": "2023-05-20T13:31:42.480481Z", "shell.execute_reply.started": "2023-05-20T13:31:42.474643Z" } }, "outputs": [], "source": [ "app_train.shape" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:42.482990Z", "iopub.status.busy": "2023-05-20T13:31:42.482691Z", "iopub.status.idle": "2023-05-20T13:31:42.497810Z", "shell.execute_reply": "2023-05-20T13:31:42.496609Z", "shell.execute_reply.started": "2023-05-20T13:31:42.482965Z" } }, "outputs": [], "source": [ "app_test.shape" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:42.499575Z", "iopub.status.busy": "2023-05-20T13:31:42.499228Z", "iopub.status.idle": "2023-05-20T13:31:43.679359Z", "shell.execute_reply": "2023-05-20T13:31:43.678275Z", "shell.execute_reply.started": "2023-05-20T13:31:42.499547Z" } }, "outputs": [], "source": [ "users_nan = (app_train.isnull().sum() / app_train.shape[0]) * 100\n", "users_nan[users_nan > 0].sort_values(ascending=False)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:43.680950Z", "iopub.status.busy": "2023-05-20T13:31:43.680639Z", "iopub.status.idle": "2023-05-20T13:31:43.878881Z", "shell.execute_reply": "2023-05-20T13:31:43.877523Z", "shell.execute_reply.started": "2023-05-20T13:31:43.680924Z" } }, "outputs": [], "source": [ "users_nan = (app_test.isnull().sum() / app_test.shape[0]) * 100\n", "users_nan[users_nan > 0].sort_values(ascending=False)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:43.880911Z", "iopub.status.busy": "2023-05-20T13:31:43.880546Z", "iopub.status.idle": "2023-05-20T13:31:48.486015Z", "shell.execute_reply": "2023-05-20T13:31:48.484853Z", "shell.execute_reply.started": "2023-05-20T13:31:43.880873Z" } }, "outputs": [], "source": [ "# Columns have less 14% NaN Values and categorical\n", "Cat_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\n", "num_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']" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:48.487653Z", "iopub.status.busy": "2023-05-20T13:31:48.487321Z", "iopub.status.idle": "2023-05-20T13:31:48.899460Z", "shell.execute_reply": "2023-05-20T13:31:48.898112Z", "shell.execute_reply.started": "2023-05-20T13:31:48.487625Z" } }, "outputs": [], "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)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:48.901595Z", "iopub.status.busy": "2023-05-20T13:31:48.901227Z", "iopub.status.idle": "2023-05-20T13:31:48.907826Z", "shell.execute_reply": "2023-05-20T13:31:48.906526Z", "shell.execute_reply.started": "2023-05-20T13:31:48.901557Z" } }, "outputs": [], "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']]\n", "col_mean_transform = ['EXT_SOURCE_2', 'AMT_ANNUITY']" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:48.911188Z", "iopub.status.busy": "2023-05-20T13:31:48.910234Z", "iopub.status.idle": "2023-05-20T13:31:49.048717Z", "shell.execute_reply": "2023-05-20T13:31:49.047610Z", "shell.execute_reply.started": "2023-05-20T13:31:48.911124Z" } }, "outputs": [], "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)\n", "for 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)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:49.050761Z", "iopub.status.busy": "2023-05-20T13:31:49.050280Z", "iopub.status.idle": "2023-05-20T13:31:49.067588Z", "shell.execute_reply": "2023-05-20T13:31:49.066219Z", "shell.execute_reply.started": "2023-05-20T13:31:49.050725Z" } }, "outputs": [], "source": [ "app_train['AMT_GOODS_PRICE'].fillna(app_train['AMT_GOODS_PRICE'].median(),inplace = True)" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:49.070174Z", "iopub.status.busy": "2023-05-20T13:31:49.069475Z", "iopub.status.idle": "2023-05-20T13:31:49.134864Z", "shell.execute_reply": "2023-05-20T13:31:49.133757Z", "shell.execute_reply.started": "2023-05-20T13:31:49.070111Z" } }, "outputs": [], "source": [ "all_numerical_cols = list(app_train.select_dtypes(exclude='object').columns)\n", "\n", "cont_cols = [col for col in all_numerical_cols if col != \"TARGET\" and col[:5]!='FLAG_']" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:49.136879Z", "iopub.status.busy": "2023-05-20T13:31:49.136528Z", "iopub.status.idle": "2023-05-20T13:31:49.170520Z", "shell.execute_reply": "2023-05-20T13:31:49.169241Z", "shell.execute_reply.started": "2023-05-20T13:31:49.136849Z" } }, "outputs": [], "source": [ "app_train[(abs(app_train['DAYS_BIRTH']) < abs(app_train['DAYS_EMPLOYED'])) & (app_train['DAYS_EMPLOYED'] != 365243)]" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:49.172092Z", "iopub.status.busy": "2023-05-20T13:31:49.171745Z", "iopub.status.idle": "2023-05-20T13:31:49.179130Z", "shell.execute_reply": "2023-05-20T13:31:49.178185Z", "shell.execute_reply.started": "2023-05-20T13:31:49.172040Z" } }, "outputs": [], "source": [ "proper_days_empolyed_df = app_train\n", "proper_days_empolyed_df['YEARS_EMPLOYED'] = proper_days_empolyed_df['DAYS_EMPLOYED']/-365.25\n" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:49.181041Z", "iopub.status.busy": "2023-05-20T13:31:49.180556Z", "iopub.status.idle": "2023-05-20T13:31:49.238079Z", "shell.execute_reply": "2023-05-20T13:31:49.236986Z", "shell.execute_reply.started": "2023-05-20T13:31:49.181007Z" } }, "outputs": [], "source": [ "app_train['DAYS_EMPLOYED'].replace({365243:np.nan},inplace=True) \n", "app_test['DAYS_EMPLOYED'].replace({365243:np.nan},inplace=True) " ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:49.239903Z", "iopub.status.busy": "2023-05-20T13:31:49.239586Z", "iopub.status.idle": "2023-05-20T13:31:49.246895Z", "shell.execute_reply": "2023-05-20T13:31:49.245736Z", "shell.execute_reply.started": "2023-05-20T13:31:49.239876Z" } }, "outputs": [], "source": [ "proper_days_empolyed_df = app_train\n", "proper_days_empolyed_df['YEARS_EMPLOYED'] = proper_days_empolyed_df['DAYS_EMPLOYED']/-365.25\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:49.248350Z", "iopub.status.busy": "2023-05-20T13:31:49.247973Z", "iopub.status.idle": "2023-05-20T13:31:49.329255Z", "shell.execute_reply": "2023-05-20T13:31:49.328177Z", "shell.execute_reply.started": "2023-05-20T13:31:49.248321Z" } }, "outputs": [], "source": [ "app_train.groupby(['OCCUPATION_TYPE'])['DAYS_EMPLOYED'].mean()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:49.331266Z", "iopub.status.busy": "2023-05-20T13:31:49.330437Z", "iopub.status.idle": "2023-05-20T13:31:49.397670Z", "shell.execute_reply": "2023-05-20T13:31:49.396570Z", "shell.execute_reply.started": "2023-05-20T13:31:49.331236Z" } }, "outputs": [], "source": [ "## create dataframe with total income > 1M\n", "susp_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\n", "susp_df1['Credit/Income'] = susp_df1['AMT_CREDIT']/susp_df1['AMT_INCOME_TOTAL']\n", "susp_df1['Annuity/Income'] = susp_df1['AMT_ANNUITY']/susp_df1['AMT_INCOME_TOTAL']\n", "\n", "## show only clients with difficuties\n", "susp_df1[susp_df1['TARGET']==1].sort_values(by='Credit/Income', ascending=True)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:49.399844Z", "iopub.status.busy": "2023-05-20T13:31:49.399208Z", "iopub.status.idle": "2023-05-20T13:31:49.523335Z", "shell.execute_reply": "2023-05-20T13:31:49.522194Z", "shell.execute_reply.started": "2023-05-20T13:31:49.399813Z" } }, "outputs": [], "source": [ "app_train = app_train[app_train['AMT_INCOME_TOTAL'] != 117000000.0]\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:49.525201Z", "iopub.status.busy": "2023-05-20T13:31:49.524772Z", "iopub.status.idle": "2023-05-20T13:31:49.604686Z", "shell.execute_reply": "2023-05-20T13:31:49.603377Z", "shell.execute_reply.started": "2023-05-20T13:31:49.525143Z" } }, "outputs": [], "source": [ "## extract dataframe with DAYS_BIRTH and TARGET only\n", "susp_df2 = app_train[['DAYS_BIRTH','TARGET']]\n", "\n", "## create column represnts the age in years\n", "susp_df2['YEARS_BIRTH'] = np.abs(susp_df2['DAYS_BIRTH']) / 365.25\n", "\n", "## show datafame\n", "display(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\n", "display(susp_df2[(susp_df2['YEARS_BIRTH']>65)]['TARGET'].value_counts())" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:49.615247Z", "iopub.status.busy": "2023-05-20T13:31:49.614863Z", "iopub.status.idle": "2023-05-20T13:31:50.648599Z", "shell.execute_reply": "2023-05-20T13:31:50.647443Z", "shell.execute_reply.started": "2023-05-20T13:31:49.615217Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
NAME_CONTRACT_TYPECODE_GENDERFLAG_OWN_CARFLAG_OWN_REALTYNAME_TYPE_SUITENAME_INCOME_TYPENAME_EDUCATION_TYPENAME_FAMILY_STATUSNAME_HOUSING_TYPEOCCUPATION_TYPEWEEKDAY_APPR_PROCESS_STARTORGANIZATION_TYPE
count307510307510307510307510307510307510307510307510307510211119307510252136
unique22227855618757
topCash loansFNYUnaccompaniedWorkingSecondary / secondary specialMarriedHouse / apartmentLaborersTUESDAYBusiness Entity Type 3
freq278231202451202923213311249817158773218390196433272867551855390067991
\n", "
" ], "text/plain": [ " NAME_CONTRACT_TYPE CODE_GENDER FLAG_OWN_CAR FLAG_OWN_REALTY \\\n", "count 307510 307510 307510 307510 \n", "unique 2 2 2 2 \n", "top Cash loans F N Y \n", "freq 278231 202451 202923 213311 \n", "\n", " NAME_TYPE_SUITE NAME_INCOME_TYPE NAME_EDUCATION_TYPE \\\n", "count 307510 307510 307510 \n", "unique 7 8 5 \n", "top Unaccompanied Working Secondary / secondary special \n", "freq 249817 158773 218390 \n", "\n", " NAME_FAMILY_STATUS NAME_HOUSING_TYPE OCCUPATION_TYPE \\\n", "count 307510 307510 211119 \n", "unique 5 6 18 \n", "top Married House / apartment Laborers \n", "freq 196433 272867 55185 \n", "\n", " WEEKDAY_APPR_PROCESS_START ORGANIZATION_TYPE \n", "count 307510 252136 \n", "unique 7 57 \n", "top TUESDAY Business Entity Type 3 \n", "freq 53900 67991 " ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "cat_col = app_train.select_dtypes('object')\n", "cat_col.describe()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:50.652481Z", "iopub.status.busy": "2023-05-20T13:31:50.651202Z", "iopub.status.idle": "2023-05-20T13:31:50.755628Z", "shell.execute_reply": "2023-05-20T13:31:50.754347Z", "shell.execute_reply.started": "2023-05-20T13:31:50.652444Z" } }, "outputs": [], "source": [ "app_train.groupby(['NAME_EDUCATION_TYPE'])['OCCUPATION_TYPE'].agg(pd.Series.mode)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:50.757725Z", "iopub.status.busy": "2023-05-20T13:31:50.757283Z", "iopub.status.idle": "2023-05-20T13:31:50.799252Z", "shell.execute_reply": "2023-05-20T13:31:50.797887Z", "shell.execute_reply.started": "2023-05-20T13:31:50.757690Z" } }, "outputs": [], "source": [ "app_train['OCCUPATION_TYPE'].isnull().sum()\n", "app_test['OCCUPATION_TYPE'].isnull().sum()" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:50.800859Z", "iopub.status.busy": "2023-05-20T13:31:50.800536Z", "iopub.status.idle": "2023-05-20T13:31:51.560567Z", "shell.execute_reply": "2023-05-20T13:31:51.558644Z", "shell.execute_reply.started": "2023-05-20T13:31:50.800833Z" }, "scrolled": true }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ ":1: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame\n", "\n", "See 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", ":2: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame\n", "\n", "See 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", ":3: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame\n", "\n", "See 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", ":4: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame\n", "\n", "See 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", ":5: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame\n", "\n", "See 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", ":7: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame\n", "\n", "See 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", ":8: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame\n", "\n", "See 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", ":9: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame\n", "\n", "See 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", ":10: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame\n", "\n", "See 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", ":11: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame\n", "\n", "See 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" ] } ], "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')\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", "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", "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", "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", "\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", "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", "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", "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", "app_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Academic degree'] = app_test['OCCUPATION_TYPE'][app_test['NAME_EDUCATION_TYPE']=='Academic degree'].fillna('Managers')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:51.562638Z", "iopub.status.busy": "2023-05-20T13:31:51.562188Z", "iopub.status.idle": "2023-05-20T13:31:51.673103Z", "shell.execute_reply": "2023-05-20T13:31:51.671788Z", "shell.execute_reply.started": "2023-05-20T13:31:51.562599Z" } }, "outputs": [], "source": [ "app_train.groupby(['OCCUPATION_TYPE'])['ORGANIZATION_TYPE'].agg(pd.Series.mode)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:51.675082Z", "iopub.status.busy": "2023-05-20T13:31:51.674754Z", "iopub.status.idle": "2023-05-20T13:31:54.946220Z", "shell.execute_reply": "2023-05-20T13:31:54.945034Z", "shell.execute_reply.started": "2023-05-20T13:31:51.675055Z" }, "scrolled": true }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ ":1: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame\n", "\n", "See 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", ":23: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame\n", "\n", "See 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", ":46: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame\n", "\n", "See 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", ":49: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame\n", "\n", "See 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", ":52: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame\n", "\n", "See 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", ":57: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame\n", "\n", "See 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", ":63: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame\n", "\n", "See 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", ":64: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame\n", "\n", "See 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" ] } ], "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", "\n", "app_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", "\n", "app_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')\n", "app_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')\n", "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')] = 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')\n", "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')] = 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", "\n", "app_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Security staff')] = app_train['ORGANIZATION_TYPE'][(app_train['OCCUPATION_TYPE'] == 'Security staff')].fillna('Security')\n", "app_test['ORGANIZATION_TYPE'][(app_test['OCCUPATION_TYPE'] == 'Security staff')] = app_test['ORGANIZATION_TYPE'][(app_test['OCCUPATION_TYPE'] == 'Security staff')].fillna('Security')\n" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:54.947839Z", "iopub.status.busy": "2023-05-20T13:31:54.947527Z", "iopub.status.idle": "2023-05-20T13:31:54.974412Z", "shell.execute_reply": "2023-05-20T13:31:54.973234Z", "shell.execute_reply.started": "2023-05-20T13:31:54.947813Z" } }, "outputs": [], "source": [ "app_test['ORGANIZATION_TYPE'] = app_test['ORGANIZATION_TYPE'].fillna(app_test['ORGANIZATION_TYPE'].mode()[0])" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:54.976259Z", "iopub.status.busy": "2023-05-20T13:31:54.975857Z", "iopub.status.idle": "2023-05-20T13:31:55.083771Z", "shell.execute_reply": "2023-05-20T13:31:55.082671Z", "shell.execute_reply.started": "2023-05-20T13:31:54.976218Z" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ ":2: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame.\n", "Try using .loc[row_indexer,col_indexer] = value instead\n", "\n", "See 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" ] } ], "source": [ "app_test['EXT_SOURCE_3'] = app_test['EXT_SOURCE_3'].fillna(app_train.groupby(['OCCUPATION_TYPE'])['EXT_SOURCE_3'].transform('mean'))\n", "app_train['EXT_SOURCE_3'] = app_train['EXT_SOURCE_3'].fillna(app_train.groupby(['OCCUPATION_TYPE'])['EXT_SOURCE_3'].transform('mean'))" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:55.085687Z", "iopub.status.busy": "2023-05-20T13:31:55.085250Z", "iopub.status.idle": "2023-05-20T13:31:55.190547Z", "shell.execute_reply": "2023-05-20T13:31:55.189369Z", "shell.execute_reply.started": "2023-05-20T13:31:55.085650Z" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ ":2: SettingWithCopyWarning: \n", "A value is trying to be set on a copy of a slice from a DataFrame.\n", "Try using .loc[row_indexer,col_indexer] = value instead\n", "\n", "See 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" ] } ], "source": [ "app_test['DAYS_EMPLOYED'] = app_test['DAYS_EMPLOYED'].fillna(app_train.groupby(['OCCUPATION_TYPE'])['DAYS_EMPLOYED'].transform('mean'))\n", "app_train['DAYS_EMPLOYED'] = app_train['DAYS_EMPLOYED'].fillna(app_train.groupby(['OCCUPATION_TYPE'])['DAYS_EMPLOYED'].transform('mean'))" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:55.192859Z", "iopub.status.busy": "2023-05-20T13:31:55.192017Z", "iopub.status.idle": "2023-05-20T13:31:55.231641Z", "shell.execute_reply": "2023-05-20T13:31:55.230479Z", "shell.execute_reply.started": "2023-05-20T13:31:55.192829Z" } }, "outputs": [], "source": [ "proper_days_empolyed_df = app_train\n", "proper_days_empolyed_df['YEARS_EMPLOYED'] = proper_days_empolyed_df['DAYS_EMPLOYED']/-365.25" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:55.235212Z", "iopub.status.busy": "2023-05-20T13:31:55.234321Z", "iopub.status.idle": "2023-05-20T13:31:55.434371Z", "shell.execute_reply": "2023-05-20T13:31:55.433495Z", "shell.execute_reply.started": "2023-05-20T13:31:55.235171Z" } }, "outputs": [], "source": [ "app_test['NAME_TYPE_SUITE'].replace({'Other_A':'Other','Other_B':'Other','Group of people':'Other'},inplace=True)\n", "app_train['NAME_TYPE_SUITE'].replace({'Other_A':'Other','Other_B':'Other','Group of people':'Other'},inplace=True)\n", "\n", "app_test['NAME_INCOME_TYPE'].replace({'Unemployed':'Other','Student':'Other','Maternity leave':'Other'},inplace=True)\n", "app_train['NAME_INCOME_TYPE'].replace({'Unemployed':'Other','Student':'Other','Maternity leave':'Other'},inplace=True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:55.437101Z", "iopub.status.busy": "2023-05-20T13:31:55.436251Z", "iopub.status.idle": "2023-05-20T13:31:55.501346Z", "shell.execute_reply": "2023-05-20T13:31:55.500108Z", "shell.execute_reply.started": "2023-05-20T13:31:55.437061Z" } }, "outputs": [], "source": [ "app_train['ORGANIZATION_TYPE'].value_counts(normalize = True)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:55.502923Z", "iopub.status.busy": "2023-05-20T13:31:55.502602Z", "iopub.status.idle": "2023-05-20T13:31:56.509256Z", "shell.execute_reply": "2023-05-20T13:31:56.508173Z", "shell.execute_reply.started": "2023-05-20T13:31:55.502892Z" } }, "outputs": [], "source": [ "others = app_train['ORGANIZATION_TYPE'].value_counts().index[15:]\n", "label = 'Others'\n", "app_train['ORGANIZATION_TYPE'] = app_train['ORGANIZATION_TYPE'].replace(others, label)\n", "app_test['ORGANIZATION_TYPE'] = app_test['ORGANIZATION_TYPE'].replace(others, label)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:56.511016Z", "iopub.status.busy": "2023-05-20T13:31:56.510708Z", "iopub.status.idle": "2023-05-20T13:31:56.549295Z", "shell.execute_reply": "2023-05-20T13:31:56.548208Z", "shell.execute_reply.started": "2023-05-20T13:31:56.510991Z" } }, "outputs": [], "source": [ "app_train['ORGANIZATION_TYPE'].unique()\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:56.550773Z", "iopub.status.busy": "2023-05-20T13:31:56.550454Z", "iopub.status.idle": "2023-05-20T13:31:57.723469Z", "shell.execute_reply": "2023-05-20T13:31:57.722427Z", "shell.execute_reply.started": "2023-05-20T13:31:56.550746Z" } }, "outputs": [], "source": [ "users_nan = (app_train.isnull().sum() / app_train.shape[0]) * 100\n", "users_nan[users_nan > 0].sort_values(ascending=False)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:57.725953Z", "iopub.status.busy": "2023-05-20T13:31:57.725183Z", "iopub.status.idle": "2023-05-20T13:31:57.925230Z", "shell.execute_reply": "2023-05-20T13:31:57.924092Z", "shell.execute_reply.started": "2023-05-20T13:31:57.725913Z" } }, "outputs": [], "source": [ "users_nan = (app_test.isnull().sum() / app_test.shape[0]) * 100\n", "users_nan[users_nan > 0].sort_values(ascending=False)" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:57.927525Z", "iopub.status.busy": "2023-05-20T13:31:57.927062Z", "iopub.status.idle": "2023-05-20T13:31:58.035594Z", "shell.execute_reply": "2023-05-20T13:31:58.034266Z", "shell.execute_reply.started": "2023-05-20T13:31:57.927486Z" } }, "outputs": [], "source": [ "app_train.drop(['YEARS_EMPLOYED'], axis = 1,inplace=True)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:58.038015Z", "iopub.status.busy": "2023-05-20T13:31:58.037233Z", "iopub.status.idle": "2023-05-20T13:31:58.047706Z", "shell.execute_reply": "2023-05-20T13:31:58.046882Z", "shell.execute_reply.started": "2023-05-20T13:31:58.037972Z" } }, "outputs": [], "source": [ "print(app_train['TARGET'].isnull().sum())\n" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:58.048903Z", "iopub.status.busy": "2023-05-20T13:31:58.048606Z", "iopub.status.idle": "2023-05-20T13:31:58.151234Z", "shell.execute_reply": "2023-05-20T13:31:58.150364Z", "shell.execute_reply.started": "2023-05-20T13:31:58.048879Z" } }, "outputs": [], "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'])\n", "app_test = app_test.drop(columns=['CNT_FAM_MEMBERS','LIVE_REGION_NOT_WORK_REGION', 'REG_REGION_NOT_WORK_REGION', 'OBS_60_CNT_SOCIAL_CIRCLE'])" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:58.153738Z", "iopub.status.busy": "2023-05-20T13:31:58.152637Z", "iopub.status.idle": "2023-05-20T13:31:58.162682Z", "shell.execute_reply": "2023-05-20T13:31:58.161609Z", "shell.execute_reply.started": "2023-05-20T13:31:58.153698Z" } }, "outputs": [ { "data": { "text/plain": [ "['DAYS_EMPLOYED',\n", " 'AMT_ANNUITY',\n", " 'REGION_RATING_CLIENT',\n", " 'REG_CITY_NOT_WORK_CITY',\n", " 'DAYS_ID_PUBLISH',\n", " 'EXT_SOURCE_3',\n", " 'REG_CITY_NOT_LIVE_CITY',\n", " 'AMT_GOODS_PRICE',\n", " 'REGION_RATING_CLIENT_W_CITY',\n", " 'AMT_REQ_CREDIT_BUREAU_WEEK',\n", " 'AMT_REQ_CREDIT_BUREAU_DAY',\n", " 'CNT_CHILDREN',\n", " 'REGION_POPULATION_RELATIVE',\n", " 'AMT_REQ_CREDIT_BUREAU_QRT',\n", " 'AMT_REQ_CREDIT_BUREAU_HOUR',\n", " 'DAYS_REGISTRATION',\n", " 'AMT_INCOME_TOTAL',\n", " 'OBS_30_CNT_SOCIAL_CIRCLE',\n", " 'DAYS_BIRTH',\n", " 'DEF_60_CNT_SOCIAL_CIRCLE',\n", " 'AMT_REQ_CREDIT_BUREAU_YEAR',\n", " 'DAYS_LAST_PHONE_CHANGE',\n", " 'DEF_30_CNT_SOCIAL_CIRCLE',\n", " 'REG_REGION_NOT_LIVE_REGION',\n", " 'AMT_REQ_CREDIT_BUREAU_MON',\n", " 'LIVE_CITY_NOT_WORK_CITY',\n", " 'EXT_SOURCE_2',\n", " 'HOUR_APPR_PROCESS_START']" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "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']\n", "cont_cols = list(set(cont_cols) - set(cols_to_remove))\n", "cont_cols " ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:58.164735Z", "iopub.status.busy": "2023-05-20T13:31:58.164060Z", "iopub.status.idle": "2023-05-20T13:31:58.181015Z", "shell.execute_reply": "2023-05-20T13:31:58.179873Z", "shell.execute_reply.started": "2023-05-20T13:31:58.164703Z" } }, "outputs": [], "source": [ "#Для этого использовался метод межквартильного размаха (IQR), который вычисляет разницу между 75-м и 25-м процентилями значений столбца. \n", "#Затем значения, выходящие за пределы диапазона от Q1-1.5IQR до Q3+1.5IQR, были заменены на медианные значения. \n", "#Это позволило удалить выбросы, которые могли бы исказить результаты анализа\n", "def 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" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:58.183609Z", "iopub.status.busy": "2023-05-20T13:31:58.182750Z", "iopub.status.idle": "2023-05-20T13:31:59.695503Z", "shell.execute_reply": "2023-05-20T13:31:59.694372Z", "shell.execute_reply.started": "2023-05-20T13:31:58.183567Z" } }, "outputs": [], "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])" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:31:59.697622Z", "iopub.status.busy": "2023-05-20T13:31:59.697231Z", "iopub.status.idle": "2023-05-20T13:32:00.311447Z", "shell.execute_reply": "2023-05-20T13:32:00.310304Z", "shell.execute_reply.started": "2023-05-20T13:31:59.697588Z" } }, "outputs": [], "source": [ "app_train['LTV'] = app_train['AMT_CREDIT']/app_train['AMT_GOODS_PRICE']\n", "app_train['DTI'] = app_train['AMT_ANNUITY']/app_train['AMT_INCOME_TOTAL']\n", "app_train['Employed/Birth'] = app_train['DAYS_EMPLOYED']/app_train['DAYS_BIRTH'] \n", "app_train['Flag_Greater_30'] = (app_train['DAYS_BIRTH']/-365.25).apply(lambda x: 1 if x > 30 else 0)\n", "app_train['Flag_Employment_Greater_5'] = (app_train['DAYS_EMPLOYED']/-365.25).apply(lambda x: 1 if x > 5 else 0)\n", "\n", "app_test['LTV'] = app_test['AMT_CREDIT']/app_test['AMT_GOODS_PRICE']\n", "app_test['DTI'] = app_test['AMT_ANNUITY']/app_test['AMT_INCOME_TOTAL']\n", "app_test['Employed/Birth'] = app_test['DAYS_EMPLOYED']/app_test['DAYS_BIRTH']\n", "app_test['Flag_Greater_30'] = (app_test['DAYS_BIRTH']/-365.25).apply(lambda x: 1 if x > 30 else 0)\n", "app_test['Flag_Employment_Greater_5'] = (app_test['DAYS_EMPLOYED']/-365.25).apply(lambda x: 1 if x > 5 else 0)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:32:00.313206Z", "iopub.status.busy": "2023-05-20T13:32:00.312874Z", "iopub.status.idle": "2023-05-20T13:32:01.567866Z", "shell.execute_reply": "2023-05-20T13:32:01.566680Z", "shell.execute_reply.started": "2023-05-20T13:32:00.313179Z" } }, "outputs": [], "source": [ "# for pre-processing\n", "\n", "from sklearn.preprocessing import OrdinalEncoder\n", "from category_encoders import TargetEncoder \n", "from sklearn.model_selection import train_test_split, GridSearchCV, RandomizedSearchCV\n", "\n", "# for machine learning modelling\n", "from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier, AdaBoostClassifier\n", "from sklearn.metrics import roc_auc_score, confusion_matrix" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:32:01.570062Z", "iopub.status.busy": "2023-05-20T13:32:01.569400Z", "iopub.status.idle": "2023-05-20T13:32:01.829177Z", "shell.execute_reply": "2023-05-20T13:32:01.828041Z", "shell.execute_reply.started": "2023-05-20T13:32:01.570028Z" } }, "outputs": [], "source": [ "app_train[cat_col.columns]\n" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:32:01.830751Z", "iopub.status.busy": "2023-05-20T13:32:01.830416Z", "iopub.status.idle": "2023-05-20T13:32:09.292612Z", "shell.execute_reply": "2023-05-20T13:32:09.291189Z", "shell.execute_reply.started": "2023-05-20T13:32:01.830722Z" } }, "outputs": [], "source": [ "enc = TargetEncoder()\n", "app_train[cat_col.columns] = enc.fit_transform(app_train[cat_col.columns], app_train['TARGET'])" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:32:09.294612Z", "iopub.status.busy": "2023-05-20T13:32:09.294260Z", "iopub.status.idle": "2023-05-20T13:32:09.649759Z", "shell.execute_reply": "2023-05-20T13:32:09.648611Z", "shell.execute_reply.started": "2023-05-20T13:32:09.294582Z" } }, "outputs": [], "source": [ "app_test[cat_col.columns] = enc.transform(app_test[cat_col.columns])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:32:09.651347Z", "iopub.status.busy": "2023-05-20T13:32:09.650994Z", "iopub.status.idle": "2023-05-20T13:32:09.716602Z", "shell.execute_reply": "2023-05-20T13:32:09.715380Z", "shell.execute_reply.started": "2023-05-20T13:32:09.651317Z" } }, "outputs": [], "source": [ "X = app_train.drop(columns=['TARGET','SK_ID_CURR'])\n", "y = app_train['TARGET']" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:32:09.718228Z", "iopub.status.busy": "2023-05-20T13:32:09.717870Z", "iopub.status.idle": "2023-05-20T13:32:10.128936Z", "shell.execute_reply": "2023-05-20T13:32:10.127890Z", "shell.execute_reply.started": "2023-05-20T13:32:09.718200Z" } }, "outputs": [], "source": [ "X_train, X_val, y_train, y_val = train_test_split(X, y, train_size=0.8, stratify=y, random_state=42)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:32:10.130697Z", "iopub.status.busy": "2023-05-20T13:32:10.130292Z", "iopub.status.idle": "2023-05-20T13:32:10.138914Z", "shell.execute_reply": "2023-05-20T13:32:10.138142Z", "shell.execute_reply.started": "2023-05-20T13:32:10.130661Z" } }, "outputs": [], "source": [ "# create a function for trained models evaluation\n", "def 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))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:32:10.140749Z", "iopub.status.busy": "2023-05-20T13:32:10.140207Z", "iopub.status.idle": "2023-05-20T13:32:10.159266Z", "shell.execute_reply": "2023-05-20T13:32:10.158427Z", "shell.execute_reply.started": "2023-05-20T13:32:10.140719Z" } }, "outputs": [], "source": [ "#В этом коде мы импортируем модуль RandomForestClassifier из библиотеки sklearn.ensemble и создаем объект модели rf. \n", "#Затем мы обучаем модель на тренировочных данных с помощью метода fit. \n", "#После этого мы используем модель для предсказания классов на тестовых данных с помощью метода predict. \n", "#Наконец, мы оцениваем качество модели на тестовых данных с помощью метрик classification_report и confusion_matrix из библиотеки sklearn.metrics.\n", "rf = RandomForestClassifier(n_estimators=70, max_depth=15, random_state=42)\n", "rf2 = RandomForestClassifier(n_estimators=100, max_depth=15, random_state=5)\n", "rf3 = RandomForestClassifier(n_estimators=75, max_depth=15, random_state=30)\n", "rf4 = RandomForestClassifier(n_estimators=80, max_depth=15, random_state=4)\n", "rf5 = RandomForestClassifier(n_estimators=110, max_depth=15, random_state=12)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:32:10.161145Z", "iopub.status.busy": "2023-05-20T13:32:10.160630Z", "iopub.status.idle": "2023-05-20T13:33:09.115510Z", "shell.execute_reply": "2023-05-20T13:33:09.114353Z", "shell.execute_reply.started": "2023-05-20T13:32:10.161115Z" } }, "outputs": [], "source": [ "rf.fit(X_train, y_train)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:33:09.118112Z", "iopub.status.busy": "2023-05-20T13:33:09.117294Z", "iopub.status.idle": "2023-05-20T13:33:20.276294Z", "shell.execute_reply": "2023-05-20T13:33:20.275200Z", "shell.execute_reply.started": "2023-05-20T13:33:09.118071Z" } }, "outputs": [], "source": [ "evaluate_model(rf)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:33:20.277821Z", "iopub.status.busy": "2023-05-20T13:33:20.277500Z", "iopub.status.idle": "2023-05-20T13:39:25.031720Z", "shell.execute_reply": "2023-05-20T13:39:25.030569Z", "shell.execute_reply.started": "2023-05-20T13:33:20.277794Z" } }, "outputs": [], "source": [ "rf.fit(X_train, y_train)\n", "rf2.fit(X_train, y_train)\n", "rf3.fit(X_train, y_train)\n", "rf4.fit(X_train, y_train)\n", "rf5.fit(X_train, y_train)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:39:25.033314Z", "iopub.status.busy": "2023-05-20T13:39:25.032979Z", "iopub.status.idle": "2023-05-20T13:39:32.327674Z", "shell.execute_reply": "2023-05-20T13:39:32.326682Z", "shell.execute_reply.started": "2023-05-20T13:39:25.033287Z" } }, "outputs": [], "source": [ "y_pred = rf.predict_proba(X_val)\n", "y_pred2 = rf2.predict_proba(X_val)\n", "y_pred3 = rf3.predict_proba(X_val)\n", "y_pred4 = rf4.predict_proba(X_val)\n", "y_pred5 = rf5.predict_proba(X_val)\n", "\n", "y_final = (y_pred+y_pred2+y_pred3+y_pred4+y_pred5)/5" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:39:32.329762Z", "iopub.status.busy": "2023-05-20T13:39:32.328806Z", "iopub.status.idle": "2023-05-20T13:39:32.359062Z", "shell.execute_reply": "2023-05-20T13:39:32.357891Z", "shell.execute_reply.started": "2023-05-20T13:39:32.329729Z" } }, "outputs": [], "source": [ "roc_auc_score(y_val,y_final[:, 1])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T13:39:32.360878Z", "iopub.status.busy": "2023-05-20T13:39:32.360442Z", "iopub.status.idle": "2023-05-20T14:11:50.817174Z", "shell.execute_reply": "2023-05-20T14:11:50.815967Z", "shell.execute_reply.started": "2023-05-20T13:39:32.360850Z" } }, "outputs": [], "source": [ "#была обнаружена проблема несбалансированных классов в задаче бинарной классификации. В данных было намного больше объектов с положительным классом (клиенты, вернувшие кредит вовремя) по сравнению с отрицательным классом (клиенты, не вернувшие кредит вовремя).\n", "#В данном проекте параметр class_weight был установлен в значение \"balanced\". Это значение автоматически вычисляет веса классов, основываясь на их соотношении в данных, и присваивает больший вес редкому классу. \n", "param_grid = {'criterion' : ['gini'],\n", " 'class_weight' : ['balanced_subsample','balanced',None],\n", " 'max_features' : ['sqrt', 'log2']}\n", "\n", "rf2 = RandomForestClassifier(n_estimators=100, max_depth=15, random_state=42)\n", "\n", "grid_cv = RandomizedSearchCV(rf2,param_grid, cv=5, scoring = 'roc_auc')\n", "\n", "grid_cv.fit(X_train, y_train)\n", "\n", "y_pred = grid_cv.predict_proba(X_val)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T14:11:50.818939Z", "iopub.status.busy": "2023-05-20T14:11:50.818505Z", "iopub.status.idle": "2023-05-20T14:11:50.849078Z", "shell.execute_reply": "2023-05-20T14:11:50.848229Z", "shell.execute_reply.started": "2023-05-20T14:11:50.818903Z" } }, "outputs": [], "source": [ "roc_auc_score(y_val, y_pred[:, 1])\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T14:11:50.851110Z", "iopub.status.busy": "2023-05-20T14:11:50.850148Z", "iopub.status.idle": "2023-05-20T14:11:50.858417Z", "shell.execute_reply": "2023-05-20T14:11:50.857314Z", "shell.execute_reply.started": "2023-05-20T14:11:50.851067Z" } }, "outputs": [], "source": [ "grid_cv.best_params_ " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T14:11:50.860918Z", "iopub.status.busy": "2023-05-20T14:11:50.859969Z", "iopub.status.idle": "2023-05-20T14:11:50.875775Z", "shell.execute_reply": "2023-05-20T14:11:50.874346Z", "shell.execute_reply.started": "2023-05-20T14:11:50.860885Z" } }, "outputs": [], "source": [ "rf = RandomForestClassifier(max_features= 'sqrt', criterion ='gini', n_estimators=70, max_depth=15, random_state=42)\n", "rf2 = RandomForestClassifier(max_features= 'sqrt', criterion ='gini',n_estimators=100, max_depth=15, random_state=5)\n", "rf3 = RandomForestClassifier(max_features= 'sqrt', criterion ='gini', n_estimators=75, max_depth=15, random_state=30)\n", "rf4 = RandomForestClassifier(max_features= 'sqrt', criterion ='gini', n_estimators=80, max_depth=15, random_state=4)\n", "rf5 = RandomForestClassifier(max_features= 'sqrt', criterion ='gini', n_estimators=100, max_depth=15, random_state=12)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T14:11:50.877613Z", "iopub.status.busy": "2023-05-20T14:11:50.877205Z", "iopub.status.idle": "2023-05-20T14:18:18.347330Z", "shell.execute_reply": "2023-05-20T14:18:18.346181Z", "shell.execute_reply.started": "2023-05-20T14:11:50.877581Z" } }, "outputs": [], "source": [ "rf.fit(X_train, y_train)\n", "rf2.fit(X_train, y_train)\n", "rf3.fit(X_train, y_train)\n", "rf4.fit(X_train, y_train)\n", "rf5.fit(X_train, y_train)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T14:18:18.349712Z", "iopub.status.busy": "2023-05-20T14:18:18.349232Z", "iopub.status.idle": "2023-05-20T14:18:25.411558Z", "shell.execute_reply": "2023-05-20T14:18:25.410246Z", "shell.execute_reply.started": "2023-05-20T14:18:18.349673Z" } }, "outputs": [], "source": [ "y_pred = rf.predict_proba(X_val)\n", "y_pred2 = rf2.predict_proba(X_val)\n", "y_pred3 = rf3.predict_proba(X_val)\n", "y_pred4 = rf4.predict_proba(X_val)\n", "y_pred5 = rf5.predict_proba(X_val)\n", "\n", "y_final = (y_pred+y_pred2+y_pred3+y_pred4+y_pred5)/5" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T14:18:25.413279Z", "iopub.status.busy": "2023-05-20T14:18:25.412934Z", "iopub.status.idle": "2023-05-20T14:18:25.442617Z", "shell.execute_reply": "2023-05-20T14:18:25.441413Z", "shell.execute_reply.started": "2023-05-20T14:18:25.413252Z" } }, "outputs": [], "source": [ "roc_auc_score(y_val, y_final[:, 1])\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T14:18:25.444762Z", "iopub.status.busy": "2023-05-20T14:18:25.444347Z", "iopub.status.idle": "2023-05-20T14:18:30.865562Z", "shell.execute_reply": "2023-05-20T14:18:30.864401Z", "shell.execute_reply.started": "2023-05-20T14:18:25.444726Z" } }, "outputs": [], "source": [ "test_set_dropID = app_test.drop(columns=['SK_ID_CURR'])\n", "\n", "y_pred = rf.predict_proba(test_set_dropID)\n", "y_pred2 = rf2.predict_proba(test_set_dropID)\n", "y_pred3 = rf3.predict_proba(test_set_dropID)\n", "y_pred4 = rf4.predict_proba(test_set_dropID)\n", "y_pred5 = rf5.predict_proba(test_set_dropID)\n", "\n", "test_proba = (y_pred+y_pred2+y_pred3+y_pred4+y_pred5)/5\n", "\n", "test_proba" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T14:18:30.867184Z", "iopub.status.busy": "2023-05-20T14:18:30.866840Z", "iopub.status.idle": "2023-05-20T14:18:35.987259Z", "shell.execute_reply": "2023-05-20T14:18:35.985576Z", "shell.execute_reply.started": "2023-05-20T14:18:30.867141Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Accuracy: 0.84\n" ] } ], "source": [ "import pandas as pd\n", "from sklearn.model_selection import train_test_split\n", "from sklearn.preprocessing import StandardScaler\n", "from sklearn.linear_model import LogisticRegression\n", "from imblearn.over_sampling import RandomOverSampler\n", "from imblearn.under_sampling import RandomUnderSampler\n", "from imblearn.pipeline import Pipeline\n", "\n", "# Выделение целевой переменной и признаков\n", "y = app_train['TARGET']\n", "X = app_train.drop(['TARGET', 'SK_ID_CURR'], axis=1)\n", "\n", "# Предобработка данных\n", "X = pd.get_dummies(X, dummy_na=True)\n", "\n", "# Разделение данных на обучающую и тестовую выборки\n", "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", "\n", "# Масштабирование признаков\n", "scaler = StandardScaler()\n", "X_train = scaler.fit_transform(X_train)\n", "X_test = scaler.transform(X_test)\n", "\n", "# Балансировка классов\n", "over_sampler = RandomOverSampler(sampling_strategy=0.5, random_state=42)\n", "under_sampler = RandomUnderSampler(sampling_strategy=0.5, random_state=42)\n", "steps = [('o', over_sampler), ('u', under_sampler)]\n", "pipeline = Pipeline(steps=steps)\n", "X_train, y_train = pipeline.fit_resample(X_train, y_train)\n", "\n", "# Создание и обучение модели логистической регрессии\n", "lr = LogisticRegression(random_state=42, max_iter=1000)\n", "lr.fit(X_train, y_train)\n", "\n", "# Оценка качества модели\n", "y_pred = lr.predict(X_test)\n", "score = lr.score(X_test, y_test)\n", "print(f\"Accuracy: {score:.2f}\")\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T14:18:36.000219Z", "iopub.status.busy": "2023-05-20T14:18:35.994257Z", "iopub.status.idle": "2023-05-20T14:18:39.477868Z", "shell.execute_reply": "2023-05-20T14:18:39.476591Z", "shell.execute_reply.started": "2023-05-20T14:18:36.000123Z" } }, "outputs": [], "source": [ "from sklearn.preprocessing import MinMaxScaler\n", "from sklearn.impute import SimpleImputer\n", "\n", "# Уберем таргет из тренировочных данных\n", "if 'TARGET' in app_train:\n", " train = app_train.drop(labels = ['TARGET'], axis=1)\n", "else:\n", " train = app_train.copy()\n", "features = list(train.columns)\n", "\n", "# копируем тестовые данные\n", "test = app_test.copy()\n", "\n", "# заполним недостающее по медиане\n", "imputer = SimpleImputer(strategy = 'median')\n", "\n", "# Нормализация\n", "scaler = MinMaxScaler(feature_range = (0, 1))\n", "\n", "# заполнение тренировочной выборки\n", "imputer.fit(train)\n", "\n", "# Трансофрмация тренировочной и тестовой выборок\n", "train = imputer.transform(train)\n", "test = imputer.transform(app_test)\n", "\n", "# то же самое с нормализацией\n", "scaler.fit(train)\n", "train = scaler.transform(train)\n", "test = scaler.transform(test)\n", "\n", "print('Формат тренировочной выборки: ', train.shape)\n", "print('Формат тестовой выборки: ', test.shape)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T14:18:39.479523Z", "iopub.status.busy": "2023-05-20T14:18:39.479177Z", "iopub.status.idle": "2023-05-20T14:18:39.485527Z", "shell.execute_reply": "2023-05-20T14:18:39.484180Z", "shell.execute_reply.started": "2023-05-20T14:18:39.479495Z" } }, "outputs": [], "source": [ "#сохраним лейблы, их же нет в тестовой выборке и при выравнивании они потеряются. \n", "train_labels = app_train['TARGET']\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T14:18:39.487559Z", "iopub.status.busy": "2023-05-20T14:18:39.487213Z", "iopub.status.idle": "2023-05-20T14:18:41.025224Z", "shell.execute_reply": "2023-05-20T14:18:41.023847Z", "shell.execute_reply.started": "2023-05-20T14:18:39.487524Z" } }, "outputs": [], "source": [ "from sklearn.linear_model import LogisticRegression\n", "\n", "log_reg = LogisticRegression(C = 0.0001)\n", "\n", "# Тренируем модель\n", "log_reg.fit(train, train_labels)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T14:18:41.028122Z", "iopub.status.busy": "2023-05-20T14:18:41.027496Z", "iopub.status.idle": "2023-05-20T14:18:41.049477Z", "shell.execute_reply": "2023-05-20T14:18:41.045337Z", "shell.execute_reply.started": "2023-05-20T14:18:41.028067Z" } }, "outputs": [], "source": [ "log_reg_pred = log_reg.predict_proba(test)[:, 1]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T14:18:41.062026Z", "iopub.status.busy": "2023-05-20T14:18:41.056355Z", "iopub.status.idle": "2023-05-20T14:18:41.102101Z", "shell.execute_reply": "2023-05-20T14:18:41.100425Z", "shell.execute_reply.started": "2023-05-20T14:18:41.061968Z" } }, "outputs": [], "source": [ "submit = app_test[['SK_ID_CURR']]\n", "submit['TARGET'] = log_reg_pred\n", "\n", "submit.head()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T14:18:41.117055Z", "iopub.status.busy": "2023-05-20T14:18:41.113664Z", "iopub.status.idle": "2023-05-20T14:18:41.147320Z", "shell.execute_reply": "2023-05-20T14:18:41.146231Z", "shell.execute_reply.started": "2023-05-20T14:18:41.116973Z" } }, "outputs": [], "source": [ "from sklearn.metrics import roc_auc_score\n", "\n", "roc_auc = roc_auc_score(y_test, y_pred)\n", "print(f'ROC AUC: {roc_auc:.4f}')" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T14:49:11.499710Z", "iopub.status.busy": "2023-05-20T14:49:11.499330Z", "iopub.status.idle": "2023-05-20T14:49:11.509280Z", "shell.execute_reply": "2023-05-20T14:49:11.508028Z", "shell.execute_reply.started": "2023-05-20T14:49:11.499682Z" } }, "outputs": [], "source": [ "def protected_division(x1, x2):\n", " if x2 == 0:\n", " return 1 # Защита от деления на ноль\n", " else:\n", " return x1 / x2\n", "\n", "def protected_sqrt(x):\n", " if x < 0:\n", " return 0 # Защита от извлечения квадратного корня из отрицательного числа\n", " else:\n", " return np.sqrt(x)\n", "\n", "def protected_log(x):\n", " if x <= 0:\n", " return 0 # Защита от логарифма от неположительного числа или нуля\n", " else:\n", " return np.log(x)\n" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T14:47:45.251432Z", "iopub.status.busy": "2023-05-20T14:47:45.250984Z", "iopub.status.idle": "2023-05-20T14:47:45.261277Z", "shell.execute_reply": "2023-05-20T14:47:45.260147Z", "shell.execute_reply.started": "2023-05-20T14:47:45.251396Z" } }, "outputs": [], "source": [ "import numpy as np\n", "import pandas as pd\n", "from deap import creator, base, tools, gp\n", "# Определение функций и операций для генерации новых признаков\n", "\n", "# fix 1 --- genetic programming (GP) individuals are only designed to work with 2 input variables, but should align with training dataset\n", "# pset = gp.PrimitiveSet(\"MAIN\", arity=2)\n", "pset = gp.PrimitiveSet(\"MAIN\", arity=X_train.shape[1])\n", " \n", "pset.addPrimitive(np.add, arity=2)\n", "pset.addPrimitive(np.subtract, arity=2)\n", "pset.addPrimitive(np.multiply, arity=2)\n", "pset.addPrimitive(np.maximum, arity=2)\n", "pset.addPrimitive(np.minimum, arity=2)\n", "pset.addPrimitive(protected_division, arity=2)\n", "pset.addPrimitive(protected_sqrt, arity=1)\n", "pset.addPrimitive(protected_log, arity=1)\n", "pset.addPrimitive(np.sin, arity=1)\n", "pset.addPrimitive(np.cos, arity=1)\n", "pset.addTerminal(0)\n", "pset.addTerminal(1)" ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T14:49:14.993876Z", "iopub.status.busy": "2023-05-20T14:49:14.993461Z", "iopub.status.idle": "2023-05-20T14:49:15.005150Z", "shell.execute_reply": "2023-05-20T14:49:15.003875Z", "shell.execute_reply.started": "2023-05-20T14:49:14.993845Z" } }, "outputs": [], "source": [ "# Создание класса для управления эволюцией\n", "creator.create(\"FitnessMax\", base.Fitness, weights=(1.0,))\n", "creator.create(\"Individual\", gp.PrimitiveTree, fitness=creator.FitnessMax)\n", "\n", "# Инициализация пакета инструментов\n", "toolbox = base.Toolbox()\n", "\n", "# Определение функций и операций, которые могут быть использованы для создания новых признаков\n", "toolbox.register(\"expr\", gp.genHalfAndHalf, pset=pset, min_=1, max_=3)\n", "toolbox.register(\"individual\", tools.initIterate, creator.Individual, toolbox.expr)\n", "toolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)\n", "\n", "# Определение операторов мутации, скрещивания и оценки фитнеса\n", "toolbox.register(\"mate\", gp.cxOnePoint)\n", "toolbox.register(\"mutate\", gp.mutUniform, expr=toolbox.expr, pset=pset)\n", "toolbox.register(\"evaluate\", evaluate_fitness)\n", "toolbox.register(\"select\", tools.selTournament, tournsize=3)" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T14:58:23.426108Z", "iopub.status.busy": "2023-05-20T14:58:23.425722Z", "iopub.status.idle": "2023-05-20T14:58:23.435016Z", "shell.execute_reply": "2023-05-20T14:58:23.433744Z", "shell.execute_reply.started": "2023-05-20T14:58:23.426080Z" } }, "outputs": [], "source": [ "# Определение функции преобразования ГП структуры в вектор признаков\n", "def transform_gp_structure(individual, X):\n", " expr = gp.compile(individual, pset)\n", " return np.array([expr(*row) for row in X])\n", "\n", "# Определение функции оценки фитнеса (ваша собственная функция)\n", "def evaluate_fitness(individual):\n", " # Вычислите значения признаков на основе individual\n", " \n", " # fix 2 --- shape mismatch\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", " X_train_gp = transform_gp_structure(individual, X_train).reshape(-1, 1)\n", " rf_model_gp = lr\n", " rf_model_gp.fit(X_train_gp, y_train)\n", " X_test_gp = transform_gp_structure(individual, X_test).reshape(-1, 1)\n", " \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," ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "execution": { "iopub.execute_input": "2023-05-20T14:58:26.121638Z", "iopub.status.busy": "2023-05-20T14:58:26.121249Z", "iopub.status.idle": "2023-05-20T14:58:26.216633Z", "shell.execute_reply": "2023-05-20T14:58:26.215421Z", "shell.execute_reply.started": "2023-05-20T14:58:26.121608Z" } }, "outputs": [], "source": [ "import random # fix missing import for crash isolation purposes\n", "crossover_prob = 0.5\n", "mutation_prob = 0.5\n", "\n", "pop_size = 10 #100 # Размер популяции\n", "num_generations = 2 #50 # Количество поколений\n", "\n", "# Создание начальной популяции\n", "population = toolbox.population(n=pop_size)\n", "\n", "# Основной цикл эволюции\n", "for 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" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.12" } }, "nbformat": 4, "nbformat_minor": 4 }