kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
8,201,023
%%writefile -a submission.py game = HungryGeese() state_dict = pickle.loads(bz2.decompress(base64.b64decode(weight))) agent = NNAgent(state_dict) mcts = MCTS(game, agent) def alphagoose_agent(obs, config): timelimit = config.actTimeout+obs.remainingOverageTime/(config.episodeSteps-obs.step)if obs.step > 50 and obs.r...
speed_test = True
Deepfake Detection Challenge
8,201,023
<set_options>
if speed_test: start_time = time.time() speedtest_videos = test_videos[:5] predictions = predict_on_video_set(speedtest_videos, num_workers=4) elapsed = time.time() - start_time print("Elapsed %f sec.Average per video: %f sec." %(elapsed, elapsed / len(speedtest_videos)) )
Deepfake Detection Challenge
8,201,023
seed = 50 os.environ['PYTHONHASHSEED'] = str(seed) random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False torch.backends.cudnn.enabled = False<set_options>
predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
8,201,023
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu' )<load_from_csv>
submission_df_resnext = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df_resnext.to_csv("submission_resnext.csv", index=False )
Deepfake Detection Challenge
8,201,023
data_path = '/kaggle/input/aerial-cactus-identification/' labels = pd.read_csv(data_path + 'train.csv') submission = pd.read_csv(data_path + 'sample_submission.csv' )<load_pretrained>
!pip install.. /input/deepfake-xception-trained-model/pytorchcv-0.0.55-py2.py3-none-any.whl --quiet
Deepfake Detection Challenge
8,201,023
with ZipFile(data_path + 'train.zip')as zipper: zipper.extractall() with ZipFile(data_path + 'test.zip')as zipper: zipper.extractall()<split>
test_dir = "/kaggle/input/deepfake-detection-challenge/test_videos/" test_videos = sorted([x for x in os.listdir(test_dir)if x[-4:] == ".mp4"]) len(test_videos )
Deepfake Detection Challenge
8,201,023
_, valid = train_test_split(labels, test_size=0.1, stratify=labels['has_cactus'], random_state=50 )<normalization>
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" )
Deepfake Detection Challenge
8,201,023
class ImageDataset(Dataset): def __init__(self, df, img_dir='./', transform=None): super().__init__() self.df = df self.img_dir = img_dir self.transform = transform def __len__(self): return len(self.df) def __getitem__(self, idx): img_id = self.df.iloc[idx, 0] img_path = self.img_dir + img_id image = cv2.imread(img_p...
facedet = BlazeFace().to(gpu) facedet.load_weights("/kaggle/input/blazeface-pytorch/blazeface.pth") facedet.load_anchors("/kaggle/input/blazeface-pytorch/anchors.npy") _ = facedet.train(False )
Deepfake Detection Challenge
8,201,023
transform_train = transforms.Compose([transforms.ToPILImage() , transforms.Pad(32, padding_mode='symmetric'), transforms.RandomHorizontalFlip() , transforms.RandomVerticalFlip() , transforms.RandomRotation(10), transforms.ToTensor() , transforms.Normalize(( 0.485, 0.456, 0.406), (0.229, 0.224, 0.225)) ]) transform_te...
frames_per_video = 83 video_reader = VideoReader() video_read_fn = lambda x: video_reader.read_frames(x, num_frames=frames_per_video) face_extractor = FaceExtractor(video_read_fn, facedet )
Deepfake Detection Challenge
8,201,023
dataset_train = ImageDataset(df=labels, img_dir='train/', transform=transform_train) dataset_valid = ImageDataset(df=valid, img_dir='train/', transform=transform_test )<load_pretrained>
input_size = 150
Deepfake Detection Challenge
8,201,023
loader_train = DataLoader(dataset=dataset_train, batch_size=32, shuffle=True) loader_valid = DataLoader(dataset=dataset_valid, batch_size=32, shuffle=False )<import_modules>
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )
Deepfake Detection Challenge
8,201,023
class Model(nn.Module): def __init__(self): super().__init__() self.layer1 = nn.Sequential(nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, padding=2), nn.BatchNorm2d(32), nn.LeakyReLU() , nn.MaxPool2d(kernel_size=2)) self.layer2 = nn.Sequential(nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=...
model = get_model("xception", pretrained=False) model = nn.Sequential(*list(model.children())[:-1]) class Pooling(nn.Module): def __init__(self): super(Pooling, self ).__init__() self.p1 = nn.AdaptiveAvgPool2d(( 1,1)) self.p2 = nn.AdaptiveMaxPool2d(( 1,1)) def forward(self, x): x1 = self.p1(x) x2 = self.p2(x) retur...
Deepfake Detection Challenge
8,201,023
model = Model().to(device )<choose_model_class>
def predict_on_video(video_path, batch_size): try: faces = face_extractor.process_video(video_path) face_extractor.keep_only_best_face(faces) if len(faces)> 0: x = np.zeros(( batch_size, input_size, input_size, 3), dtype=np.uint8) n = 0 for frame_data in faces: for face in frame_data["faces"]: resized_face = isotrop...
Deepfake Detection Challenge
8,201,023
criterion = nn.CrossEntropyLoss()<choose_model_class>
def predict_on_video_set(videos, num_workers): def process_file(i): filename = videos[i] y_pred = predict_on_video(os.path.join(test_dir, filename), batch_size=frames_per_video) return y_pred with ThreadPoolExecutor(max_workers=num_workers)as ex: predictions = ex.map(process_file, range(len(videos))) return list(pred...
Deepfake Detection Challenge
8,201,023
optimizer = torch.optim.Adamax(model.parameters() , lr=0.00006 )<categorify>
speed_test = True
Deepfake Detection Challenge
8,201,023
epochs = 70 for epoch in range(epochs): epoch_loss = 0 for images, labels in loader_train: images = images.to(device) labels = labels.to(device) optimizer.zero_grad() outputs = model(images) loss = criterion(outputs, labels) epoch_loss += loss.item() loss.backward() optimizer.step() print(f'에폭: [{epoch+1}/{epochs}]...
if speed_test: start_time = time.time() speedtest_videos = test_videos[:5] predictions = predict_on_video_set(speedtest_videos, num_workers=4) elapsed = time.time() - start_time print("Elapsed %f sec.Average per video: %f sec." %(elapsed, elapsed / len(speedtest_videos)) )
Deepfake Detection Challenge
8,201,023
dataset_test = ImageDataset(df=submission, img_dir='test/', transform=transform_test) loader_test = DataLoader(dataset=dataset_test, batch_size=32, shuffle=False) model.eval() preds = [] with torch.no_grad() : for images, _ in loader_test: images = images.to(device) outputs = model(images) preds_part = torch.softma...
%%time model.eval() predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
8,201,023
submission['has_cactus'] = preds submission.to_csv('submission.csv', index=False )<set_options>
submission_df_xception = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df_xception.to_csv("submission_xception.csv", index=False )
Deepfake Detection Challenge
8,201,023
shutil.rmtree('./train') shutil.rmtree('./test' )<set_options>
submission_df = pd.DataFrame({"filename": test_videos} )
Deepfake Detection Challenge
8,201,023
warnings.filterwarnings('ignore' )<init_hyperparams>
r1 = 0.32 r2 = 0.68 total = r1 + r2 r11 = r1/total r22 = r2/total
Deepfake Detection Challenge
8,201,023
def seed_everything(seed=0): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) def reduce_mem_usage(df, verbose=True): numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64'] start_mem = df.memory_usage().sum() / 1024**2 for col in df.columns: col_type = df[col].dtypes i...
submission_df["label"] = r22*submission_df_resnext["label"] + r11*submission_df_xception["label"]
Deepfake Detection Challenge
8,201,023
<define_variables><EOS>
submission_df.to_csv("submission.csv", index=False )
Deepfake Detection Challenge
7,717,913
<SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<init_hyperparams>
%matplotlib inline
Deepfake Detection Challenge
7,717,913
lgb_params = { 'objective':'binary', 'boosting_type':'gbdt', 'metric':'auc', 'n_jobs':-1, 'learning_rate':0.01, 'num_leaves': 2**8, 'max_depth':-1, 'tree_learner':'serial', 'colsample_bytree': 0.7, 'subsample_freq':1, 'subsample':0.7, 'n_estimators':800, 'max_bin':255, 'verbose':-1, 'seed': SEED, 'early_stopping_rounds...
test_dir = "/kaggle/input/deepfake-detection-challenge/test_videos/" test_videos = sorted([x for x in os.listdir(test_dir)if x[-4:] == ".mp4"]) len(test_videos )
Deepfake Detection Challenge
7,717,913
print('Load Data') train_df = pd.read_pickle('.. /input/ieee-fe-with-some-eda/train_df.pkl') if LOCAL_TEST: test_df = train_df[train_df['DT_M']==train_df['DT_M'].max() ].reset_index(drop=True) train_df = train_df[train_df['DT_M']<(train_df['DT_M'].max() -1)].reset_index(drop=True) else: test_df = pd.read_pickle('.....
print("PyTorch version:", torch.__version__) print("CUDA version:", torch.version.cuda) print("cuDNN version:", torch.backends.cudnn.version() )
Deepfake Detection Challenge
7,717,913
features_columns = [col for col in list(train_df)if col not in remove_features] train_df = reduce_mem_usage(train_df) test_df = reduce_mem_usage(test_df )<predict_on_test>
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu
Deepfake Detection Challenge
7,717,913
if LOCAL_TEST: lgb_params['learning_rate'] = 0.01 lgb_params['n_estimators'] = 20000 lgb_params['early_stopping_rounds'] = 100 test_predictions = make_predictions(train_df, test_df, features_columns, TARGET, lgb_params) print(metrics.roc_auc_score(test_predictions[TARGET], test_predictions['prediction'])) else: lgb_pa...
facedet = BlazeFace().to(gpu) facedet.load_weights("/kaggle/input/blazeface-pytorch/blazeface.pth") facedet.load_anchors("/kaggle/input/blazeface-pytorch/anchors.npy") _ = facedet.train(False )
Deepfake Detection Challenge
7,717,913
if not LOCAL_TEST: test_predictions['isFraud'] = test_predictions['prediction'] test_predictions[['TransactionID','isFraud']].to_csv('submission.csv', index=False )<define_variables>
frames_per_video = 17 video_reader = VideoReader() video_read_fn = lambda x: video_reader.read_frames(x, num_frames=frames_per_video) face_extractor = FaceExtractor(video_read_fn, facedet )
Deepfake Detection Challenge
7,717,913
BUILD95 = True BUILD96 = True str_type = ['ProductCD', 'card4', 'card6', 'P_emaildomain', 'R_emaildomain','M1', 'M2', 'M3', 'M4','M5', 'M6', 'M7', 'M8', 'M9', 'id_12', 'id_15', 'id_16', 'id_23', 'id_27', 'id_28', 'id_29', 'id_30', 'id_31', 'id_33', 'id_34', 'id_35', 'id_36', 'id_37', 'id_38', 'DeviceType', 'DeviceInfo'...
input_size = 224
Deepfake Detection Challenge
7,717,913
%%time X_train = pd.read_csv('.. /input/ieee-fraud-detection/train_transaction.csv',index_col='TransactionID', dtype=dtypes, usecols=cols+['isFraud']) train_id = pd.read_csv('.. /input/ieee-fraud-detection/train_identity.csv',index_col='TransactionID', dtype=dtypes) X_train = X_train.merge(train_id, how='left', left_...
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )
Deepfake Detection Challenge
7,717,913
for i in range(1,16): if i in [1,2,3,5,9]: continue X_train['D'+str(i)] = X_train['D'+str(i)] - X_train.TransactionDT/np.float32(24*60*60) X_test['D'+str(i)] = X_test['D'+str(i)] - X_test.TransactionDT/np.float32(24*60*60 )<data_type_conversions>
class MyResNeXt(models.resnet.ResNet): def __init__(self, training=True): super(MyResNeXt, self ).__init__(block=models.resnet.Bottleneck, layers=[3, 4, 6, 3], groups=32, width_per_group=4) self.fc = nn.Linear(2048, 1 )
Deepfake Detection Challenge
7,717,913
%%time for i,f in enumerate(X_train.columns): if(np.str(X_train[f].dtype)=='category')|(X_train[f].dtype=='object'): df_comb = pd.concat([X_train[f],X_test[f]],axis=0) df_comb,_ = df_comb.factorize(sort=True) if df_comb.max() >32000: print(f,'needs int32') X_train[f] = df_comb[:len(X_train)].astype('int16') X_test[...
checkpoint = torch.load("/kaggle/input/deepfakes-inference-demo/resnext.pth", map_location=gpu) model = MyResNeXt().to(gpu) model.load_state_dict(checkpoint) _ = model.eval() del checkpoint
Deepfake Detection Challenge
7,717,913
def encode_FE(df1, df2, cols): for col in cols: df = pd.concat([df1[col],df2[col]]) vc = df.value_counts(dropna=True, normalize=True ).to_dict() vc[-1] = -1 nm = col+'_FE' df1[nm] = df1[col].map(vc) df1[nm] = df1[nm].astype('float32') df2[nm] = df2[col].map(vc) df2[nm] = df2[nm].astype('float32') print(nm,', ',end...
def predict_on_video(video_path, batch_size): try: faces = face_extractor.process_video(video_path) face_extractor.keep_only_best_face(faces) if len(faces)> 0: x = np.zeros(( batch_size, input_size, input_size, 3), dtype=np.uint8) n = 0 for frame_data in faces: for face in frame_data["faces"]: resized_face = isotrop...
Deepfake Detection Challenge
7,717,913
%%time X_train['cents'] =(X_train['TransactionAmt'] - np.floor(X_train['TransactionAmt'])).astype('float32') X_test['cents'] =(X_test['TransactionAmt'] - np.floor(X_test['TransactionAmt'])).astype('float32') print('cents, ', end='') encode_FE(X_train,X_test,['addr1','card1','card2','card3','P_emaildomain']) encode_...
def predict_on_video_set(videos, num_workers): def process_file(i): filename = videos[i] y_pred = predict_on_video(os.path.join(test_dir, filename), batch_size=frames_per_video) return y_pred with ThreadPoolExecutor(max_workers=num_workers)as ex: predictions = ex.map(process_file, range(len(videos))) return list(pred...
Deepfake Detection Challenge
7,717,913
cols = list(X_train.columns) cols.remove('TransactionDT') for c in ['D6','D7','D8','D9','D12','D13','D14']: cols.remove(c) for c in ['C3','M5','id_08','id_33']: cols.remove(c) for c in ['card4','id_07','id_14','id_21','id_30','id_32','id_34']: cols.remove(c) for c in ['id_'+str(x)for x in range(22,28)]: cols.remov...
speed_test = False
Deepfake Detection Challenge
7,717,913
idxT = X_train.index[:3*len(X_train)//4] idxV = X_train.index[3*len(X_train)//4:] <train_model>
if speed_test: start_time = time.time() speedtest_videos = test_videos[:5] predictions = predict_on_video_set(speedtest_videos, num_workers=4) elapsed = time.time() - start_time print("Elapsed %f sec.Average per video: %f sec." %(elapsed, elapsed / len(speedtest_videos)) )
Deepfake Detection Challenge
7,717,913
print("XGBoost version:", xgb.__version__) if BUILD95: clf = xgb.XGBClassifier( n_estimators=2000, max_depth=12, learning_rate=0.02, subsample=0.8, colsample_bytree=0.4, missing=-1, eval_metric='auc', tree_method='gpu_hist' ) h = clf.fit(X_train.loc[idxT,cols], y_train[idxT], eval_set=[(X_train.loc[idxV,cols],y_tra...
predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
7,717,913
<train_on_grid><EOS>
submission_df = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df.to_csv("submission.csv", index=False )
Deepfake Detection Challenge
7,463,602
<SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<save_to_csv>
!pip install.. /input/facenet-pytorch-vggface2/facenet_pytorch-2.0.1-py3-none-any.whl !mkdir -p /root/.cache/torch/checkpoints/ !cp.. /input/facenet-pytorch-vggface2/20180402-114759-vggface2-logits.pth /root/.cache/torch/checkpoints/vggface2_DG3kwML46X.pt !cp.. /input/facenet-pytorch-vggface2/20180402-114759-vggface2-f...
Deepfake Detection Challenge
7,463,602
if BUILD95: plt.hist(oof,bins=100) plt.ylim(( 0,5000)) plt.title('XGB OOF') plt.show() X_train['oof'] = oof X_train.reset_index(inplace=True) X_train[['TransactionID','oof']].to_csv('oof_xgb_95.csv') X_train.set_index('TransactionID',drop=True,inplace=True) else: X_train['oof'] = 0<save_to_csv>
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
Deepfake Detection Challenge
7,463,602
if BUILD95: sample_submission = pd.read_csv('.. /input/ieee-fraud-detection/sample_submission.csv') sample_submission.isFraud = preds sample_submission.to_csv('sub_xgb_95.csv',index=False) plt.hist(sample_submission.isFraud,bins=100) plt.ylim(( 0,5000)) plt.title('XGB95 Submission') plt.show()<data_type_conversions...
submission_path = '.. /input/deepfake-detection-challenge/sample_submission.csv' train_video_path = '.. /input/deepfake-detection-challenge/train_sample_videos' test_video_path = '.. /input/deepfake-detection-challenge/test_videos'
Deepfake Detection Challenge
7,463,602
X_train['day'] = X_train.TransactionDT /(24*60*60) X_train['uid'] = X_train.card1_addr1.astype(str)+'_'+np.floor(X_train.day-X_train.D1 ).astype(str) X_test['day'] = X_test.TransactionDT /(24*60*60) X_test['uid'] = X_test.card1_addr1.astype(str)+'_'+np.floor(X_test.day-X_test.D1 ).astype(str )<categorify>
list_train = glob(os.path.join(train_video_path, '*.mp4')) print(f'Sum video in train: {len(list_train)}' )
Deepfake Detection Challenge
7,463,602
%%time encode_FE(X_train,X_test,['uid']) encode_AG(['TransactionAmt','D4','D9','D10','D15'],['uid'],['mean','std'],fillna=True,usena=True) encode_AG(['C'+str(x)for x in range(1,15)if x!=3],['uid'],['mean'],X_train,X_test,fillna=True,usena=True) encode_AG(['M'+str(x)for x in range(1,10)],['uid'],['mean'],fillna=True,...
list_test = glob(os.path.join(test_video_path, '*.mp4')) print(f'Sum video in test: {len(list_test)}' )
Deepfake Detection Challenge
7,463,602
cols = list(X_train.columns) cols.remove('TransactionDT') for c in ['D6','D7','D8','D9','D12','D13','D14']: cols.remove(c) for c in ['oof','DT_M','day','uid']: cols.remove(c) for c in ['C3','M5','id_08','id_33']: cols.remove(c) for c in ['card4','id_07','id_14','id_21','id_30','id_32','id_34']: cols.remove(c) for...
train_json = glob(os.path.join(train_video_path, '*.json')) with open(train_json[0], 'rt')as file: train = json.load(file) train_df = pd.DataFrame() train_df['file'] = train.keys() label = [i['label'] for i in train.values() if isinstance(i, dict)] train_df['label'] = label split = [i['split'] for i in train.values() ...
Deepfake Detection Challenge
7,463,602
idxT = X_train.index[:3*len(X_train)//4] idxV = X_train.index[3*len(X_train)//4:] <train_model>
original_same = train_df.pivot_table(values=['file'], columns=['label'], index=['original'], fill_value=0, aggfunc='count') original_same = original_same[(original_same[('file', 'FAKE')] != 0)&(original_same[('file', 'REAL')] != 0)] print(f'Number of file having both FAKE and REAL: {len(original_same)}') original_sam...
Deepfake Detection Challenge
7,463,602
if BUILD96: clf = xgb.XGBClassifier( n_estimators=2000, max_depth=12, learning_rate=0.02, subsample=0.8, colsample_bytree=0.4, missing=-1, eval_metric='auc', tree_method='gpu_hist' ) h = clf.fit(X_train.loc[idxT,cols], y_train[idxT], eval_set=[(X_train.loc[idxV,cols],y_train[idxV])], verbose=50, early_stopping_round...
train_df['label'] = train_df['label'].apply(lambda x: 1 if x=='FAKE' else 0 )
Deepfake Detection Challenge
7,463,602
if BUILD96: oof = np.zeros(len(X_train)) preds = np.zeros(len(X_test)) skf = GroupKFold(n_splits=6) for i,(idxT, idxV)in enumerate(skf.split(X_train, y_train, groups=X_train['DT_M'])) : month = X_train.iloc[idxV]['DT_M'].iloc[0] print('Fold',i,'withholding month',month) print(' rows of train =',len(idxT),'rows of hol...
def transfer(label): if label==0: return "real" else: return "fake" def display_mtcnn(number_frame=3, number_video=2): fake_real = original_same[(original_same[('file', 'FAKE')] == 1)&(original_same[('file', 'REAL')] == 1)].index.tolist() original_images = random.sample(fake_real, number_video) for original_image in o...
Deepfake Detection Challenge
7,463,602
if BUILD96: plt.hist(oof,bins=100) plt.ylim(( 0,5000)) plt.title('XGB OOF') plt.show() X_train['oof'] = oof X_train.reset_index(inplace=True) X_train[['TransactionID','oof']].to_csv('oof_xgb_96.csv') X_train.set_index('TransactionID',drop=True,inplace=True )<save_to_csv>
class VideoDataset(Dataset): def __init__(self, df, path_video, num_frame=5, is_train=True): super(VideoDataset, self ).__init__() self.df = df self.num_frame = num_frame self.is_train = is_train self.path_video = path_video index_list = deque() for index in tqdm(range(len(self.df))): video_name = self.df.loc[index, 'f...
Deepfake Detection Challenge
7,463,602
if BUILD96: sample_submission = pd.read_csv('.. /input/ieee-fraud-detection/sample_submission.csv') sample_submission.isFraud = preds sample_submission.to_csv('sub_xgb_96.csv',index=False) plt.hist(sample_submission.isFraud,bins=100) plt.ylim(( 0,5000)) plt.title('XGB96 Submission') plt.show()<load_from_csv>
test_size = 0.2 index_split = int(len(dataset)*test_size) list_index =(list(range(len(dataset)))) random.shuffle(list_index) train_idx = list_index[index_split:] val_idx = list_index[:index_split] train_dataset = Subset(dataset, train_idx) val_dataset = Subset(dataset, val_idx) train_ld = DataLoader(train_dataset, ...
Deepfake Detection Challenge
7,463,602
X_test['isFraud'] = sample_submission.isFraud.values X_train['isFraud'] = y_train.values comb = pd.concat([X_train[['isFraud']],X_test[['isFraud']]],axis=0) uids = pd.read_csv('/kaggle/input/ieee-submissions-and-uids/uids_v4_no_multiuid_cleaning.. csv',usecols=['TransactionID','uid'] ).rename({'uid':'uid2'},axis=1) c...
class swish(Module): def __init__(self): super(swish, self ).__init__() self.sigmoid = nn.Sigmoid() def forward(self, x): return x*self.sigmoid(x) class small_model(Module): def __init__(self, num_class=1): super(small_model, self ).__init__() self.conv = nn.Sequential(nn.Conv2d(1, 32, kernel_size=3, stride=1, padding...
Deepfake Detection Challenge
7,463,602
<import_modules><EOS>
class Trainer(object): def __init__(self, model): self.model = model self.creation = nn.MSELoss() self.optimizer = optim.AdamW([ {'params': model.conv.parameters() , 'lr': 1e-4}, {'params': model.fc.parameters() , 'lr': 1e-3}], lr=0.001) self.scheduler = ReduceLROnPlateau(self.optimizer, mode='min', factor=0.15) def ...
Deepfake Detection Challenge
17,910,828
model.train_model(shuffled_training, acc=sklearn.metrics.accuracy_score, f1=sklearn.metrics.f1_score )<predict_on_test>
%matplotlib inline warnings.filterwarnings('ignore') pd.set_option('display.max_rows', 100) pd.set_option('display.max_columns', 200 )
Home Credit Default Risk
17,910,828
result, model_outputs, wrong_predictions = model.eval_model(shuffled_training, acc=sklearn.metrics.accuracy_score, f1=sklearn.metrics.f1_score )<compute_test_metric>
app_train = pd.read_csv('.. /input/home-credit-default-risk/application_train.csv') app_test = pd.read_csv('.. /input/home-credit-default-risk/application_test.csv' )
Home Credit Default Risk
17,910,828
result<predict_on_test>
app_train.isnull().sum()
Home Credit Default Risk
17,910,828
predictions, raw_outputs = model.predict(test["text"].to_list() )<create_dataframe>
app_train['TARGET'].value_counts()
Home Credit Default Risk
17,910,828
mypreds = pd.DataFrame(test[["id"]]) mypreds["target"] = predictions<save_to_csv>
columns = ['AMT_INCOME_TOTAL','AMT_CREDIT', 'AMT_ANNUITY', 'AMT_GOODS_PRICE', 'DAYS_BIRTH', 'DAYS_EMPLOYED', 'DAYS_ID_PUBLISH', 'DAYS_REGISTRATION', 'DAYS_LAST_PHONE_CHANGE', 'CNT_FAM_MEMBERS', 'REGION_RATING_CLIENT', 'EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3', 'AMT_REQ_CREDIT_BUREAU_HOUR', 'AMT_REQ_CREDIT_BUREAU_D...
Home Credit Default Risk
17,910,828
mypreds.to_csv("submission.csv", index=False )<install_modules>
app_train['DAYS_BIRTH']=abs(app_train['DAYS_BIRTH']) app_train['DAYS_BIRTH'].corr(app_train['TARGET'] )
Home Credit Default Risk
17,910,828
! python -m pip install tf-models-nightly --no-deps -q ! python -m pip install tf-models-official==2.4.0 -q ! python -m pip install tensorflow-gpu==2.4.1 -q ! python -m pip install tensorflow-text==2.4.1 -q ! python -m spacy download en_core_web_sm -q ! python -m spacy validate<import_modules>
app_train[['EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3']].isnull().sum()
Home Credit Default Risk
17,910,828
print(f'TensorFlow Version: {tf.__version__}') print(f'Python Version: {python_version() }' )<set_options>
app_train['EXT_SOURCE_3'].value_counts(dropna=False )
Home Credit Default Risk
17,910,828
RANDOM_SEED = 123 nlp = spacy.load('en_core_web_sm') pd.set_option('display.max_colwidth', None) rcParams['figure.figsize'] =(10, 6) sns.set_theme(palette='muted', style='whitegrid' )<load_from_csv>
cond_1 =(app_train['TARGET'] == 1) cond_0 =(app_train['TARGET'] == 0) print(app_train['CODE_GENDER'].value_counts() /app_train.shape[0]) print(' 연체인 경우 ',app_train[cond_1]['CODE_GENDER'].value_counts() /app_train[cond_1].shape[0]) print(' 연체가 아닌 경우 ',app_train[cond_0]['CODE_GENDER'].value_counts() /app_train[cond_0...
Home Credit Default Risk
17,910,828
path = '.. /input/nlp-getting-started/train.csv' df = pd.read_csv(path) print(df.shape) df.head()<load_from_csv>
app_train = pd.read_csv('.. /input/home-credit-default-risk/application_train.csv') app_test = pd.read_csv('.. /input/home-credit-default-risk/application_test.csv' )
Home Credit Default Risk
17,910,828
path_test = '.. /input/nlp-getting-started/test.csv' df_test = pd.read_csv(path_test) print(df_test.shape) df_test.head()<count_duplicates>
apps = pd.concat([app_train, app_test]) print(apps.shape )
Home Credit Default Risk
17,910,828
duplicates = df[df.duplicated(['text', 'target'], keep=False)] print(f'Train Duplicate Entries(text, target): {len(duplicates)}') duplicates.head()<remove_duplicates>
def get_apps_processed(apps): apps['APPS_EXT_SOURCE_MEAN'] = apps[['EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3']].mean(axis=1) apps['APPS_EXT_SOURCE_STD'] = apps[['EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3']].std(axis=1) apps['APPS_EXT_SOURCE_STD'] = apps['APPS_EXT_SOURCE_STD'].fillna(apps['APPS_EXT_SOURCE_STD']...
Home Credit Default Risk
17,910,828
df.drop_duplicates(['text', 'target'], inplace=True, ignore_index=True) print(df.shape, df_test.shape )<count_duplicates>
prev_app = pd.read_csv('.. /input/home-credit-default-risk/previous_application.csv') print(prev_app.shape, apps.shape )
Home Credit Default Risk
17,910,828
new_duplicates = df[df.duplicated(['keyword', 'text'], keep=False)] print(f'Train Duplicate Entries(keyword, text): {len(new_duplicates)}') new_duplicates[['text', 'target']].sort_values(by='text' )<drop_column>
prev_app_outer = prev_app.merge(apps['SK_ID_CURR'], on='SK_ID_CURR', how='outer', indicator=True )
Home Credit Default Risk
17,910,828
df.drop([4253, 4193, 2802, 4554, 4182, 3212, 4249, 4259, 6535, 4319, 4239, 606, 3936, 6018, 5573], inplace=True )<drop_column>
prev_app_outer['_merge'].value_counts()
Home Credit Default Risk
17,910,828
df = df.reset_index(drop=True) df<count_values>
def missing_data(data): total = data.isnull().sum().sort_values(ascending = False) percent =(data.isnull().sum() /data.isnull().count() *100 ).sort_values(ascending = False) return pd.concat([total, percent], axis=1, keys=['Total', 'Percent'] )
Home Credit Default Risk
17,910,828
df['target'].value_counts() / len(df )<count_missing_values>
prev_app.groupby('SK_ID_CURR' ).count()
Home Credit Default Risk
17,910,828
def null_table(data): null_list = [] for i in data: if data[i].notnull().any() : null_list.append(data[i].notnull().value_counts()) return pd.DataFrame(pd.concat(null_list, axis=1 ).T )<count_missing_values>
prev_app.groupby('SK_ID_CURR')['SK_ID_CURR'].count()
Home Credit Default Risk
17,910,828
null_table(df )<count_missing_values>
app_prev_target = prev_app.merge(app_train[['SK_ID_CURR', 'TARGET']], on='SK_ID_CURR', how='left') app_prev_target.shape
Home Credit Default Risk
17,910,828
null_table(df_test )<define_variables>
num_columns = [column for column in num_columns if column not in ['SK_ID_PREV', 'SK_ID_CURR', 'TARGET']] num_columns
Home Credit Default Risk
17,910,828
text = df['text'] target = df['target'] test_text = df_test['text'] for i in np.random.randint(500, size=5): print(f'Tweet ' * 2 )<define_variables>
app_prev_target.TARGET.value_counts()
Home Credit Default Risk
17,910,828
lookup_dict = { 'abt' : 'about', 'afaik' : 'as far as i know', 'bc' : 'because', 'bfn' : 'bye for now', 'bgd' : 'background', 'bh' : 'blockhead', 'br' : 'best regards', 'btw' : 'by the way', 'cc': 'carbon copy', 'chk' : 'check', 'dam' : 'do not annoy me', 'dd' : 'dear daughter', 'df': 'dear fiance', 'ds' : 'dear son', ...
print(app_prev_target.groupby('TARGET' ).agg({'AMT_ANNUITY': ['mean', 'median', 'count']})) print(app_prev_target.groupby('TARGET' ).agg({'AMT_APPLICATION': ['mean', 'median', 'count']})) print(app_prev_target.groupby('TARGET' ).agg({'AMT_CREDIT': ['mean', 'median', 'count']}))
Home Credit Default Risk
17,910,828
def lemmatize_text(text, nlp=nlp): doc = nlp(text) lemma_sent = [i.lemma_ for i in doc if not i.is_stop] return ' '.join(lemma_sent) def abbrev_conversion(text): words = text.split() abbrevs_removed = [] for i in words: if i in lookup_dict: i = lookup_dict[i] abbrevs_removed.append(i) return ' '.join(abbrevs_removed...
app_prev_target.groupby(['NAME_CONTRACT_TYPE', 'NAME_GOODS_CATEGORY'] ).agg({'AMT_ANNUITY': ['mean', 'median', 'count', 'max']} )
Home Credit Default Risk
17,910,828
df['clean_text'] = pd.DataFrame(clean_text) df_test['clean_text'] = pd.DataFrame(test_clean_text )<feature_engineering>
prev_app.groupby('SK_ID_CURR' )
Home Credit Default Risk
17,910,828
df['clean_text'] = df['clean_text'].apply(lambda x: re.sub(pattern_new, '', x)if pd.isna(x)!= True else x) df_test['clean_text'] = df_test['clean_text'].apply(lambda x: re.sub(pattern_new, '', x)if pd.isna(x)!= True else x )<count_values>
prev_group = prev_app.groupby('SK_ID_CURR') prev_group.head()
Home Credit Default Risk
17,910,828
print('Training Counts of 'new': ', len(re.findall(pattern_new, ' '.join(df['clean_text'])))) print('Test Counts of 'new': ', len(re.findall(pattern_new, ' '.join(df_test['clean_text']))))<load_pretrained>
prev_agg = pd.DataFrame() prev_agg['CNT'] = prev_group['SK_ID_CURR'].count() prev_agg.head()
Home Credit Default Risk
17,910,828
sentence_enc = hub.load('https://tfhub.dev/google/universal-sentence-encoder/4' )<string_transform>
prev_agg['AVG_CREDIT'] = prev_group['AMT_CREDIT'].mean() prev_agg['MAX_CREDIT'] = prev_group['AMT_CREDIT'].max() prev_agg['MIN_CREDIT'] = prev_group['AMT_CREDIT'].min() prev_agg.head()
Home Credit Default Risk
17,910,828
def extract_keywords(text, nlp=nlp): potential_keywords = [] TOP_KEYWORD = -1 pos_tag = ['ADJ', 'NOUN', 'PROPN'] doc = nlp(text) for i in doc: if i.pos_ in pos_tag: potential_keywords.append(i.text) document_embed = sentence_enc([text]) potential_embed = sentence_enc(potential_keywords) vector_distances = cosine_si...
prev_group = prev_app.groupby('SK_ID_CURR') prev_agg1 = prev_group['AMT_CREDIT'].agg(['mean', 'max', 'min']) prev_agg2 = prev_group['AMT_ANNUITY'].agg(['mean', 'max', 'min']) prev_agg = prev_agg1.merge(prev_agg2, on='SK_ID_CURR', how='inner') prev_agg.head()
Home Credit Default Risk
17,910,828
df['keyword_fill'] = pd.DataFrame(list(map(keyword_filler, df['keyword'], df['clean_text'])) ).astype(str) df_test['keyword_fill'] = pd.DataFrame(list(map(keyword_filler, df_test['keyword'], df_test['clean_text'])) ).astype(str) print('Null Training Keywords => ', df['keyword_fill'].isnull().any()) print('Null Test ...
prev_app['PREV_CREDIT_DIFF'] = prev_app['AMT_APPLICATION'] - prev_app['AMT_CREDIT'] prev_app['PREV_GOODS_DIFF'] = prev_app['AMT_APPLICATION'] - prev_app['AMT_GOODS_PRICE'] prev_app['PREV_CREDIT_APPL_RATIO'] = prev_app['AMT_CREDIT']/prev_app['AMT_APPLICATION'] prev_app['PREV_ANNUITY_APPL_RATIO'] = prev_app['AMT_ANNUITY'...
Home Credit Default Risk
17,910,828
df['keyword_fill'] = pd.DataFrame(standardize_text(df['keyword_fill'])) df_test['keyword_fill'] = pd.DataFrame(standardize_text(df_test['keyword_fill']))<count_values>
prev_app['DAYS_FIRST_DRAWING'].replace(365243, np.nan, inplace=True) prev_app['DAYS_FIRST_DUE'].replace(365243, np.nan, inplace= True) prev_app['DAYS_LAST_DUE_1ST_VERSION'].replace(365243, np.nan, inplace= True) prev_app['DAYS_LAST_DUE'].replace(365243, np.nan, inplace= True) prev_app['DAYS_TERMINATION'].replace(36...
Home Credit Default Risk
17,910,828
keyword_count_0 = pd.DataFrame(df['keyword_fill'][df['target']==0].value_counts().reset_index()) keyword_count_1 = pd.DataFrame(df['keyword_fill'][df['target']==1].value_counts().reset_index() )<define_variables>
all_pay = prev_app['AMT_ANNUITY'] * prev_app['CNT_PAYMENT'] prev_app['PREV_INTERESTS_RATE'] =(all_pay/prev_app['AMT_CREDIT'] - 1)/prev_app['CNT_PAYMENT']
Home Credit Default Risk
17,910,828
train_features = df[['clean_text','keyword_fill']] test_features = df_test[['clean_text', 'keyword_fill']]<split>
agg_dict = { 'SK_ID_CURR':['count'], 'AMT_CREDIT':['mean', 'max', 'sum'], 'AMT_ANNUITY':['mean', 'max', 'sum'], 'AMT_APPLICATION':['mean', 'max', 'sum'], 'AMT_DOWN_PAYMENT':['mean', 'max', 'sum'], 'AMT_GOODS_PRICE':['mean', 'max', 'sum'], 'RATE_DOWN_PAYMENT': ['min', 'max', 'mean'], 'DAYS_DECISION': ['min', 'max', 'mea...
Home Credit Default Risk
17,910,828
train_x, val_x, train_y, val_y = train_test_split( train_features, target, test_size=0.2, random_state=RANDOM_SEED, ) print(train_x.shape) print(train_y.shape) print(val_x.shape) print(val_y.shape )<create_dataframe>
prev_group = prev_app.groupby('SK_ID_CURR') prev_amt_agg = prev_group.agg(agg_dict) prev_amt_agg.columns = ['PREV_'+('_' ).join(column ).upper() for column in prev_amt_agg.columns.ravel() ]
Home Credit Default Risk
17,910,828
train_ds = tf.data.Dataset.from_tensor_slices(( dict(train_x), train_y)) val_ds = tf.data.Dataset.from_tensor_slices(( dict(val_x), val_y)) test_ds = tf.data.Dataset.from_tensor_slices(dict(test_features))<categorify>
prev_app['NAME_CONTRACT_STATUS'].value_counts()
Home Credit Default Risk
17,910,828
AUTOTUNE = tf.data.experimental.AUTOTUNE BUFFER_SIZE = 1000 BATCH_SIZE = 32 def configure_dataset(dataset, shuffle=False, test=False): if shuffle: dataset = dataset.cache() \ .shuffle(BUFFER_SIZE, seed=RANDOM_SEED, reshuffle_each_iteration=True)\ .batch(BATCH_SIZE, drop_remainder=True ).prefetch(AUTOTUNE) elif test:...
prev_refused_agg = prev_refused.groupby('SK_ID_CURR')['SK_ID_CURR'].count() prev_refused_agg.shape, prev_amt_agg.shape
Home Credit Default Risk
17,910,828
train_ds = configure_dataset(train_ds, shuffle=True) val_ds = configure_dataset(val_ds) test_ds = configure_dataset(test_ds, test=True )<categorify>
pd.DataFrame(prev_refused_agg )
Home Credit Default Risk
17,910,828
bert_preprocessor = hub.KerasLayer('https://tfhub.dev/tensorflow/bert_en_uncased_preprocess/3', name='BERT_preprocesser') bert_encoder = hub.KerasLayer('https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/4', trainable=True, name='BERT_encoder') nnlm_embed = hub.KerasLayer('https://tfhub.dev/google/nnlm-en-d...
prev_refused_agg.reset_index(name='PREV_REFUSED_COUNT' )
Home Credit Default Risk
17,910,828
def build_model() : text_input = layers.Input(shape=() , dtype=tf.string, name='clean_text') encoder_inputs = bert_preprocessor(text_input) encoder_outputs = bert_encoder(encoder_inputs) pooled_output = encoder_outputs["pooled_output"] bert_dropout = layers.Dropout(0.1, name='BERT_dropout' )(pooled_output) key_inpu...
prev_refused_agg = prev_refused_agg.reset_index(name='PREV_REFUSED_COUNT') prev_amt_agg = prev_amt_agg.reset_index() prev_amt_refused_agg = prev_amt_agg.merge(prev_refused_agg, on='SK_ID_CURR', how='left') prev_amt_refused_agg.head(10 )
Home Credit Default Risk
17,910,828
EPOCHS = 2 LEARNING_RATE = 5e-5 STEPS_PER_EPOCH = int(train_ds.unbatch().cardinality().numpy() / BATCH_SIZE) VAL_STEPS = int(val_ds.unbatch().cardinality().numpy() / BATCH_SIZE) TRAIN_STEPS = STEPS_PER_EPOCH * EPOCHS WARMUP_STEPS = int(TRAIN_STEPS * 0.1) adamw_optimizer = create_optimizer( init_lr=LEARNING_RATE, nu...
prev_amt_refused_agg['PREV_REFUSED_COUNT'].value_counts(dropna=False )
Home Credit Default Risk
17,910,828
bert_classifier.compile( loss=BinaryCrossentropy(from_logits=True), optimizer= adamw_optimizer, metrics=[BinaryAccuracy(name='accuracy')] ) history = bert_classifier.fit( train_ds, epochs=EPOCHS, steps_per_epoch=STEPS_PER_EPOCH, validation_data= val_ds, validation_steps=VAL_STEPS )<find_best_params>
prev_amt_refused_agg = prev_amt_refused_agg.fillna(0) prev_amt_refused_agg['PREV_REFUSE_RATIO'] = prev_amt_refused_agg['PREV_REFUSED_COUNT'] / prev_amt_refused_agg['PREV_SK_ID_CURR_COUNT'] prev_amt_refused_agg.head(10 )
Home Credit Default Risk
17,910,828
train_loss = history.history['loss'] val_loss = history.history['val_loss'] train_acc = history.history['accuracy'] val_acc = history.history['val_accuracy']<define_variables>
prev_refused_appr_group = prev_app[prev_app['NAME_CONTRACT_STATUS'].isin(['Approved', 'Refused'])].groupby(['SK_ID_CURR', 'NAME_CONTRACT_STATUS']) prev_refused_appr_agg = prev_refused_appr_group['SK_ID_CURR'].count().unstack() prev_refused_appr_agg.head(10 )
Home Credit Default Risk
17,910,828
val_target = np.asarray([i[1] for i in list(val_ds.unbatch().as_numpy_iterator())]) print(val_target.shape) val_target[:5]<predict_on_test>
prev_refused_appr_agg = prev_refused_appr_agg.fillna(0) prev_refused_appr_agg.columns = ['PREV_APPROVED_COUNT', 'PREV_REFUSED_COUNT'] prev_refused_appr_agg = prev_refused_appr_agg.reset_index() prev_refused_appr_agg.head(10 )
Home Credit Default Risk
17,910,828
val_predict = bert_classifier.predict(val_ds )<predict_on_test>
prev_agg = prev_amt_agg.merge(prev_refused_appr_agg, on='SK_ID_CURR', how='left') prev_agg['PREV_REFUSED_RATIO'] = prev_agg['PREV_REFUSED_COUNT']/prev_agg['PREV_SK_ID_CURR_COUNT'] prev_agg['PREV_APPROVED_RATIO'] = prev_agg['PREV_APPROVED_COUNT']/prev_agg['PREV_SK_ID_CURR_COUNT'] prev_agg = prev_agg.drop(['PREV_REFUSED...
Home Credit Default Risk
17,910,828
predictions = bert_classifier.predict(test_ds) print(predictions.shape) print(predictions[:5] )<prepare_output>
apps_all = get_apps_processed(apps )
Home Credit Default Risk
17,910,828
predictions = np.where(predictions > THRESHOLD, 1, 0) df_predictions = pd.DataFrame(predictions) df_predictions.columns = ['target'] print(df_predictions.shape) df_predictions.head()<save_to_csv>
print(apps_all.shape, prev_agg.shape) apps_all = apps_all.merge(prev_agg, on='SK_ID_CURR', how='left') print(apps_all.shape )
Home Credit Default Risk
17,910,828
submission = pd.concat([df_test['id'], df_predictions], axis=1) submission.to_csv('submission.csv', index=False )<load_from_csv>
object_columns = apps_all.dtypes[apps_all.dtypes == 'object'].index.tolist() for column in object_columns: apps_all[column] = pd.factorize(apps_all[column])[0]
Home Credit Default Risk
17,910,828
train_filepath = '/kaggle/input/nlp-getting-started/train.csv' test_filepath = '/kaggle/input/nlp-getting-started/test.csv' df_train = pd.read_csv(train_filepath) df_test = pd.read_csv(test_filepath) df_train.head() <feature_engineering>
apps_all_train = apps_all[~apps_all['TARGET'].isnull() ] apps_all_test = apps_all[apps_all['TARGET'].isnull() ] apps_all_test = apps_all_test.drop('TARGET', axis=1 )
Home Credit Default Risk
17,910,828
lemmatizer = WordNetLemmatizer() for i in range(0, len(df_train)) : text = re.sub('[^a-zA-Z]', ' ', df_train['text'][i]) text = text.lower() text = re.sub(r'^https?:\/\/.*[\r ]*', '', text) text = text.split() text = [lemmatizer.lemmatize(word)for word in text if word not in stopwords.words('english')] text = ' '.joi...
ftr_app = apps_all_train.drop(['SK_ID_CURR', 'TARGET'], axis=1) target_app = apps_all_train['TARGET'] train_x, valid_x, train_y, valid_y = train_test_split(ftr_app, target_app, test_size=0.3, random_state=2020) train_x.shape, valid_x.shape
Home Credit Default Risk
17,910,828
for i in range(0, len(df_test)) : text = re.sub('[^a-zA-Z]', ' ', df_test['text'][i]) text = text.lower() text = re.sub(r'^https?:\/\/.*[\r ]*', '', text) text = text.split() text = [lemmatizer.lemmatize(word)for word in text if word not in stopwords.words('english')] text = ' '.join(text) df_test['text'][i] = text ...
clf = LGBMClassifier( n_jobs=-1, n_estimators=1000, learning_rate=0.02, num_leaves=32, subsample=0.8, max_depth=12, silent=-1, verbose=-1 ) clf.fit(train_x, train_y, eval_set=[(train_x, train_y),(valid_x, valid_y)], eval_metric= 'auc', verbose= 100, early_stopping_rounds= 50 )
Home Credit Default Risk