{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"#####################################\n# Developed by Baptiste PICARD      #\n# picard.baptiste@laposte.net       #\n# Started the 06th of March 2020    #\n# picard.baptiste@laposte.net       #\n#                                   #\n#####################################\n# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\n# Utils \nimport os\nimport time \nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n# Modules from sklearn for preprocessing.\nfrom sklearn.metrics import accuracy_score, roc_auc_score\nfrom sklearn.model_selection import train_test_split\nfrom category_encoders.target_encoder import TargetEncoder\nfrom sklearn.preprocessing import LabelEncoder, StandardScaler\n\n# Modules from sklearn for classification/regression.\nimport xgboost as xgb\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\n\n# Environment \npd.set_option('display.max_columns', 125)\n\n# Constants \ntrain_set = '../input/cat-in-the-dat-ii/train.csv'\ntest_set = '../input/cat-in-the-dat-ii/test.csv'\nsubmission_set = '../input/cat-in-the-dat-ii/sample_submission.csv'\nSTANDARD_SCALER = True\nOUTLIERS = True\nDUMMIES = False\nGRAFS = True\nMAX = False\n\n#print(\"The actual path : {}.'.format(os.getcwd()))\nprint('The project is set up.')\nprint('OPTION || SCALER = {}, DUMMIES = {}, GRAFS = {}, MAX = {}, OUTLIER = {}.'.format(STANDARD_SCALER, DUMMIES, GRAFS, MAX, OUTLIERS))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"df_train = pd.read_csv(train_set, index_col='id')\ndf_test = pd.read_csv(test_set, index_col='id')\ndf_sub = pd.read_csv(submission_set)\nn_rows, n_columns = df_train.shape\ncolumn_names = df_train.columns\nprint(\"Initialy, the train set is composed by {} and the test set by {}.\".format(df_train.shape, (df_test.shape)))\n\ntargets = df_train.target\ndf_train = df_train.drop('target', axis=1)\nif(df_train.shape[1] == df_test.shape[1]) :\n    df = pd.concat([df_train, df_test])\nprint(\"Now, I have a set composed by {}.\".format(df.shape))\ndf.head(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if(GRAFS):\n    plt.figure(figsize=(13,7))\n    plt.subplot(121)\n    plt.title(\"Target distribution in the set\")\n    ax = sns.countplot(targets)\n    for patch in ax.patches : \n        ax.text(patch.get_x() + patch.get_width()/3,\n                patch.get_height()*1.02 ,\n                \"{}%\".format(patch.get_height()/len(df_train) * 100))\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"bins = ['bin_0', 'bin_1', 'bin_2', 'bin_3', 'bin_4']\nfor index, c_bin in enumerate(bins) :\n    missing_values = df[c_bin].isnull().sum()\n    if(df[c_bin].dtype == np.object) :\n        if(c_bin == 'bin_3') : \n            df[c_bin] = df[c_bin].apply(lambda x: 0.0 if x == 'F' else 1.0)\n        elif(c_bin == 'bin_4') : \n            df[c_bin] = df[c_bin].apply(lambda x: 0.0 if x == 'N' else 1.0)\n        pd.to_numeric(df[c_bin])\n    if(MAX) : \n        val = df[c_bin].value_counts().index[0]\n    else : \n        val = df[c_bin].median()\n    df[c_bin] = df[c_bin].fillna(val)\n    print(\"From {} to {} missing values in the column : {} | filled value = {}.\".format(missing_values, df[c_bin].isnull().sum(), c_bin, val))\nprint(\"Bins filled and encoded.\")\nif(GRAFS) :\n    for c_bin in bins :        \n        plt.figure(figsize=(13,7))\n        plt.subplot(121)\n        plt.title(\"Target distribution of \"+c_bin)\n        ax = sns.countplot(df[c_bin])\n        for patch in ax.patches : \n            ax.text(patch.get_x() + patch.get_width()/3,\n                    patch.get_height()*1.02 ,\n                    \"{}%\".format(patch.get_height()/len(df) * 100))\n        plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_names =  ['nom_0', 'nom_1', 'nom_2', 'nom_3', 'nom_4', \"nom_5\", \"nom_6\", \"nom_7\", \"nom_8\", \"nom_9\"]   \ncat_to_show = ['nom_0', 'nom_1', 'nom_2', 'nom_3', 'nom_4']\nfor index, c_name in enumerate(all_names) :\n    missing_values = df[c_name].isnull().sum()\n    if(MAX) : \n        val = df[c_name].value_counts().index[0]\n    else : \n        val = df[c_name].mode()[0]\n    df[c_name] = df[c_name].fillna(val)\n    encoder = LabelEncoder()\n    df[c_name] = encoder.fit_transform(df[c_name])\n    print(\"From {} to {} missing values in the column : {} | filled value = {}.\".format(missing_values, df[c_name].isnull().sum(), c_name, val))\nprint(\"Categorical's name columns filled and encoded.\\n\") \nif(GRAFS) :\n    for column in cat_to_show :        \n        plt.figure(figsize=(13,7))\n        plt.subplot(121)\n        plt.title(\"Target distribution of \"+column)\n        ax = sns.countplot(df[column])\n        for patch in ax.patches : \n            ax.text(patch.get_x() + patch.get_width()/3,\n                    patch.get_height()*1.02 ,\n                    \"{}%\".format(patch.get_height()/len(df) * 100))\n        plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ordinal_categories = ['ord_0', 'ord_1', 'ord_2', 'ord_3', 'ord_4', 'ord_5'] # Too many values in ord_5\nfor c_name in ordinal_categories : \n    missing_values = df[c_name].isnull().sum()\n    if(c_name == 'ord_5') : \n        items_to_keep = list(df_train[c_name].value_counts()[:15].index)\n        df[c_name] = df[c_name].apply(lambda x: 'Other' if x not in items_to_keep else x) \n    if(MAX) : \n        val = df[c_name].value_counts().index[0]\n    else : \n        val = df[c_name].mode()[0]\n    df[c_name] = df[c_name].fillna(val)\n    encoder = LabelEncoder()\n    df[c_name] = encoder.fit_transform(df[c_name])\n    print(\"From {} to {} missing values in the column : {} | filled value = {}.\".format(missing_values, df[c_name].isnull().sum(), c_name, val))\nprint(\"Ordinal columns filled.\\n\")\nif(GRAFS) :\n    for column in ordinal_categories :        \n        plt.figure(figsize=(13,7))\n        plt.subplot(121)\n        plt.title(\"Target distribution of \"+column)\n        ax = sns.countplot(df[column])\n        for patch in ax.patches : \n            ax.text(patch.get_x() + patch.get_width()/3,\n                    patch.get_height()*1.02 ,\n                    \"{}%\".format(patch.get_height()/len(df) * 100))\n        plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datetime_categories = ['day', \"month\"] \nfor c_name in datetime_categories : \n    missing_values = df[c_name].isnull().sum()\n    if(MAX) : \n        val = df[c_name].value_counts().index[0]\n    else : \n        val = df[c_name].mode()[0]\n    df[c_name] = df[c_name].fillna(val)\n    print(\"From {} to {} missing values in the column : {} | filled value = {}.\".format(missing_values, df[c_name].isnull().sum(), c_name, val))\nprint(\"Day and month columns filled.\\n\")\nif(GRAFS) :\n    for column in datetime_categories :        \n        plt.figure(figsize=(13,7))\n        plt.subplot(121)\n        plt.title(\"Target distribution of \"+column)\n        ax = sns.countplot(df[column])\n        for patch in ax.patches : \n            ax.text(patch.get_x() + patch.get_width()/3,\n                    patch.get_height(),\n                    \"{}%\".format(patch.get_height()/len(df) * 100))\n        plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nif(STANDARD_SCALER) :\n    print('Normalizing the data with scaler.')\n    scaler = StandardScaler()\n    df[df.columns] = scaler.fit_transform(df[df.columns])\nif(DUMMIES) :\n    print('Normalizing the data with dummies.')\n    columns_to_keep = ['bin_0', 'bin_1', 'bin_2',  'bin_3', 'bin_4', 'nom_5', 'nom_6', 'nom_7', 'nom_8','nom_9']\n    df_tokeep = df[columns_to_keep]\n    df = df.drop(columns_to_keep, axis=1)\n    \n    for col in df.columns : \n        train = pd.get_dummies(df[col])\n        for column in train.columns : \n            df_tokeep[str(col)+'_'+str(column)] = train[column]\n    df = df_tokeep.copy()\ndf_train = df[:n_rows]\ndf_test = df[n_rows:]\nif(OUTLIERS) : # 1 on 23 -> 36% outliers / 3 on 23 -> >1%%\n    print(\"Detecting outliers\")\n    start_time = time.time()\n    threshold = 1.5 \n    nb_detect = 3\n    Q1 = df_train.quantile(0.25)\n    Q3 = df_train.quantile(0.75)\n    IQR = Q3 - Q1\n    outliers = []\n    outlier_matrix = (df_train < (Q1 - threshold * IQR)) |(df_train > (Q3 + threshold * IQR))\n    for index_row, row in outlier_matrix.iterrows() :\n        cmpt = 0\n        for item in row : \n            if(item==True) : \n                cmpt += 1 \n                if(index_row not in outliers and cmpt>=nb_detect) :\n                    outliers.append(index_row)\n                    break\n    print(\"There are {}% of outliers (exactly {} outliers) in the train set.\".format((len(outliers)/len(df_train)), len(outliers)))\n    print(\"It takes {} minutes to detect outliers.\".format((time.time() - start_time)/60))\n    try :\n        print(\"{} outliers were dropped.\".format(len(outliers)))\n        df_train = df_train.drop(outliers)\n        targets = targets.drop(outliers)\n    except : \n        print(\"Can't drop outliers\")\nX_train, X_test, y_train, y_test = train_test_split(df_train, targets, test_size=0.1, random_state=42)\nprint(\"X_train : {}, X_test : {}, y_train : {}, y_test : {}\".format(X_train.shape, X_test.shape, y_train.shape, y_test.shape))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nmodels = [\n            {'name' : 'LogisticRegression', 'model' : LogisticRegression(), 'predictions' : None, \"auc\" : 0.0, 'accuracy' : 0.0, 'training_time' : 0.0, 'prediction_time' : 0.0},\n            {'name' : 'GradientBoostingClassifier', 'model' : GradientBoostingClassifier(), 'predictions' : None, \"auc\" : 0.0, 'accuracy' : 0.0, 'training_time' : 0.0, 'prediction_time' : 0.0},\n            {'name' : 'XGBClassifier', 'model' : xgb.XGBClassifier(), 'predictions' : None, \"auc\" : 0.0, 'accuracy' : 0.0, 'training_time' : 0.0, 'prediction_time' : 0.0},\n            {'name' : 'RandomForestClassifier', 'model' : RandomForestClassifier(), 'predictions' : None, \"auc\" : 0.0, 'accuracy' : 0.0, 'training_time' : 0.0, 'prediction_time' : 0.0}\n]\nfor index_model, model in enumerate(models) : \n    print(\"Model {} : {}.\".format(index_model, model['name']))\n    training_time = time.time()\n    model['model'].fit(X_train, y_train)\n    model['training_time'] = (time.time() - training_time)/60\n    print(\"Model {} : {} completed training.\".format(index_model, model['name']))\n    predict_time = time.time()\n    y_pred = model['model'].predict_proba(X_test)[:,1]\n    pred = model['model'].predict_proba(df_test)[:,1]\n    model['predictions'] = pred\n    print(\"Model {} : {} completed predicting.\".format(index_model, model['name']))\n    model['auc'] = roc_auc_score(y_test, y_pred) \n    model['accuracy'] = accuracy_score(y_test, y_pred.round()) \n    model['prediction_time'] = (time.time() - predict_time)/60\n    print(\"Model {} : {} reachs the end in {} minutes.\".format(index_model, model['name'], (time.time() - training_time)/60))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if(GRAFS) : \n    df_results = {'model' : [], 'auc (%)' : [], 'accuracy (%)' : [], 'training_time (minutes)' : []}\n    for model in models : \n        df_results['model'].append(model['name'])\n        df_results['auc (%)'].append(model['auc'])\n        df_results['accuracy (%)'].append(model['accuracy'])\n        df_results['training_time (minutes)'].append(model['training_time'])\n    df_results = pd.DataFrame(df_results)\n    print(df_results)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"try : \n    if(len(predictions_reg) == df_sub.shape[0]):\n        df_sub.target = models[0]['predictions']\n        df_sub.to_csv(submission_set, index=False)\nelse : \n    print(\"There is a problem uploading the results in the .csv file.\")\nprint(\"Ending the kernel - Thank to read.\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}