{"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-30T06:21:15.586629Z","iopub.execute_input":"2022-05-30T06:21:15.589528Z","iopub.status.idle":"2022-05-30T06:21:15.615605Z","shell.execute_reply.started":"2022-05-30T06:21:15.589387Z","shell.execute_reply":"2022-05-30T06:21:15.614732Z"},"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-30T06:21:16.498771Z","iopub.execute_input":"2022-05-30T06:21:16.499524Z","iopub.status.idle":"2022-05-30T06:21:22.148985Z","shell.execute_reply.started":"2022-05-30T06:21:16.499456Z","shell.execute_reply":"2022-05-30T06:21:22.147937Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.shape, test.shape","metadata":{"execution":{"iopub.status.busy":"2022-05-30T06:21:22.150893Z","iopub.execute_input":"2022-05-30T06:21:22.151337Z","iopub.status.idle":"2022-05-30T06:21:22.161592Z","shell.execute_reply.started":"2022-05-30T06:21:22.151291Z","shell.execute_reply":"2022-05-30T06:21:22.160560Z"},"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-30T06:26:46.091498Z","iopub.execute_input":"2022-05-30T06:26:46.092095Z","iopub.status.idle":"2022-05-30T06:26:48.476814Z","shell.execute_reply.started":"2022-05-30T06:26:46.092055Z","shell.execute_reply":"2022-05-30T06:26:48.475734Z"},"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-30T06:26:50.478218Z","iopub.execute_input":"2022-05-30T06:26:50.478715Z","iopub.status.idle":"2022-05-30T06:26:55.314998Z","shell.execute_reply.started":"2022-05-30T06:26:50.478673Z","shell.execute_reply":"2022-05-30T06:26:55.313962Z"},"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-30T06:26:55.316970Z","iopub.execute_input":"2022-05-30T06:26:55.317338Z","iopub.status.idle":"2022-05-30T06:26:55.946841Z","shell.execute_reply.started":"2022-05-30T06:26:55.317306Z","shell.execute_reply":"2022-05-30T06:26:55.945738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_data","metadata":{"execution":{"iopub.status.busy":"2022-05-30T06:26:55.948386Z","iopub.execute_input":"2022-05-30T06:26:55.948801Z","iopub.status.idle":"2022-05-30T06:26:56.752461Z","shell.execute_reply.started":"2022-05-30T06:26:55.948767Z","shell.execute_reply":"2022-05-30T06:26:56.751736Z"},"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-30T06:28:40.242575Z","iopub.execute_input":"2022-05-30T06:28:40.242986Z","iopub.status.idle":"2022-05-30T06:28:40.878367Z","shell.execute_reply.started":"2022-05-30T06:28:40.242954Z","shell.execute_reply":"2022-05-30T06:28:40.877455Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_data","metadata":{"execution":{"iopub.status.busy":"2022-05-30T06:28:43.627821Z","iopub.execute_input":"2022-05-30T06:28:43.628186Z","iopub.status.idle":"2022-05-30T06:28:44.304724Z","shell.execute_reply.started":"2022-05-30T06:28:43.628157Z","shell.execute_reply":"2022-05-30T06:28:44.303770Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.preprocessing import OrdinalEncoder","metadata":{"execution":{"iopub.status.busy":"2022-05-30T06:29:19.168701Z","iopub.execute_input":"2022-05-30T06:29:19.169349Z","iopub.status.idle":"2022-05-30T06:29:19.173441Z","shell.execute_reply.started":"2022-05-30T06:29:19.169316Z","shell.execute_reply":"2022-05-30T06:29:19.172492Z"},"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-30T06:31:07.287566Z","iopub.execute_input":"2022-05-30T06:31:07.287954Z","iopub.status.idle":"2022-05-30T06:31:08.845672Z","shell.execute_reply.started":"2022-05-30T06:31:07.287923Z","shell.execute_reply":"2022-05-30T06:31:08.844524Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_data","metadata":{"execution":{"iopub.status.busy":"2022-05-30T06:31:17.402393Z","iopub.execute_input":"2022-05-30T06:31:17.402819Z","iopub.status.idle":"2022-05-30T06:31:17.941422Z","shell.execute_reply.started":"2022-05-30T06:31:17.402785Z","shell.execute_reply":"2022-05-30T06:31:17.940406Z"},"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-30T06:31:53.274414Z","iopub.execute_input":"2022-05-30T06:31:53.274843Z","iopub.status.idle":"2022-05-30T06:31:53.279716Z","shell.execute_reply.started":"2022-05-30T06:31:53.274809Z","shell.execute_reply":"2022-05-30T06:31:53.278964Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.preprocessing import OneHotEncoder","metadata":{"execution":{"iopub.status.busy":"2022-05-30T06:32:00.711244Z","iopub.execute_input":"2022-05-30T06:32:00.711690Z","iopub.status.idle":"2022-05-30T06:32:00.716174Z","shell.execute_reply.started":"2022-05-30T06:32:00.711637Z","shell.execute_reply":"2022-05-30T06:32:00.715426Z"},"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-30T06:32:30.441976Z","iopub.execute_input":"2022-05-30T06:32:30.442405Z","iopub.status.idle":"2022-05-30T06:32:34.685408Z","shell.execute_reply.started":"2022-05-30T06:32:30.442371Z","shell.execute_reply":"2022-05-30T06:32:34.684514Z"},"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-30T06:33:01.995493Z","iopub.execute_input":"2022-05-30T06:33:01.995880Z","iopub.status.idle":"2022-05-30T06:33:02.034827Z","shell.execute_reply.started":"2022-05-30T06:33:01.995850Z","shell.execute_reply":"2022-05-30T06:33:02.033792Z"},"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-30T06:36:23.851495Z","iopub.execute_input":"2022-05-30T06:36:23.852714Z","iopub.status.idle":"2022-05-30T06:36:24.321206Z","shell.execute_reply.started":"2022-05-30T06:36:23.852609Z","shell.execute_reply":"2022-05-30T06:36:24.319595Z"},"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-30T06:34:31.093673Z","iopub.execute_input":"2022-05-30T06:34:31.094044Z","iopub.status.idle":"2022-05-30T06:34:31.098291Z","shell.execute_reply.started":"2022-05-30T06:34:31.094015Z","shell.execute_reply":"2022-05-30T06:34:31.097384Z"},"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-30T06:34:45.489223Z","iopub.execute_input":"2022-05-30T06:34:45.489712Z","iopub.status.idle":"2022-05-30T06:34:45.638534Z","shell.execute_reply.started":"2022-05-30T06:34:45.489650Z","shell.execute_reply":"2022-05-30T06:34:45.637523Z"},"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-30T06:35:08.538142Z","iopub.execute_input":"2022-05-30T06:35:08.538546Z","iopub.status.idle":"2022-05-30T06:35:08.542827Z","shell.execute_reply.started":"2022-05-30T06:35:08.538511Z","shell.execute_reply":"2022-05-30T06:35:08.541920Z"},"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-30T06:36:42.631053Z","iopub.execute_input":"2022-05-30T06:36:42.631433Z","iopub.status.idle":"2022-05-30T06:36:43.757739Z","shell.execute_reply.started":"2022-05-30T06:36:42.631402Z","shell.execute_reply":"2022-05-30T06:36:43.756717Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_data_sprs","metadata":{"execution":{"iopub.status.busy":"2022-05-30T06:36:47.732951Z","iopub.execute_input":"2022-05-30T06:36:47.733389Z","iopub.status.idle":"2022-05-30T06:36:47.739686Z","shell.execute_reply.started":"2022-05-30T06:36:47.733351Z","shell.execute_reply":"2022-05-30T06:36:47.738930Z"},"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-30T06:37:17.339293Z","iopub.execute_input":"2022-05-30T06:37:17.339747Z","iopub.status.idle":"2022-05-30T06:37:17.847894Z","shell.execute_reply.started":"2022-05-30T06:37:17.339708Z","shell.execute_reply":"2022-05-30T06:37:17.846296Z"},"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-30T06:37:19.027693Z","iopub.execute_input":"2022-05-30T06:37:19.028100Z","iopub.status.idle":"2022-05-30T06:37:19.097267Z","shell.execute_reply.started":"2022-05-30T06:37:19.028069Z","shell.execute_reply":"2022-05-30T06:37:19.096272Z"},"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-30T06:37:26.186005Z","iopub.execute_input":"2022-05-30T06:37:26.186985Z","iopub.status.idle":"2022-05-30T06:37:26.579427Z","shell.execute_reply.started":"2022-05-30T06:37:26.186925Z","shell.execute_reply":"2022-05-30T06:37:26.578381Z"},"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-30T06:37:52.156792Z","iopub.execute_input":"2022-05-30T06:37:52.157208Z","iopub.status.idle":"2022-05-30T06:37:52.236318Z","shell.execute_reply.started":"2022-05-30T06:37:52.157177Z","shell.execute_reply":"2022-05-30T06:37:52.235191Z"},"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-30T06:39:24.159932Z","iopub.execute_input":"2022-05-30T06:39:24.160410Z","iopub.status.idle":"2022-05-30T06:49:21.068080Z","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.074210Z","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":[]}]}