{"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:28:40.516936Z","iopub.execute_input":"2022-05-30T07:28:40.517762Z","iopub.status.idle":"2022-05-30T07:28:40.551436Z","shell.execute_reply.started":"2022-05-30T07:28:40.517635Z","shell.execute_reply":"2022-05-30T07:28:40.550217Z"},"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:28:40.904046Z","iopub.execute_input":"2022-05-30T07:28:40.904438Z","iopub.status.idle":"2022-05-30T07:28:47.205776Z","shell.execute_reply.started":"2022-05-30T07:28:40.904407Z","shell.execute_reply":"2022-05-30T07:28:47.204938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.shape, test.shape","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:28:47.207383Z","iopub.execute_input":"2022-05-30T07:28:47.208382Z","iopub.status.idle":"2022-05-30T07:28:47.219130Z","shell.execute_reply.started":"2022-05-30T07:28:47.208323Z","shell.execute_reply":"2022-05-30T07:28:47.217498Z"},"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:28:48.885500Z","iopub.execute_input":"2022-05-30T07:28:48.886685Z","iopub.status.idle":"2022-05-30T07:28:50.971228Z","shell.execute_reply.started":"2022-05-30T07:28:48.886626Z","shell.execute_reply":"2022-05-30T07:28:50.970093Z"},"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:28:50.973298Z","iopub.execute_input":"2022-05-30T07:28:50.973760Z","iopub.status.idle":"2022-05-30T07:28:55.800563Z","shell.execute_reply.started":"2022-05-30T07:28:50.973725Z","shell.execute_reply":"2022-05-30T07:28:55.799164Z"},"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:28:55.803170Z","iopub.execute_input":"2022-05-30T07:28:55.804485Z","iopub.status.idle":"2022-05-30T07:28:56.392155Z","shell.execute_reply.started":"2022-05-30T07:28:55.804418Z","shell.execute_reply":"2022-05-30T07:28:56.391186Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_data","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:28:56.393456Z","iopub.execute_input":"2022-05-30T07:28:56.393864Z","iopub.status.idle":"2022-05-30T07:28:57.199585Z","shell.execute_reply.started":"2022-05-30T07:28:56.393803Z","shell.execute_reply":"2022-05-30T07:28:57.198491Z"},"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:28:57.202114Z","iopub.execute_input":"2022-05-30T07:28:57.202714Z","iopub.status.idle":"2022-05-30T07:28:57.851346Z","shell.execute_reply.started":"2022-05-30T07:28:57.202662Z","shell.execute_reply":"2022-05-30T07:28:57.850259Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_data","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:28:57.852715Z","iopub.execute_input":"2022-05-30T07:28:57.853484Z","iopub.status.idle":"2022-05-30T07:28:58.573979Z","shell.execute_reply.started":"2022-05-30T07:28:57.853433Z","shell.execute_reply":"2022-05-30T07:28:58.572802Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.preprocessing import OrdinalEncoder","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:28:58.575272Z","iopub.execute_input":"2022-05-30T07:28:58.575849Z","iopub.status.idle":"2022-05-30T07:28:59.863870Z","shell.execute_reply.started":"2022-05-30T07:28:58.575800Z","shell.execute_reply":"2022-05-30T07:28:59.862957Z"},"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:28:59.865102Z","iopub.execute_input":"2022-05-30T07:28:59.865582Z","iopub.status.idle":"2022-05-30T07:29:01.444983Z","shell.execute_reply.started":"2022-05-30T07:28:59.865549Z","shell.execute_reply":"2022-05-30T07:29:01.442787Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_data","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:29:01.446692Z","iopub.execute_input":"2022-05-30T07:29:01.447419Z","iopub.status.idle":"2022-05-30T07:29:02.021521Z","shell.execute_reply.started":"2022-05-30T07:29:01.447369Z","shell.execute_reply":"2022-05-30T07:29:02.020001Z"},"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:29:02.024235Z","iopub.execute_input":"2022-05-30T07:29:02.024629Z","iopub.status.idle":"2022-05-30T07:29:02.030949Z","shell.execute_reply.started":"2022-05-30T07:29:02.024593Z","shell.execute_reply":"2022-05-30T07:29:02.029534Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.preprocessing import OneHotEncoder","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:29:02.032179Z","iopub.execute_input":"2022-05-30T07:29:02.032530Z","iopub.status.idle":"2022-05-30T07:29:02.049207Z","shell.execute_reply.started":"2022-05-30T07:29:02.032500Z","shell.execute_reply":"2022-05-30T07:29:02.047406Z"},"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:29:02.050821Z","iopub.execute_input":"2022-05-30T07:29:02.051487Z","iopub.status.idle":"2022-05-30T07:29:06.546647Z","shell.execute_reply.started":"2022-05-30T07:29:02.051445Z","shell.execute_reply":"2022-05-30T07:29:06.545541Z"},"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:29:06.548679Z","iopub.execute_input":"2022-05-30T07:29:06.549651Z","iopub.status.idle":"2022-05-30T07:29:06.590773Z","shell.execute_reply.started":"2022-05-30T07:29:06.549572Z","shell.execute_reply":"2022-05-30T07:29:06.588983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 날짜 피처 인코딩","metadata":{}},{"cell_type":"code","source":"import numpy as np","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:30:04.226574Z","iopub.execute_input":"2022-05-30T07:30:04.227303Z","iopub.status.idle":"2022-05-30T07:30:04.234021Z","shell.execute_reply.started":"2022-05-30T07:30:04.227239Z","shell.execute_reply":"2022-05-30T07:30:04.232290Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.linspace(0, np.pi / 2, 8)","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:31:30.521813Z","iopub.execute_input":"2022-05-30T07:31:30.522530Z","iopub.status.idle":"2022-05-30T07:31:30.529559Z","shell.execute_reply.started":"2022-05-30T07:31:30.522486Z","shell.execute_reply":"2022-05-30T07:31:30.528412Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"date_features = ['day', 'month']\n\nday_dict = {i: np.sin(k) for i, k in enumerate(np.linspace(0, np.pi / 2, train['day'].nunique() + 1))}\nmonth_dict = {i: np.sin(k) for i, k in enumerate(np.linspace(0, np.pi / 2, train['month'].nunique() + 1))}\n\nall_data['day'] = all_data['day'].map(day_dict)\nall_data['month'] = all_data['month'].map(month_dict)\nall_data","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:35:18.245952Z","iopub.execute_input":"2022-05-30T07:35:18.246395Z","iopub.status.idle":"2022-05-30T07:35:18.367298Z","shell.execute_reply.started":"2022-05-30T07:35:18.246361Z","shell.execute_reply":"2022-05-30T07:35:18.366203Z"},"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:35:55.863887Z","iopub.execute_input":"2022-05-30T07:35:55.864951Z","iopub.status.idle":"2022-05-30T07:35:55.869661Z","shell.execute_reply.started":"2022-05-30T07:35:55.864904Z","shell.execute_reply":"2022-05-30T07:35:55.868376Z"},"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:35:56.987782Z","iopub.execute_input":"2022-05-30T07:35:56.988191Z","iopub.status.idle":"2022-05-30T07:35:57.123626Z","shell.execute_reply.started":"2022-05-30T07:35:56.988159Z","shell.execute_reply":"2022-05-30T07:35:57.122679Z"},"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:35:58.530449Z","iopub.execute_input":"2022-05-30T07:35:58.531114Z","iopub.status.idle":"2022-05-30T07:35:58.536322Z","shell.execute_reply.started":"2022-05-30T07:35:58.531078Z","shell.execute_reply":"2022-05-30T07:35:58.534743Z"},"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                              ],\n                              format='csr')","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:36:07.890272Z","iopub.execute_input":"2022-05-30T07:36:07.890674Z","iopub.status.idle":"2022-05-30T07:36:09.066106Z","shell.execute_reply.started":"2022-05-30T07:36:07.890644Z","shell.execute_reply":"2022-05-30T07:36:09.065138Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_data_sprs","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:36:09.342749Z","iopub.execute_input":"2022-05-30T07:36:09.343206Z","iopub.status.idle":"2022-05-30T07:36:09.349829Z","shell.execute_reply.started":"2022-05-30T07:36:09.343172Z","shell.execute_reply":"2022-05-30T07:36:09.348875Z"},"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:36:11.911632Z","iopub.execute_input":"2022-05-30T07:36:11.912479Z","iopub.status.idle":"2022-05-30T07:36:12.222954Z","shell.execute_reply.started":"2022-05-30T07:36:11.912414Z","shell.execute_reply":"2022-05-30T07:36:12.221721Z"},"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:36:12.471875Z","iopub.execute_input":"2022-05-30T07:36:12.472269Z","iopub.status.idle":"2022-05-30T07:36:12.544662Z","shell.execute_reply.started":"2022-05-30T07:36:12.472239Z","shell.execute_reply":"2022-05-30T07:36:12.543822Z"},"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:36:14.525587Z","iopub.execute_input":"2022-05-30T07:36:14.526501Z","iopub.status.idle":"2022-05-30T07:36:14.909674Z","shell.execute_reply.started":"2022-05-30T07:36:14.526448Z","shell.execute_reply":"2022-05-30T07:36:14.908539Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 하이퍼파라미터 최적화","metadata":{}},{"cell_type":"code","source":"from sklearn.model_selection import GridSearchCV\nfrom sklearn.linear_model import LogisticRegression","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:36:15.843127Z","iopub.execute_input":"2022-05-30T07:36:15.843655Z","iopub.status.idle":"2022-05-30T07:36:15.940708Z","shell.execute_reply.started":"2022-05-30T07:36:15.843623Z","shell.execute_reply":"2022-05-30T07:36:15.939592Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nlogistic_model = LogisticRegression()\n\nlr_params = {'C': [0.1, 0.125, 0.2], 'max_iter': [800, 900, 1000],\n             'solver': ['liblinear'], 'random_state': [42]}\n\ngridsearch_logistic_model = GridSearchCV(estimator=logistic_model,\n                                         param_grid=lr_params, \n                                         scoring='roc_auc',\n                                         cv=5)\n\ngridsearch_logistic_model.fit(X_train, y_train)\n\nprint('최적 하이퍼파라미터 :', gridsearch_logistic_model.best_params_)","metadata":{"execution":{"iopub.status.busy":"2022-05-30T07:36:16.316915Z","iopub.execute_input":"2022-05-30T07:36:16.317345Z"},"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_logistic_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_logistic_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":[]}]}