{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# 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\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Data Understanding and Cleansing**"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"#Reading the Train file \nX_train=pd.read_csv(\"/kaggle/input/cat-in-the-dat-ii/train.csv\")\nX_train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Reading Test file\nX_test=pd.read_csv(\"/kaggle/input/cat-in-the-dat-ii/test.csv\")\nX_test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Identifying Missing Values perecntage of train data set\nround((X_train.isnull().sum()/len(X_train)*100),2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Identifying Missing Values perecntage of test data set\nround((X_test.isnull().sum()/len(X_test)*100),2)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"As above columns contins around ~3% of NULL values, It is good to impute with Mean for Numerical columns and Mode for Categorical Columns."},{"metadata":{"trusted":true},"cell_type":"code","source":"# Get list of categorical variables\ns = X_train.select_dtypes(include=['object'])\nCat_cols=s.columns.to_list()\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"We will impute above categorical columns with Mode."},{"metadata":{"trusted":true},"cell_type":"code","source":"#Imputing Missg Values with Mode() for categorical columns\nfor c in Cat_cols:\n    X_train[c].fillna(X_train[c].mode()[0], inplace = True)  \nround((X_train.isnull().sum()/len(X_train)*100),2)    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Imputing Missg Values with Mode() for categorical columns-Test data set\nfor c in Cat_cols:\n    X_test[c].fillna(X_test[c].mode()[0], inplace = True)  \nround((X_test.isnull().sum()/len(X_test)*100),2)  ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"Next is to impute Numerical columns with Mean value"},{"metadata":{"trusted":true},"cell_type":"code","source":"Num_cols =X_train.select_dtypes(include=['int64','float']).columns.to_list()\nNum_cols.pop(Num_cols.index('id'))  #Removing ID as it not requried\nNum_cols\n\n\nfor c in Num_cols:\n    X_train[c].fillna(np.mean(X_train[c]), inplace = True)  \nround((X_train.isnull().sum()/len(X_train)*100),2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Test Dataset\nNum_cols =X_test.select_dtypes(include=['int64','float']).columns.to_list()\nNum_cols.pop(Num_cols.index('id'))  #Removing ID as it not requried\nNum_cols\n\n\nfor c in Num_cols:\n    X_test[c].fillna(np.mean(X_test[c]), inplace = True)  \nround((X_test.isnull().sum()/len(X_test)*100),2)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Now data set contain no NULL values and  is ready for EDA"},{"metadata":{"trusted":true},"cell_type":"code","source":"\nbin_cols = [col for col in X_train if col.startswith('bin')]\n\nfor i in bin_cols:\n    print([i],X_train[i].unique())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"bin_cols = [col for col in X_test if col.startswith('bin')]\n\nfor i in bin_cols:\n    print([i],X_test[i].unique())","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"binary variables bin_0,bin_1,bin_2 contains decimal as well. we will convert it into either 0 or 1 based on threshold"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Converting into Binary values\nfor i in bin_cols[:3]:\n    X_train[i]=X_train[i].apply(lambda x : 1 if x>0.5 else 0)\n    \nfor i in bin_cols[:3]:\n    X_test[i]=X_test[i].apply(lambda x : 1 if x>0.5 else 0)    \n     ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train['bin_0'].unique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import seaborn as sns\nimport matplotlib.pyplot as plt ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Binary variable visualisation\n\nfor i in bin_cols:\n    sns.countplot(x=i, hue=\"target\", data=X_train)\n    plt.title(i)\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Bin_3 and Bin_4- We convert categorical into Binary values\nX_train['bin_3']=X_train['bin_3'].apply(lambda x : 1 if 'F' else 'T')\nX_train['bin_4']=X_train['bin_2'].apply(lambda x : 1 if 'N' else 'Y')\n\n# Test set\nX_test['bin_3']=X_test['bin_3'].apply(lambda x : 1 if 'F' else 'T')\nX_test['bin_4']=X_test['bin_2'].apply(lambda x : 1 if 'N' else 'Y')\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train[bin_cols].head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Now Binary columns are ready for Modelling. Next is to encoding nominal and ordinary variables"},{"metadata":{"trusted":true},"cell_type":"code","source":"ord_cols = [col for col in X_train if col.startswith('ord')]\n\nfor i in ord_cols:\n    print([i],X_train[i].unique())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"nominal_cols = [col for col in X_train if col.startswith('nom')]\n\nfor i in nominal_cols:\n    print([i],X_train[i].unique())","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Categorical Encoding**"},{"metadata":{},"cell_type":"markdown","source":"We have to do encoding for Categorical variables. For Nominal , it is better to do by One Hot Encoding"},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cat_cols_encoding= X_train.select_dtypes(include=['object']).columns.to_list()\nX_test[cat_cols_encoding].head()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# X_train[cat_cols_encoding].head()\nX_test.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"# we will do Random Forest Method to Identify the target. for that we will do Label encoding.\n\n\ncat_cols_encoding= X_train.select_dtypes(include=['object']).columns.to_list()\n\nfrom sklearn.preprocessing import LabelEncoder\n\n# Apply label encoder to each column with categorical data\nlabel_encoder = LabelEncoder()\n\nfor col in cat_cols_encoding:\n    X_train[c]= label_encoder.fit_transform(X_train[c])\n \n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for c in cat_cols_encoding:\n    X_test[c] = label_encoder.transform(X_test[c])","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}