{"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\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 read-only \"../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# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.preprocessing import OneHotEncoder\noh = OneHotEncoder()\nimport gc","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/cat-in-the-dat-ii/train.csv')\ntest = pd.read_csv('/kaggle/input/cat-in-the-dat-ii/test.csv')\ntrain = train[:50000]\ntrain","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_id = test.id\ntrain_target = train.target","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.concat((train.loc[:,'bin_0':'month'], test.loc[:,'bin_0':'month']))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# before tuning\n\ndef basic_details(df):\n    b = pd.DataFrame()\n    b['Missing value, %'] = round(df.isnull().sum()/df.shape[0]*100)\n    b['N unique value'] = df.nunique()\n    b['dtype'] = df.dtypes\n    return b\nbasic_details(df)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_cols = df.select_dtypes(exclude=['object']).columns\nfig, ax = plt.subplots(2,3,figsize=(22,7))\nfor i, col in enumerate(num_cols):\n    plt.subplot(2,3,i+1)\n    plt.xlabel(col, fontsize=9)\n    sns.kdeplot(df[col].values, bw=0.5)  \nplt.show() ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# simplest NaN imputation\n\nfor col in df:\n    if df[col].dtype == 'object':        \n        df[col].fillna('N', inplace=True)\n    else: df[col].fillna(-10000, inplace=True)\n\n# df = df.dropna()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def basic_details(df):\n    b = pd.DataFrame()\n    b['Missing value, %'] = round(df.isnull().sum()/df.shape[0]*100)\n    b['N unique value'] = df.nunique()\n    b['dtype'] = df.dtypes\n    return b\nbasic_details(df)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#label encoding for high shape object columns    \nhigh_shape_features = ['nom_5', 'nom_6', 'nom_7', 'nom_8', 'nom_9', 'ord_5']\nle = LabelEncoder()\nfor col in high_shape_features:\n    df[col] = le.fit_transform(df[col].astype(str))\n\n# one hot encoding of low shape features\n    \nfor col in df:\n    if df[col].nunique()<=27:\n        df[col] = df[col].astype(str)\ndf = pd.get_dummies(df)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"columns = [i for i in df.columns]\ndummies = pd.get_dummies(df,columns=columns, drop_first=True,sparse=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = dummies.iloc[:train.shape[0], :]\ntest = dummies.iloc[train.shape[0]:, :]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = train.sparse.to_coo().tocsr()\ntest = test.sparse.to_coo().tocsr()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#creating matrices for feature selection:\nX = train\ny = train_target\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import xgboost as xgb\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n\n\nx_train, x_valid, y_train, y_valid = train_test_split(X, y, test_size=0.2, random_state=10)\n\nd_train = xgb.DMatrix(x_train, label=y_train)\nd_valid = xgb.DMatrix(x_valid, label=y_valid)\nd_test = xgb.DMatrix(test)\n\nparams = {\n        'objective':'binary:logistic',\n        'eta': 0.3,\n#         'tree_method':'gpu_hist',\n        'max_depth':6,\n        'learning_rate':0.3,\n        'eval_metric':'auc',\n        'min_child_weight':3,\n        'subsample':0.8,\n        'colsample_bytree':0.8,\n        'seed':29,\n        'reg_lambda':0.8,\n        'reg_alpha':0.000001,\n        'gamma':0.1,\n        'scale_pos_weight':2.5,\n        'nthread':-1\n}\n\nwatchlist = [(d_train, 'train'), (d_valid, 'valid')]\nnrounds=100000 \nmodel = xgb.train(params, d_train, nrounds, watchlist, early_stopping_rounds=500, maximize=True, verbose_eval=10)\np_test = model.predict(d_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n# plt.style.use('fivethirtyeight')\n# fig,ax = plt.subplots(figsize=(30,20))\n# xgb.plot_importance(model,ax=ax,height=0.8,color='r')\n# plt.tight_layout()\n# plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# sub = pd.DataFrame({'id':test_id,'target':p_test})\n\n# sub.to_csv('submission.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}