{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-05-30T07:53:19.120354Z","iopub.execute_input":"2022-05-30T07:53:19.12107Z","iopub.status.idle":"2022-05-30T07:53:19.150977Z","shell.execute_reply.started":"2022-05-30T07:53:19.120948Z","shell.execute_reply":"2022-05-30T07:53:19.150182Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_path = '/kaggle/input/cat-in-the-dat-ii/'\n\ntrain = pd.read_csv(data_path + 'train.csv', index_col='id')\ntest = pd.read_csv(data_path + 'test.csv', index_col='id')\nsubmission = pd.read_csv(data_path + 'sample_submission.csv', index_col='id')","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:19.349287Z","iopub.execute_input":"2022-05-30T07:53:19.349904Z","iopub.status.idle":"2022-05-30T07:53:25.341835Z","shell.execute_reply.started":"2022-05-30T07:53:19.349854Z","shell.execute_reply":"2022-05-30T07:53:25.340779Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.shape, test.shape","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:25.343368Z","iopub.execute_input":"2022-05-30T07:53:25.343696Z","iopub.status.idle":"2022-05-30T07:53:25.352549Z","shell.execute_reply.started":"2022-05-30T07:53:25.343668Z","shell.execute_reply":"2022-05-30T07:53:25.351367Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 피처 엔지니어링 1 : 피처 맞춤 인코딩","metadata":{}},{"cell_type":"markdown","source":"### 데이터 합치기","metadata":{}},{"cell_type":"code","source":"all_data = pd.concat([train, test])\nall_data = all_data.drop('target', axis=1)\nall_data","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:25.358884Z","iopub.execute_input":"2022-05-30T07:53:25.359323Z","iopub.status.idle":"2022-05-30T07:53:27.435699Z","shell.execute_reply.started":"2022-05-30T07:53:25.35927Z","shell.execute_reply":"2022-05-30T07:53:27.434688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for col in all_data.columns:\n    mode = all_data[col].mode(dropna=True).values[0]\n    all_data[col] = all_data[col].fillna(mode)","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:27.437282Z","iopub.execute_input":"2022-05-30T07:53:27.43784Z","iopub.status.idle":"2022-05-30T07:53:32.223744Z","shell.execute_reply.started":"2022-05-30T07:53:27.437794Z","shell.execute_reply":"2022-05-30T07:53:32.222643Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"간단하게 최빈값으로 NaN 값 처리","metadata":{}},{"cell_type":"markdown","source":"### 이진 피처 인코딩","metadata":{}},{"cell_type":"code","source":"all_data['bin_3'] = all_data['bin_3'].map({'F': 0.0, 'T': 1.0})\nall_data['bin_4'] = all_data['bin_4'].map({'N': 0.0, 'Y': 1.0})","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:32.226243Z","iopub.execute_input":"2022-05-30T07:53:32.226715Z","iopub.status.idle":"2022-05-30T07:53:32.80692Z","shell.execute_reply.started":"2022-05-30T07:53:32.226669Z","shell.execute_reply":"2022-05-30T07:53:32.80601Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_data","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:32.808577Z","iopub.execute_input":"2022-05-30T07:53:32.808929Z","iopub.status.idle":"2022-05-30T07:53:33.550478Z","shell.execute_reply.started":"2022-05-30T07:53:32.808899Z","shell.execute_reply":"2022-05-30T07:53:33.549455Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 순서형 피처 인코딩\n\n- ord_0 피처는 이미 숫자로 구성돼 있어 인코딩하지 않아도 됨\n- ord_1, ord_2 피처는 순서를 정해서 인코딩\n- ord_3 ~ ord_5 피처는 알파벳 순서대로 인코딩","metadata":{}},{"cell_type":"code","source":"ord1dict = {'Novice': 0, 'Contributor': 1, 'Expert': 2, 'Master': 3, 'Grandmaster': 4}\nord2dict = {'Freezing': 0, 'Cold': 1, 'Warm': 2, 'Hot': 3, 'Boiling Hot': 4, 'Lava Hot': 5}\n\nall_data['ord_1'] = all_data['ord_1'].map(ord1dict)\nall_data['ord_2'] = all_data['ord_2'].map(ord2dict)","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:33.551681Z","iopub.execute_input":"2022-05-30T07:53:33.552024Z","iopub.status.idle":"2022-05-30T07:53:34.211179Z","shell.execute_reply.started":"2022-05-30T07:53:33.551993Z","shell.execute_reply":"2022-05-30T07:53:34.210233Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_data","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:34.212332Z","iopub.execute_input":"2022-05-30T07:53:34.212679Z","iopub.status.idle":"2022-05-30T07:53:34.889331Z","shell.execute_reply.started":"2022-05-30T07:53:34.212648Z","shell.execute_reply":"2022-05-30T07:53:34.888349Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.preprocessing import OrdinalEncoder","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:34.891886Z","iopub.execute_input":"2022-05-30T07:53:34.892213Z","iopub.status.idle":"2022-05-30T07:53:35.943739Z","shell.execute_reply.started":"2022-05-30T07:53:34.892183Z","shell.execute_reply":"2022-05-30T07:53:35.942615Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ord_345 = ['ord_' + str(i) for i in range(3, 6)]\n\nord_encoder = OrdinalEncoder()\n\nall_data[ord_345] = ord_encoder.fit_transform(all_data[ord_345])\n\nfor feature, categories in zip(ord_345, ord_encoder.categories_):\n    print(feature)\n    print(categories)","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:35.944727Z","iopub.execute_input":"2022-05-30T07:53:35.94504Z","iopub.status.idle":"2022-05-30T07:53:37.517485Z","shell.execute_reply.started":"2022-05-30T07:53:35.945012Z","shell.execute_reply":"2022-05-30T07:53:37.5166Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_data","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:37.518633Z","iopub.execute_input":"2022-05-30T07:53:37.518965Z","iopub.status.idle":"2022-05-30T07:53:38.047161Z","shell.execute_reply.started":"2022-05-30T07:53:37.518934Z","shell.execute_reply":"2022-05-30T07:53:38.046177Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 명목형 피처 인코딩","metadata":{}},{"cell_type":"code","source":"nom_features = ['nom_' + str(i) for i in range(10)]","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:38.048399Z","iopub.execute_input":"2022-05-30T07:53:38.048766Z","iopub.status.idle":"2022-05-30T07:53:38.053313Z","shell.execute_reply.started":"2022-05-30T07:53:38.048734Z","shell.execute_reply":"2022-05-30T07:53:38.052474Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.preprocessing import OneHotEncoder","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:38.054585Z","iopub.execute_input":"2022-05-30T07:53:38.054917Z","iopub.status.idle":"2022-05-30T07:53:38.06565Z","shell.execute_reply.started":"2022-05-30T07:53:38.054886Z","shell.execute_reply":"2022-05-30T07:53:38.064761Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"onehot_encoder = OneHotEncoder()\n\nencoded_nom_matrix = onehot_encoder.fit_transform(all_data[nom_features])\n\nencoded_nom_matrix","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:38.066927Z","iopub.execute_input":"2022-05-30T07:53:38.067242Z","iopub.status.idle":"2022-05-30T07:53:42.341086Z","shell.execute_reply.started":"2022-05-30T07:53:38.067213Z","shell.execute_reply":"2022-05-30T07:53:42.340442Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_data = all_data.drop(nom_features, axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:42.341974Z","iopub.execute_input":"2022-05-30T07:53:42.342594Z","iopub.status.idle":"2022-05-30T07:53:42.379469Z","shell.execute_reply.started":"2022-05-30T07:53:42.342563Z","shell.execute_reply":"2022-05-30T07:53:42.378756Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 날짜 피처 인코딩","metadata":{}},{"cell_type":"code","source":"date_features = ['day', 'month']\n\nencoded_date_matrix = onehot_encoder.fit_transform(all_data[date_features])\n\nall_data = all_data.drop(date_features, axis=1)\n\nencoded_date_matrix","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:42.38068Z","iopub.execute_input":"2022-05-30T07:53:42.381122Z","iopub.status.idle":"2022-05-30T07:53:42.732448Z","shell.execute_reply.started":"2022-05-30T07:53:42.381091Z","shell.execute_reply":"2022-05-30T07:53:42.73156Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 피처 엔지니어링 2 : 피처 스케일링","metadata":{}},{"cell_type":"markdown","source":"### 순서형 피처 스케일링","metadata":{}},{"cell_type":"code","source":"from sklearn.preprocessing import MinMaxScaler","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:42.733845Z","iopub.execute_input":"2022-05-30T07:53:42.734517Z","iopub.status.idle":"2022-05-30T07:53:42.739601Z","shell.execute_reply.started":"2022-05-30T07:53:42.73447Z","shell.execute_reply":"2022-05-30T07:53:42.738386Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ord_features = ['ord_' + str(i) for i in range(6)]\n\nall_data[ord_features] = MinMaxScaler().fit_transform(all_data[ord_features])","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:42.741058Z","iopub.execute_input":"2022-05-30T07:53:42.741545Z","iopub.status.idle":"2022-05-30T07:53:42.87177Z","shell.execute_reply.started":"2022-05-30T07:53:42.741499Z","shell.execute_reply":"2022-05-30T07:53:42.870819Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 인코딩 및 스케일링된 피처 합치기","metadata":{}},{"cell_type":"code","source":"from scipy import sparse","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:42.875473Z","iopub.execute_input":"2022-05-30T07:53:42.875833Z","iopub.status.idle":"2022-05-30T07:53:42.880129Z","shell.execute_reply.started":"2022-05-30T07:53:42.875802Z","shell.execute_reply":"2022-05-30T07:53:42.879441Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_data_sprs = sparse.hstack([sparse.csr_matrix(all_data),\n                               encoded_nom_matrix,\n                               encoded_date_matrix],\n                              format='csr')","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:42.881213Z","iopub.execute_input":"2022-05-30T07:53:42.881699Z","iopub.status.idle":"2022-05-30T07:53:44.046491Z","shell.execute_reply.started":"2022-05-30T07:53:42.881668Z","shell.execute_reply":"2022-05-30T07:53:44.045635Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_data_sprs","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:44.047998Z","iopub.execute_input":"2022-05-30T07:53:44.048497Z","iopub.status.idle":"2022-05-30T07:53:44.056152Z","shell.execute_reply.started":"2022-05-30T07:53:44.048443Z","shell.execute_reply":"2022-05-30T07:53:44.055135Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 데이터 나누기","metadata":{"execution":{"iopub.status.busy":"2022-05-30T06:07:21.653123Z","iopub.execute_input":"2022-05-30T06:07:21.653744Z","iopub.status.idle":"2022-05-30T06:07:21.661977Z","shell.execute_reply.started":"2022-05-30T06:07:21.653699Z","shell.execute_reply":"2022-05-30T06:07:21.660767Z"}}},{"cell_type":"code","source":"num_train = len(train)\n\nX_train = all_data_sprs[:num_train]\nX_test = all_data_sprs[num_train:]\n\ny = train['target']","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:44.057501Z","iopub.execute_input":"2022-05-30T07:53:44.057963Z","iopub.status.idle":"2022-05-30T07:53:44.358385Z","shell.execute_reply.started":"2022-05-30T07:53:44.057931Z","shell.execute_reply":"2022-05-30T07:53:44.357472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:44.359765Z","iopub.execute_input":"2022-05-30T07:53:44.360073Z","iopub.status.idle":"2022-05-30T07:53:44.427585Z","shell.execute_reply.started":"2022-05-30T07:53:44.360044Z","shell.execute_reply":"2022-05-30T07:53:44.426623Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train, X_valid, y_train, y_valid = train_test_split(X_train, y, test_size=0.1, stratify=y, random_state=42)","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:44.42877Z","iopub.execute_input":"2022-05-30T07:53:44.429211Z","iopub.status.idle":"2022-05-30T07:53:44.794631Z","shell.execute_reply.started":"2022-05-30T07:53:44.429175Z","shell.execute_reply":"2022-05-30T07:53:44.793622Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 하이퍼파라미터 최적화","metadata":{}},{"cell_type":"code","source":"from sklearn.model_selection import GridSearchCV\nfrom sklearn.ensemble import RandomForestClassifier","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:53:52.770903Z","iopub.execute_input":"2022-05-30T07:53:52.771717Z","iopub.status.idle":"2022-05-30T07:53:52.776613Z","shell.execute_reply.started":"2022-05-30T07:53:52.771672Z","shell.execute_reply":"2022-05-30T07:53:52.775794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nrandomforest_model = RandomForestClassifier()\n\nlr_params = {'n_estimators': [100, 120, 140], 'random_state': [42]}\n\ngridsearch_rf_model = GridSearchCV(estimator=randomforest_model,\n                                         param_grid=lr_params, \n                                         scoring='roc_auc',\n                                         cv=5)\n\ngridsearch_rf_model.fit(X_train, y_train)\n\nprint('최적 하이퍼파라미터 :', gridsearch_rf_model.best_params_)","metadata":{"execution":{"iopub.status.busy":"2022-05-30T06:39:24.159932Z","iopub.execute_input":"2022-05-30T06:39:24.16041Z","iopub.status.idle":"2022-05-30T06:49:21.06808Z","shell.execute_reply.started":"2022-05-30T06:39:24.160375Z","shell.execute_reply":"2022-05-30T06:49:21.067099Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 모델 성능 검증","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import roc_auc_score","metadata":{"execution":{"iopub.status.busy":"2022-05-30T06:49:21.069596Z","iopub.execute_input":"2022-05-30T06:49:21.069941Z","iopub.status.idle":"2022-05-30T06:49:21.07421Z","shell.execute_reply.started":"2022-05-30T06:49:21.069911Z","shell.execute_reply":"2022-05-30T06:49:21.073402Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_valid_preds = gridsearch_rf_model.best_estimator_.predict_proba(X_valid)[:, 1]\n\nroc_auc = roc_auc_score(y_valid, y_valid_preds)\n\nprint(f'검증 데이터 ROC AUC : {roc_auc:.4f}')","metadata":{"execution":{"iopub.status.busy":"2022-05-30T06:50:06.922336Z","iopub.execute_input":"2022-05-30T06:50:06.922788Z","iopub.status.idle":"2022-05-30T06:50:06.955348Z","shell.execute_reply.started":"2022-05-30T06:50:06.922744Z","shell.execute_reply":"2022-05-30T06:50:06.954585Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 예측 및 결과 제출","metadata":{}},{"cell_type":"code","source":"y_preds = gridsearch_rf_model.best_estimator_.predict_proba(X_test)[:, 1]\n\nsubmission['target'] = y_preds\nsubmission.to_csv('submission.csv')","metadata":{"execution":{"iopub.status.busy":"2022-05-30T06:50:21.528049Z","iopub.execute_input":"2022-05-30T06:50:21.528614Z","iopub.status.idle":"2022-05-30T06:50:23.075545Z","shell.execute_reply.started":"2022-05-30T06:50:21.528583Z","shell.execute_reply":"2022-05-30T06:50:23.074559Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}