{"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# StandardScaler\nfrom sklearn.preprocessing import StandardScaler\n# used for feature selection\nfrom sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import chi2\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import train_test_split\n# to handle imbalanced data set\nfrom imblearn.over_sampling import SMOTE\nfrom collections import Counter\n# performance\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import auc\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import mean_squared_error\n\n# PCA\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import LabelEncoder\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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"%%time\n# Load data\ntrain = pd.read_csv('../input/cat-in-the-dat-ii/train.csv')\ntest = pd.read_csv('../input/cat-in-the-dat-ii/test.csv')\n\nprint(train.shape)\nprint(test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Change boolean value to int so as to encode\ntrain['bin_3'] = train['bin_3'].apply(lambda x: 1 if x=='T' else 0)\ntrain['bin_4'] = train['bin_4'].apply(lambda x:1 if x =='Y' else 0)\ntest['bin_3'] = test['bin_3'].apply(lambda x:1 if x=='T' else 0)\ntest['bin_4'] = test['bin_4'].apply(lambda x:1 if x == 'Y' else 0)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Replace NAN "},{"metadata":{"trusted":true},"cell_type":"code","source":"def replace_nan(data):\n    for column in data.columns:\n        if data[column].isna().sum() > 0:\n            data[column] = data[column].fillna(data[column].mode()[0])\n\n\nreplace_nan(train)\nreplace_nan(test)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Label Encoder \n"},{"metadata":{"trusted":true},"cell_type":"code","source":"features = []\n\nfor col in train.columns[:-1]:\n    rd = LabelEncoder()\n    rd.fit_transform( train[col].append( test[col] ) )\n    train[col] = rd.transform( train[col] )\n    test [col] = rd.transform( test [col] )\n    features.append(col)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Train Sample\")\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Test Sample\")\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## Train\nX_data = train.iloc[:,0:24]\ny_data = train.iloc[:,-1]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Standard Scaler"},{"metadata":{"trusted":true},"cell_type":"code","source":"standard_scaler = preprocessing.StandardScaler()\nX_standard_scaled_df = standard_scaler.fit_transform(X_data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_standard_scaled_df = pd.DataFrame(data=X_standard_scaled_df[:,:], columns=['id','V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10',\n       'V11', 'V12', 'V13', 'V14', 'V15', 'V16', 'V17', 'V18', 'V19', 'V20',\n       'V21', 'day', 'month',])  ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Principal Component Analysis"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Make an instance of the Model\npca = PCA(10)\npca_selected = pca.fit_transform(X_standard_scaled_df)\npca_selected_df = pd.DataFrame(data=pca_selected[:,:])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('After PCA' , pca_selected_df.head())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ready_data = pca_selected_df.join(y_data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('After Target' , ready_data.head())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_class_0 = ready_data[ready_data['target']==0]\nprint(data_class_0.shape)\ndata_class_1 = ready_data[ready_data['target']==1]\nprint(data_class_1.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_0 = data_class_0.iloc[:,0:-1]  #independent columns\ny_0 = data_class_0.iloc[:,-1]    #target column i.e Class\n\nX_1 = data_class_1.iloc[:,0:-1]  #independent columns\ny_1 = data_class_1.iloc[:,-1]    #target column i.e Class\n\n# def train_gen():\nX_train_0, X_test_0, y_train_0, y_test_0 = train_test_split(X_0, y_0, test_size=0.33, random_state=42)\nX_train_1, X_test_1, y_train_1, y_test_1 = train_test_split(X_1, y_1, test_size=0.33, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = pd.concat([X_train_0, X_train_1])\ny_train = pd.concat([y_train_0, y_train_1])\nX_test = pd.concat([X_test_0 , X_test_1])\ny_test = pd.concat([y_test_0 , y_test_1])\n\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Original dataset shape %s' % Counter(y_train))\nsm = SMOTE(random_state=42)\nX_res, y_res = sm.fit_resample(X_train, y_train)\nprint('Resampled dataset shape using smote %s' % Counter(y_res))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# XGBClassifier"},{"metadata":{"trusted":true},"cell_type":"code","source":" from xgboost import XGBClassifier","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"XGB_classifier = XGBClassifier(max_depth=20,n_estimators=2020,colsample_bytree=0.20,learning_rate=0.020,objective='binary:logistic', n_jobs=-1)\nXGB_classifier.fit(X_train,y_train, eval_metric = 'aucpr')\n#aucpr: Area under the PR curve","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"XGB_classifier_predict_smote = XGB_classifier.predict(X_test)\nprint(XGB_classifier.score(X_train,y_train))\nprint(np.sqrt(mean_squared_error(XGB_classifier_predict_smote,y_test)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"accuracy_score(y_test,XGB_classifier_predict_smote)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(classification_report(y_test,XGB_classifier_predict_smote))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Test Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"test.head(1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"standard_scaler = preprocessing.StandardScaler()\ntest_standard_scaled_df = standard_scaler.fit_transform(test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_standard_scaled_df = pd.DataFrame(data=test_standard_scaled_df[:,:], columns=['id','V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10',\n       'V11', 'V12', 'V13', 'V14', 'V15', 'V16', 'V17', 'V18', 'V19', 'V20',\n       'V21', 'day', 'month',]) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pca_selected = pca.fit_transform(test_standard_scaled_df)\npca_selected_df = pd.DataFrame(data=pca_selected[:,:])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"XGB_classifier.fit(X_train,y_train, eval_metric = 'aucpr')\ntest = XGB_classifier.predict(pca_selected_df)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_score = XGB_classifier.predict(pca_selected_df)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission = pd.read_csv(\"../input/cat-in-the-dat-ii/sample_submission.csv\")\nsample_submission.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission['target'] = test_score","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission.to_csv('submission_xgboost_v1.csv', index=False)","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}