import pandas as pdimport numpy as npimport sklearnimport pickle import time import datetimeimport warningswarnings.filterwarnings('ignore')
def throw(df, fraud_rate, random_state=42): # 사기 거래 비율에 맞춰 버려지는 함수! df1 = df[df['is_fraud'] ==1].copy() df0 = df[df['is_fraud'] ==0].copy() df0_downsample = (len(df1) * (1-fraud_rate)) / (len(df0) * fraud_rate) df0_down = df0.sample(frac=df0_downsample, random_state=random_state) df_p = pd.concat([df1, df0_down])return df_pdef split_dataframe(data_frame, test_fraud_rate, test_rate=0.3, random_state=42): n =len(data_frame)# 사기 거래와 정상 거래를 분리 fraud_data = data_frame[data_frame['is_fraud'] ==1] normal_data = data_frame[data_frame['is_fraud'] ==0]# 테스트 데이터 크기 계산 test_samples =int(test_fraud_rate * (n * test_rate)) remaining_test_samples =int(n * test_rate) - test_samples# 사기 거래 및 정상 거래에서 무작위로 테스트 데이터 추출 test_fraud_data = fraud_data.sample(n=test_samples, replace=False, random_state=random_state) test_normal_data = normal_data.sample(n=remaining_test_samples, replace=False, random_state=random_state)# 테스트 데이터 합치기 test_data = pd.concat([test_normal_data, test_fraud_data])# 훈련 데이터 생성 train_data = data_frame[~data_frame.index.isin(test_data.index)]return train_data, test_data