{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":88400,"databundleVersionId":10121331,"sourceType":"competition"}],"dockerImageVersionId":30786,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"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 20GB 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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-13T11:58:10.899089Z","iopub.execute_input":"2024-11-13T11:58:10.899625Z","iopub.status.idle":"2024-11-13T11:58:10.907796Z","shell.execute_reply.started":"2024-11-13T11:58:10.899583Z","shell.execute_reply":"2024-11-13T11:58:10.906386Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#데이터 불러오기\ndata = pd.read_csv('/kaggle/input/aiffel-ds-3-credit-card-fraud-detection/train.csv')\ntest = pd.read_csv('/kaggle/input/aiffel-ds-3-credit-card-fraud-detection/test.csv')\nsubmission = pd.read_csv('/kaggle/input/aiffel-ds-3-credit-card-fraud-detection/sample_submission.csv')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-13T11:58:13.919002Z","iopub.execute_input":"2024-11-13T11:58:13.920050Z","iopub.status.idle":"2024-11-13T11:58:18.099286Z","shell.execute_reply.started":"2024-11-13T11:58:13.919991Z","shell.execute_reply":"2024-11-13T11:58:18.097944Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#데이터 살펴보기\ndata.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-13T11:58:22.612815Z","iopub.execute_input":"2024-11-13T11:58:22.613245Z","iopub.status.idle":"2024-11-13T11:58:22.659139Z","shell.execute_reply.started":"2024-11-13T11:58:22.613205Z","shell.execute_reply":"2024-11-13T11:58:22.657852Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 피처 설명\r\n\r\n1. **id**: 거래 고유 식별자\r\n2. **Time**: 각 거래와 첫 거래 간 경과 시간(초)\r\n3. **V1 ~ V28**: PCA로 변환된 특성, 원래 특성 정보는 비공개\r\n4. **Amount**: 거래 금액\r\n5. **Class**: 사기 유무 (1: 사기, 0: 정상)\r\n \n관계 탐색\r\n","metadata":{}},{"cell_type":"markdown","source":"# 분석 전략\n\n1. **클래스 비율**: 사기 거래 비율 확인\n2. **Amount**: 거래 금액 분포 비교 (사기 vs. 정상)\n3. **Time**: 거래 시간대별 사기 패턴 분석\n4. **V1~V28**: 변환된 특성 분포 및 사기 거래와의 관계 탐색\n","metadata":{}},{"cell_type":"code","source":"#불균형 데이터 확인\nprint(data['Class'].value_counts())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-13T11:59:07.813573Z","iopub.execute_input":"2024-11-13T11:59:07.814765Z","iopub.status.idle":"2024-11-13T11:59:07.830714Z","shell.execute_reply.started":"2024-11-13T11:59:07.814703Z","shell.execute_reply":"2024-11-13T11:59:07.829135Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns\n\n# 1. 클래스 비율 확인\nplt.figure(figsize=(6, 4))\nsns.countplot(x='Class', data=data)\nplt.title('Class Distribution')\nplt.xlabel('Class (0: Normal, 1: Fraud)')\nplt.ylabel('Count')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-12T09:07:48.756514Z","iopub.execute_input":"2024-11-12T09:07:48.756958Z","iopub.status.idle":"2024-11-12T09:07:49.072437Z","shell.execute_reply.started":"2024-11-12T09:07:48.756916Z","shell.execute_reply":"2024-11-12T09:07:49.071333Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#데이터 스케일링\nfrom sklearn.preprocessing import StandardScaler\n\n# StandardScaler 객체 생성\nscaler = StandardScaler()\n\n# Class 열을 제외한 모든 피처 선택\nfeatures_to_scale = data.columns.difference(['Class'])\n\n# 스케일링 적용\ndata[features_to_scale] = scaler.fit_transform(data[features_to_scale])\n\n# 스케일링 결과 확인\ndata.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-13T12:01:20.723259Z","iopub.execute_input":"2024-11-13T12:01:20.723822Z","iopub.status.idle":"2024-11-13T12:01:21.464524Z","shell.execute_reply.started":"2024-11-13T12:01:20.723779Z","shell.execute_reply":"2024-11-13T12:01:21.463153Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 데이터 복사\ndata_copy = data.copy()\n\n# Time 열 제거\ndata_copy = data_copy.drop(columns=['Time'])\n\n# 결과 확인\ndata_copy.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-13T12:08:25.735723Z","iopub.execute_input":"2024-11-13T12:08:25.736357Z","iopub.status.idle":"2024-11-13T12:08:25.852278Z","shell.execute_reply.started":"2024-11-13T12:08:25.736313Z","shell.execute_reply":"2024-11-13T12:08:25.850777Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#데이터 분할\nfrom sklearn.model_selection import train_test_split\n\n# 특성과 레이블 분리\nX = data_copy.drop(columns=['Class'])\ny = data_copy['Class']\n\n# 데이터 분할 (학습 : 테스트 = 7 : 3, 레이블 분포 유지를 위한 stratify 설정)\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42, stratify=y)\n\n# 분할된 레이블의 분포 확인\nprint(\"Train label distribution:\")\nprint(y_train.value_counts(normalize=True))\nprint(\"\\nTest label distribution:\")\nprint(y_test.value_counts(normalize=True))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-13T12:44:37.547048Z","iopub.execute_input":"2024-11-13T12:44:37.547662Z","iopub.status.idle":"2024-11-13T12:44:37.820467Z","shell.execute_reply.started":"2024-11-13T12:44:37.547597Z","shell.execute_reply":"2024-11-13T12:44:37.819074Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#모델 설정 (랜덤 포레스트, LightGBM, XGBoost)\n#랜덤 포레스트\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import roc_auc_score\n\n# 랜덤 포레스트 모델 생성 및 학습\nrf_model = RandomForestClassifier(random_state=42)\nrf_model.fit(X_train, y_train)\n\n# 테스트 데이터에 대한 예측 확률 계산 (양성 클래스에 대한 확률)\ny_pred_proba = rf_model.predict_proba(X_test)[:, 1]\n\n# ROC-AUC 평가\nroc_auc = roc_auc_score(y_test, y_pred_proba)\nprint(f'Random Forest ROC-AUC Score: {roc_auc:.4f}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-13T12:58:46.418364Z","iopub.execute_input":"2024-11-13T12:58:46.419349Z","iopub.status.idle":"2024-11-13T13:00:41.911197Z","shell.execute_reply.started":"2024-11-13T12:58:46.419300Z","shell.execute_reply":"2024-11-13T13:00:41.909841Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#LightGBM\nimport lightgbm as lgb\n\n# LightGBM 모델 생성\nlgb_model = lgb.LGBMClassifier(random_state=42)\n\n# 모델 학습\nlgb_model.fit(X_train, y_train)\n\n# 테스트 데이터에 대한 예측 확률 계산 (양성 클래스에 대한 확률)\ny_pred_proba = lgb_model.predict_proba(X_test)[:, 1]\n\n# ROC-AUC 평가\nroc_auc = roc_auc_score(y_test, y_pred_proba)\nprint(f'LightGBM ROC-AUC Score: {roc_auc:.4f}')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-13T13:01:26.367634Z","iopub.execute_input":"2024-11-13T13:01:26.368105Z","iopub.status.idle":"2024-11-13T13:01:30.919327Z","shell.execute_reply.started":"2024-11-13T13:01:26.368062Z","shell.execute_reply":"2024-11-13T13:01:30.918107Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#XGBoost\nimport xgboost as xgb\n\n# XGBoost 모델 생성\nxgb_model = xgb.XGBClassifier(use_label_encoder=False, eval_metric='logloss', random_state=42)\n\n# 모델 학습\nxgb_model.fit(X_train, y_train)\n\n# 테스트 데이터에 대한 예측 확률 계산 (양성 클래스에 대한 확률)\ny_pred_proba = xgb_model.predict_proba(X_test)[:, 1]\n\n# ROC-AUC 평가\nroc_auc = roc_auc_score(y_test, y_pred_proba)\nprint(f'XGBoost ROC-AUC Score: {roc_auc:.4f}')\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-13T13:03:12.121347Z","iopub.execute_input":"2024-11-13T13:03:12.122155Z","iopub.status.idle":"2024-11-13T13:03:17.203701Z","shell.execute_reply.started":"2024-11-13T13:03:12.122014Z","shell.execute_reply":"2024-11-13T13:03:17.202241Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-13T13:21:34.736377Z","iopub.execute_input":"2024-11-13T13:21:34.737092Z","iopub.status.idle":"2024-11-13T13:21:34.775210Z","shell.execute_reply.started":"2024-11-13T13:21:34.737016Z","shell.execute_reply":"2024-11-13T13:21:34.773835Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 테스트 데이터에서 'id'와 'Time' 열을 제거하여 모델 입력 특성만 남김\nX_test_final = test.drop(columns=['Time'])\n\n# XGBoost 모델을 사용하여 예측 수행\ntest['Class'] = xgb_model.predict(X_test_final)\n\n# id와 예측된 Class 컬럼만 추출하여 submission 테이블 생성\nsubmission = test[['id', 'Class']]\n\n# submission 테이블을 CSV 파일로 저장\nsubmission.to_csv('submission.csv', index=False)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-13T13:28:29.699130Z","iopub.execute_input":"2024-11-13T13:28:29.699604Z","iopub.status.idle":"2024-11-13T13:28:30.167186Z","shell.execute_reply.started":"2024-11-13T13:28:29.699562Z","shell.execute_reply":"2024-11-13T13:28:30.166108Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-13T13:28:41.864238Z","iopub.execute_input":"2024-11-13T13:28:41.864935Z","iopub.status.idle":"2024-11-13T13:28:41.879925Z","shell.execute_reply.started":"2024-11-13T13:28:41.864888Z","shell.execute_reply":"2024-11-13T13:28:41.878283Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}