{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","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":"# 라이브러리 임포트\nimport numpy as np \nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-12T05:01:28.384112Z","iopub.execute_input":"2024-11-12T05:01:28.384649Z","iopub.status.idle":"2024-11-12T05:01:28.390107Z","shell.execute_reply.started":"2024-11-12T05:01:28.384606Z","shell.execute_reply":"2024-11-12T05:01:28.388830Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 데이터 임포트\ntrain_data = pd.read_csv(\"/kaggle/input/aiffel-ds-3-credit-card-fraud-detection/train.csv\") \ntest_data = 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-12T05:01:30.688933Z","iopub.execute_input":"2024-11-12T05:01:30.689581Z","iopub.status.idle":"2024-11-12T05:01:33.274001Z","shell.execute_reply.started":"2024-11-12T05:01:30.689529Z","shell.execute_reply":"2024-11-12T05:01:33.272836Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 학습 데이터 \b구조\ntrain_data.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-12T05:01:34.729355Z","iopub.execute_input":"2024-11-12T05:01:34.729788Z","iopub.status.idle":"2024-11-12T05:01:34.756746Z","shell.execute_reply.started":"2024-11-12T05:01:34.729748Z","shell.execute_reply":"2024-11-12T05:01:34.755599Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### 데이터 정보 및 결측치 확인","metadata":{}},{"cell_type":"code","source":"# 학습 데이터 정보\ntrain_data.info()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-12T05:01:38.802481Z","iopub.execute_input":"2024-11-12T05:01:38.802926Z","iopub.status.idle":"2024-11-12T05:01:38.824881Z","shell.execute_reply.started":"2024-11-12T05:01:38.802887Z","shell.execute_reply":"2024-11-12T05:01:38.823381Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"모두 수치형 변수로 구성, 결측치 미확인","metadata":{}},{"cell_type":"code","source":"# 학습 데이터 통계 분포\ntrain_data.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-12T05:01:44.875126Z","iopub.execute_input":"2024-11-12T05:01:44.875598Z","iopub.status.idle":"2024-11-12T05:01:45.215748Z","shell.execute_reply.started":"2024-11-12T05:01:44.875551Z","shell.execute_reply":"2024-11-12T05:01:45.214078Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### 이상치 처리","metadata":{}},{"cell_type":"code","source":"# Amount 변수의 이상치 확인\nplt.figure(figsize=(10, 6))\nsns.boxplot(x=train_data['Amount'])\nplt.title('Amount outlier check')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-12T05:01:50.781679Z","iopub.execute_input":"2024-11-12T05:01:50.782569Z","iopub.status.idle":"2024-11-12T05:01:51.040759Z","shell.execute_reply.started":"2024-11-12T05:01:50.782521Z","shell.execute_reply":"2024-11-12T05:01:51.039141Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 사분위수를 이용한 이상치 제거\nq1 = train_data['Amount'].quantile(0.25)\nq3 = train_data['Amount'].quantile(0.75)\niqr = q3 - q1\nlower_bound = q1 - 1.5 * iqr\nupper_bound = q3 + 1.5 * iqr\n\n# 범위를 벗어나는 이상치 제거\ntrain_data = train_data[(train_data['Amount'] >= lower_bound) & (train_data['Amount'] <= upper_bound)]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-12T05:01:53.704618Z","iopub.execute_input":"2024-11-12T05:01:53.705025Z","iopub.status.idle":"2024-11-12T05:01:53.739140Z","shell.execute_reply.started":"2024-11-12T05:01:53.704987Z","shell.execute_reply":"2024-11-12T05:01:53.737670Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Amount 변수의 이상치 제거 확인\nplt.figure(figsize=(10, 6))\nsns.boxplot(x=train_data['Amount'])\nplt.title('Amount outlier check')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-12T05:01:58.015850Z","iopub.execute_input":"2024-11-12T05:01:58.017119Z","iopub.status.idle":"2024-11-12T05:01:58.245036Z","shell.execute_reply.started":"2024-11-12T05:01:58.017068Z","shell.execute_reply":"2024-11-12T05:01:58.243834Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### 피처 간 상관관계 분석","metadata":{}},{"cell_type":"code","source":"# 각 피처의 상관관계 파악\ncorrelation_matrix = train_data.corr()\ncorrelation_matrix","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-12T05:02:02.032615Z","iopub.execute_input":"2024-11-12T05:02:02.033025Z","iopub.status.idle":"2024-11-12T05:02:02.516555Z","shell.execute_reply.started":"2024-11-12T05:02:02.032989Z","shell.execute_reply":"2024-11-12T05:02:02.515363Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 피처 간 상관관계 히트맵 시각화\nplt.figure(figsize=(14, 10))\nsns.heatmap(correlation_matrix, cmap='coolwarm', annot=True, fmt='.2f')\nplt.title('피처 간의 상관관계')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-12T05:02:06.309623Z","iopub.execute_input":"2024-11-12T05:02:06.310044Z","iopub.status.idle":"2024-11-12T05:02:08.926078Z","shell.execute_reply.started":"2024-11-12T05:02:06.310005Z","shell.execute_reply":"2024-11-12T05:02:08.924871Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"피처들 간의 상관계수가 0.7 이상인 경우, 미확인. 피처들간의 독립적으로 다중공선성(multicollinearity) 문제 없음.","metadata":{}},{"cell_type":"markdown","source":"### 모델링","metadata":{}},{"cell_type":"code","source":"# 피처(X)와 레이블(y) 나누기\nX_train = train_data.drop(columns=['Class'])\ny_train = train_data['Class']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-12T05:02:12.884614Z","iopub.execute_input":"2024-11-12T05:02:12.885704Z","iopub.status.idle":"2024-11-12T05:02:12.908226Z","shell.execute_reply.started":"2024-11-12T05:02:12.885651Z","shell.execute_reply":"2024-11-12T05:02:12.906866Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 훈련 데이터와 검증 데이터 나누기\nfrom sklearn.model_selection import train_test_split\nX_train, X_valid, y_train, y_valid = train_test_split(X_train, y_train, test_size=0.2, random_state=42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-12T05:02:48.864047Z","iopub.execute_input":"2024-11-12T05:02:48.864487Z","iopub.status.idle":"2024-11-12T05:02:48.905875Z","shell.execute_reply.started":"2024-11-12T05:02:48.864443Z","shell.execute_reply":"2024-11-12T05:02:48.904531Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### 스케일링 적용","metadata":{}},{"cell_type":"markdown","source":"주성분 피처 제외한 'Amount'와 'Time' 수치변수에 대한 스케일링 적용 ","metadata":{}},{"cell_type":"code","source":"from sklearn.preprocessing import StandardScaler\n\n# StandardScaler를 사용한 표준화 진행\nscaler = StandardScaler()\n\n# 학습 데이터의 'Amount'와 'Time' 변수에 대해 스케일링 적용\ntrain_data[['Amount', 'Time']] = scaler.fit_transform(train_data[['Amount', 'Time']])\n\n# 테스트 데이터에도 같은 스케일링 적용\ntest_data[['Amount', 'Time']] = scaler.transform(test_data[['Amount', 'Time']])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-12T05:02:59.540437Z","iopub.execute_input":"2024-11-12T05:02:59.540854Z","iopub.status.idle":"2024-11-12T05:02:59.562029Z","shell.execute_reply.started":"2024-11-12T05:02:59.540817Z","shell.execute_reply":"2024-11-12T05:02:59.560806Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":" # Class 열의 사기 거래(fraud) 비율 계산\nprint(train_data['Class'].value_counts())\n\nfraud_cnt = train_data[train_data['Class'] == 1].shape[0]\ntotal_cnt = train_data['Class'].count()\n\nprint('fraud 비율은 {0:.2f}%'.format((fraud_cnt / total_cnt) * 100))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-12T05:01:07.662566Z","iopub.execute_input":"2024-11-12T05:01:07.663030Z","iopub.status.idle":"2024-11-12T05:01:07.677280Z","shell.execute_reply.started":"2024-11-12T05:01:07.662977Z","shell.execute_reply":"2024-11-12T05:01:07.676064Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"사기 거래 비율이 0.21%로 적은 비중으로 확인, 불균형 데이터에도 강한 앙상블 기법인 랜덤 포레스트(Random Forest)나 XGBoost 모델 활용 예정","metadata":{}},{"cell_type":"markdown","source":"#### 랜던 포레스트 모델","metadata":{}},{"cell_type":"code","source":"from sklearn.ensemble import RandomForestClassifier\n\n# 모델 초기화\nrf_clf = RandomForestClassifier(random_state=42, class_weight='balanced')\n\n# 모델 학습\nrf_clf.fit(X_train, y_train)\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}