kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
7,930,779
train.drop(['PID'], axis=1, inplace=True )<load_from_csv>
frames_per_video = 64 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,930,779
df_test=pd.read_csv(".. /input/house-prices-advanced-regression-techniques/test.csv" )<count_missing_values>
input_size = 224
Deepfake Detection Challenge
7,930,779
df_test.isna().sum()<load_from_csv>
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )
Deepfake Detection Challenge
7,930,779
submission = pd.read_csv('.. /input/house-prices-advanced-regression-techniques/sample_submission.csv' )<load_from_csv>
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,930,779
df_train=pd.read_csv(".. /input/house-prices-advanced-regression-techniques/train.csv" )<drop_column>
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,930,779
missing = df_test.isnull().sum() missing = missing[missing>0] train.drop(missing.index, axis=1, inplace=True) train.drop(['Electrical'], axis=1, inplace=True) df_test.dropna(axis=1, inplace=True) df_test.drop(['Electrical'], axis=1, inplace=True )<count_duplicates>
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,930,779
test = tqdm(range(0, len(df_test)) , desc='Matching') for i in test: for j in range(0, len(train)) : for k in range(1, len(df_test.columns)) : if df_test.iloc[i,k] == train.iloc[j,k]: continue else: break else: submission.iloc[i, 1] = train.iloc[j, -1] break test.close()<save_to_csv>
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,930,779
submission.to_csv('enes_results.csv', index=False )<import_modules>
speed_test = False
Deepfake Detection Challenge
7,930,779
!pip install contractions nltk.download("stopwords") nltk.download('punkt') nltk.download('wordnet') for dirname, _, filenames in os.walk('/kaggle/input'): for filename in filenames: print(os.path.join(dirname, filename)) train = pd.read_csv('/kaggle/input/jigsaw-toxic-comment-classification-challenge/train.csv.zip'...
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,930,779
class_names = ['toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate'] train_text = train['comment_text'] test_text = test['comment_text'] all_text = pd.concat([train_text, test_text] )<string_transform>
predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
7,930,779
<feature_engineering><EOS>
submission_df = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df.to_csv("submission.csv", index=False )
Deepfake Detection Challenge
7,808,440
<SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<categorify>
%matplotlib inline
Deepfake Detection Challenge
7,808,440
if False: word_vectorizer = pickle.load(open("word_vectorizer.pk", "rb")) char_vectorizer = pickle.load(open("char_vectorizer.pk", "rb")) train_word_features = word_vectorizer.transform(train_text) test_word_features = word_vectorizer.transform(test_text) train_char_features = char_vectorizer.transform(train_text) t...
frames_per_vid = [17, 25, 30, 32, 35, 36, 38, 39, 40, 49, 56, 64, 72, 80, 81, 82, 100] public_LB = [0.46788, 0.46776, 0.46611, 0.46542, 0.46643, 0.46484, 0.46444, 0.46603, 0.46635, 0.46620, 0.46481, 0.46441, 0.46559, 0.46518, 0.46453, 0.46482, 0.46495] df_viz = pd.DataFrame({'frames_per_vid': frames_per_vid, 'public_LB...
Deepfake Detection Challenge
7,808,440
del train_word_features, test_word_features,train_char_features, test_char_features, del word_vectorizer, char_vectorizer<create_dataframe>
test_dir = "/kaggle/input/deepfake-detection-challenge/test_videos/" test_videos = sorted([x for x in os.listdir(test_dir)if x[-4:] == ".mp4"]) frame_h = 5 frame_l = 5 len(test_videos )
Deepfake Detection Challenge
7,808,440
%%time scores = [] submission = pd.DataFrame.from_dict({'id': test['id']}) for class_name in class_names: train_target = train[class_name] classifier = LogisticRegression(solver='sag',n_jobs=-1) cv_score = np.mean(cross_val_score(classifier, train_features, train_target, cv=3, scoring='roc_auc')) scores.append(cv_sco...
print("PyTorch version:", torch.__version__) print("CUDA version:", torch.version.cuda) print("cuDNN version:", torch.backends.cudnn.version() )
Deepfake Detection Challenge
7,808,440
import tensorflow as tf from tensorflow.keras import layers import os import re import math import numpy as np import matplotlib.pyplot as plt import pandas as pd<define_variables>
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu
Deepfake Detection Challenge
7,808,440
GCS_DS_PATH = ".. /input/ranzcr-clip-catheter-line-classification"<load_from_csv>
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,808,440
train_df = pd.read_csv(GCS_DS_PATH+"/train.csv") train_df.index = train_df["StudyInstanceUID"] del train_df["StudyInstanceUID"] train_annot_df = pd.read_csv(GCS_DS_PATH+"/train_annotations.csv") train_annot_df.index = train_annot_df["StudyInstanceUID"] del train_annot_df["StudyInstanceUID"]<define_variables>
frames_per_video = 65 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,808,440
classes = list(train_df.columns[:-1]) classes_normal= [name for name in classes[:-1] if name.split(" - ")[1] == "Normal"] classes_abnormal= [name for name in classes[:-1] if name.split(" - ")[1] == "Abnormal"] classes_borderline = [name for name in classes[:-1] if name.split(" - ")[1] == "Borderline"] classes_count = ...
input_size = 224
Deepfake Detection Challenge
7,808,440
class_weights = {} ls = list(classes_count.values) tot_samples = sum(ls) for i in range(num_classes): class_weights[i] = tot_samples/(num_classes*ls[i]) class_weights<count_values>
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )
Deepfake Detection Challenge
7,808,440
patient_ids = train_df["PatientID"].unique() patientwise_count = train_df['PatientID'].value_counts() num_patients = len(patientwise_count) print("Number of patients: ",num_patients) patientwise_count<define_variables>
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,808,440
IMAGE_SIZE = [600,600] AUTO = tf.data.experimental.AUTOTUNE TEST_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH + '/test_tfrecords/*.tfrec' )<categorify>
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,808,440
def decode_image(image_data): image = tf.image.decode_jpeg(image_data, channels=3) image = tf.cast(image, tf.float32)/ 255.0 image = tf.image.resize(image, [*IMAGE_SIZE]) return image def read_labeled_tfrecord(example): LABELED_TFREC_FORMAT = { "StudyInstanceUID" : tf.io.FixedLenFeature([], tf.string), "image" : tf.i...
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,808,440
def data_augment(image, label): image = tf.image.random_flip_left_right(image) return image,label def get_test_dataset(ordered=False): dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered) dataset = dataset.map(data_augment, num_parallel_calls=AUTO) dataset = dataset.batch(BATCH_SIZE) dataset = dat...
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,808,440
BATCH_SIZE = 16 * strategy.num_replicas_in_sync test_ds = get_test_dataset() print("Test:", test_ds )<install_modules>
speed_test = False
Deepfake Detection Challenge
7,808,440
!pip install /kaggle/input/kerasapplications -q !pip install /kaggle/input/efficientnet-keras-source-code/ -q --no-deps <load_pretrained>
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,808,440
model = tf.keras.models.load_model(".. /input/ranzcr-clip-tpu/model.h5" )<save_to_csv>
predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
7,808,440
<set_options><EOS>
submission_df = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df.to_csv("submission.csv", index=False )
Deepfake Detection Challenge
7,955,513
<SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<train_model>
%matplotlib inline
Deepfake Detection Challenge
7,955,513
print('Train images: %d' %len(os.listdir(os.path.join(WORK_DIR, "train"))))<load_from_csv>
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,955,513
train = pd.read_csv(os.path.join(WORK_DIR, "train.csv")) train_images = WORK_DIR + "/train/" + train['StudyInstanceUID'] + '.jpg' ss = pd.read_csv(os.path.join(WORK_DIR, 'sample_submission.csv')) test_images = WORK_DIR + "/test/" + ss['StudyInstanceUID'] + '.jpg' label_cols = ss.columns[1:] labels = train[label_cols].v...
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu
Deepfake Detection Challenge
7,955,513
BATCH_SIZE = 8 * 1 STEPS_PER_EPOCH = len(train)* 0.85 / BATCH_SIZE VALIDATION_STEPS = len(train)* 0.15 / BATCH_SIZE EPOCHS = 30 TARGET_SIZE = 750<categorify>
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,955,513
def build_decoder(with_labels = True, target_size =(TARGET_SIZE, TARGET_SIZE), ext = 'jpg'): def decode(path): file_bytes = tf.io.read_file(path) if ext == 'png': img = tf.image.decode_png(file_bytes, channels = 3) elif ext in ['jpg', 'jpeg']: img = tf.image.decode_jpeg(file_bytes, channels = 3) else: raise ValueErr...
frames_per_video = 150 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,955,513
test_df = build_dataset( test_images, bsize = BATCH_SIZE, repeat = False, shuffle = False, augment = False, cache = False) test_df<choose_model_class>
input_size =224
Deepfake Detection Challenge
7,955,513
<choose_model_class>
mean = [0.43216, 0.394666, 0.37645] std = [0.22803, 0.22145, 0.216989] normalize_transform = Normalize(mean,std )
Deepfake Detection Challenge
7,955,513
print('Our Xception CNN has %d layers' %len(model.layers))<create_dataframe>
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,955,513
img_tensor = build_dataset( pd.Series(test_images[0]), bsize = 1,repeat = False, shuffle = False, augment = False, cache = False )<save_to_csv>
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,955,513
ss[label_cols] = model.predict(test_df, verbose = 1) ss.to_csv('submission.csv', index = False )<define_variables>
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,955,513
class CFG: device = 'GPU' cpu_workers = 2 debug = True seed = 13353 batch_size = 50 num_tta = 2 num_folds = 3 fold_idx = False fold_blend = 'pmean' model_blend = 'pmean' power = 1/11 w_public = 0.25 lgb_folds = 5 label_features = False sort_targets = True pred_as_feature = True lgb_stop_rounds = 200 lgb_params = {'obje...
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,955,513
CFG = dict(vars(CFG)) for key in ['__dict__', '__doc__', '__module__', '__weakref__']: del CFG[key]<load_pretrained>
speed_test = False
Deepfake Detection Challenge
7,955,513
CFGs = [] for model in CFG['models']: model_cfg = pickle.load(open(model + 'configuration.pkl', 'rb')) CFGs.append(model_cfg) print('Numer of models:', len(CFGs))<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
7,955,513
pd.set_option('display.max_columns', 100) ImageFile.LOAD_TRUNCATED_IMAGES = True %matplotlib inline warnings.filterwarnings('ignore') sys.path.append('.. /input/timm-pytorch-image-models/pytorch-image-models-master') <train_model>
predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
7,955,513
<compute_test_metric><EOS>
submission_df = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df.to_csv("submission.csv", index=False )
Deepfake Detection Challenge
8,684,188
<SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<load_from_csv>
!pip install.. /input/kaggle-efficientnet-repo/efficientnet-1.0.0-py3-none-any.whl
Deepfake Detection Challenge
8,684,188
df = pd.read_csv(CFG['data_path'] + 'sample_submission.csv') CFG['targets'] = ['ETT - Abnormal', 'ETT - Borderline', 'ETT - Normal', 'NGT - Abnormal', 'NGT - Borderline', 'NGT - Incompletely Imaged', 'NGT - Normal', 'CVC - Abnormal', 'CVC - Borderline', 'CVC - Normal', 'Swan Ganz Catheter Present'] CFG['num_classes'] ...
import pandas as pd import tensorflow as tf import cv2 import glob from tqdm.notebook import tqdm import numpy as np import os from keras.layers import * from keras import Model import matplotlib.pyplot as plt import time from keras.applications.xception import Xception import efficientnet.keras as efn
Deepfake Detection Challenge
8,684,188
for m in CFG['models']: tmp_train_preds = pd.read_csv(m + '/oof.csv') tmp_train_preds.columns = ['StudyInstanceUID'] + CFG['targets'] + ['PatientID', 'fold'] + [m + ' ' + c for c in CFG['targets']] if m == CFG['models'][0]: train_preds = tmp_train_preds else: train_preds = train_preds.merge(tmp_train_preds[['StudyInst...
import torch import torch.nn as nn import torch.nn.functional as F
Deepfake Detection Challenge
8,684,188
for c in CFG['targets']: class_preds = train_preds.filter(like = 'kaggle' ).filter(like = c ).columns for blend in ['amean', 'median', 'gmean', 'pmean', 'rmean']: train_preds[blend + ' ' + c] = compute_blend(train_preds, class_preds, blend, CFG) for blend in ['amean', 'median', 'gmean', 'pmean', 'rmean']: train_preds[...
print("PyTorch version:", torch.__version__) print("CUDA version:", torch.version.cuda) print("cuDNN version:", torch.backends.cudnn.version() )
Deepfake Detection Challenge
8,684,188
def get_dataset(CFG): class ImageData(Dataset): def __init__(self, df, path, transform = None, labeled = False, indexed = False): self.df = df self.path = path self.transform = transform self.labeled = labeled self.indexed = indexed def __len__(self): return len(self.df) def __getitem__(self, idx): path = os.path.join...
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu
Deepfake Detection Challenge
8,684,188
def get_model(CFG, device, num_classes): if CFG['weights'] != 'public': model = timm.create_model(model_name = CFG['backbone'], pretrained = False, in_chans = CFG['channels']) if 'efficient' in CFG['backbone']: model.classifier = nn.Linear(model.classifier.in_features, num_classes) else: model.fc = nn.Linear(model.fc...
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,684,188
cv_start = time.time() gc.collect() all_counter = 0 fold_counter = 0 if not CFG['fold_idx'] else CFG['fold_idx'] all_cnn_preds = None for model_idx in range(len(CFG['models'])) : ImageData = get_dataset(CFGs[model_idx]) test_dataset = ImageData(df = df, path = CFG['data_path'] + 'test/', transform = get_augs(CFGs[mode...
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,684,188
print('Blending fold predictions with: ' + CFG['fold_blend']) for m in CFG['models']: for c in CFG['targets']: class_preds = all_cnn_preds.filter(like = m ).filter(like = c ).columns all_cnn_preds[m + c] = compute_blend(all_cnn_preds, class_preds, CFG['fold_blend'], CFG) all_cnn_preds.drop(class_preds, axis = 1, inpl...
input_size = 224
Deepfake Detection Challenge
8,684,188
for m in CFG['models']: tmp_train_preds = pd.read_csv(m + '/oof.csv') tmp_train_preds.columns = ['StudyInstanceUID'] + CFG['targets'] + ['PatientID', 'fold'] + [m + '' + c for c in CFG['targets']] if m == CFG['models'][0]: train_preds = tmp_train_preds else: train_preds = train_preds.merge(tmp_train_preds[['StudyInsta...
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )
Deepfake Detection Challenge
8,684,188
test_preds = all_cnn_preds.copy() test_preds = pd.concat([df['StudyInstanceUID'], test_preds], axis = 1) test_preds.head()<create_dataframe>
frames_per_video = 10 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,684,188
X = train_preds.copy() X_test = test_preds.copy() drop_features = ['StudyInstanceUID', 'PatientID', 'fold'] + CFG['targets'] features = [f for f in X.columns if f not in drop_features] print(len(features), 'features') display(features )<load_from_csv>
class HisResNeXt(models.resnet.ResNet): def __init__(self, training=True): super(HisResNeXt, 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
8,684,188
folds = pd.read_csv('/kaggle/input/how-to-properly-split-folds/train_folds.csv') del X['fold'] X = X.merge(folds[['StudyInstanceUID', 'fold']], how = 'left', on = 'StudyInstanceUID' )<sort_values>
detection_graph = tf.Graph() with detection_graph.as_default() : od_graph_def = tf.compat.v1.GraphDef() with tf.io.gfile.GFile('.. /input/mobilenet-face/frozen_inference_graph_face.pb', 'rb')as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='' )
Deepfake Detection Challenge
8,684,188
if CFG['sort_targets']: sorted_targets = ['Swan Ganz Catheter Present', 'ETT - Normal', 'ETT - Abnormal', 'ETT - Borderline', 'NGT - Abnormal', 'NGT - Normal', 'NGT - Incompletely Imaged', 'NGT - Borderline', 'CVC - Abnormal', 'CVC - Normal', 'CVC - Borderline']<prepare_x_and_y>
checkpoint = torch.load("/kaggle/input/deepfakes-inference-demo/resnext.pth", map_location=gpu) model = HisResNeXt().to(gpu) model.load_state_dict(checkpoint) _ = model.eval() del checkpoint
Deepfake Detection Challenge
8,684,188
cnn_oof = np.zeros(( len(X), CFG['num_classes'])) lgb_oof = np.zeros(( len(X), CFG['num_classes'])) lgb_tst = np.zeros(( len(X_test), CFG['lgb_folds'], CFG['num_classes'])) all_lgb_preds = None cv_start = time.time() print('-' * 45) print('{:<28}{:<7}{:>5}'.format('Label', 'Model', 'AUC')) print('-' * 45) for label i...
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,684,188
print('Blending fold predictions with: ' + CFG['fold_blend']) for c in CFG['targets']: class_preds = all_lgb_preds.filter(like = c ).columns all_lgb_preds[c] = compute_blend(all_lgb_preds, class_preds, CFG['fold_blend'], CFG) all_lgb_preds.drop(class_preds, axis = 1, inplace = True) all_lgb_preds.head()<define_varia...
cm = detection_graph.as_default() cm.__enter__()
Deepfake Detection Challenge
8,684,188
if CFG['w_public'] > 0: gc.collect() BATCH_SIZE = 96 IMAGE_SIZE = 640 TEST_PATH = '.. /input/ranzcr-clip-catheter-line-classification/test' MODEL_PATH_resnet200d = '.. /input/resnet200d-public/resnet200d_320_CV9632.pth' MODEL_PATH_seresnet152d = '.. /input/seresnet152d-cv9615/seresnet152d_320_CV96.15.pth' class TestDat...
config = tf.compat.v1.ConfigProto() config.gpu_options.allow_growth = True sess=tf.compat.v1.Session(graph=detection_graph, config=config) image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') boxes_tensor = detection_graph.get_tensor_by_name('detection_boxes:0') scores_tensor = detection_graph.get_ten...
Deepfake Detection Challenge
8,684,188
if CFG['w_public'] == 0: df_pub = all_lgb_preds.copy() else: for c in CFG['targets']: class_preds = df_pub.filter(like = c ).columns df_pub[c] = compute_blend(df_pub, class_preds, CFG['model_blend'], CFG, weights = np.array([2/3, 1/3])) df_pub.drop(class_preds, axis = 1, inplace = True) df_pub.head()<categorify>
def get_img(images): global boxes,scores,num_detections im_heights,im_widths=[],[] imgs=[] for image in images: (im_height,im_width)=image.shape[:-1] imgs.append(image) im_heights.append(im_height) im_widths.append(im_widths) imgs=np.array(imgs) (boxes, scores_)= sess.run( [boxes_tensor, scores_tensor], feed_dict=...
Deepfake Detection Challenge
8,684,188
all_preds = all_lgb_preds.copy() all_preds.columns = ['my/' + c for c in all_preds.columns] df_pub.columns = ['public/' + c for c in df_pub.columns] preds = pd.concat([all_preds, df_pub], axis = 1) for c in CFG['targets']: class_preds = preds.filter(like = c ).columns preds[c] = compute_blend(preds, class_preds, CFG['...
res_predictions =[]
Deepfake Detection Challenge
8,684,188
if all_counter == len(CFG['models'] * CFG['num_folds']): for c in CFG['targets']: df[c] = preds[c].rank(pct = True) df.to_csv('submission.csv', index = False) display(df.head() )<install_modules>
for x in tqdm(glob.glob('.. /input/deepfake-detection-challenge/test_videos/*.mp4')) : try: filename=x.replace('.. /input/deepfake-detection-challenge/test_videos/','' ).replace('.mp4','.jpg') a=detect_video(x) y_pred = predict_on_video(x, batch_size=frames_per_video) res_predictions.append(y_pred) if a is None: co...
Deepfake Detection Challenge
8,684,188
!pip install /kaggle/input/kerasapplications -q !pip install /kaggle/input/efficientnet-keras-source-code/ -q --no-deps<import_modules>
bottleneck_EfficientNetB1 = efn.EfficientNetB1(weights=None,include_top=False,pooling='avg') inp=Input(( 10,240,240,3)) x=TimeDistributed(bottleneck_EfficientNetB1 )(inp) x = LSTM(128 )(x) x = Dense(64, activation='elu' )(x) x = Dense(1,activation='sigmoid' )(x) model_EfficientNetB1=Model(inp,x) bottleneck_Xcepti...
Deepfake Detection Challenge
8,684,188
import os, gc import efficientnet.tfkeras as efn import numpy as np import pandas as pd import tensorflow as tf<categorify>
model_EfficientNetB1.load_weights('.. /input/efficientnetb1dfdc/EfficientNetB1-e_2_b_4_f_30-10.h5') model_Xception.load_weights('.. /input/xceptiondfdc/Xception-e_2_b_4_f_30-10.h5' )
Deepfake Detection Challenge
8,684,188
def auto_select_accelerator() : try: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() tf.config.experimental_connect_to_cluster(tpu) tf.tpu.experimental.initialize_tpu_system(tpu) strategy = tf.distribute.experimental.TPUStrategy(tpu) print("Running on TPU:", tpu.master()) except ValueError: strategy = tf....
def get_birghtness(img): return img/img.max() def process_img(img,flip=False): imgs=[] for x in range(10): if flip: imgs.append(get_birghtness(cv2.flip(img[:,x*240:(x+1)*240,:],1))) else: imgs.append(get_birghtness(img[:,x*240:(x+1)*240,:])) return np.array(imgs )
Deepfake Detection Challenge
8,684,188
COMPETITION_NAME = "ranzcr-clip-catheter-line-classification" strategy = auto_select_accelerator() BATCH_SIZE = strategy.num_replicas_in_sync * 16<load_from_csv>
sample_submission = pd.read_csv(".. /input/deepfake-detection-challenge/sample_submission.csv") test_files=glob.glob('./videos/*.jpg') submission=pd.DataFrame() submission['filename']=os.listdir(( '.. /input/deepfake-detection-challenge/test_videos/')) submission['label']=0.5 filenames=[] batch=[] batch1=[] preds=[]
Deepfake Detection Challenge
8,684,188
model_paths = [ '.. /input/ranzcr-last-models/0.952_model_640_47.h5', '.. /input/ranzcr-last-models/0.953_model_616_51.h5', '.. /input/ranzcr-last-models/0.953_model_640_43.h5', '.. /input/ranzcr-last-models/0.954_model_640_42.h5', '.. /input/ranzcr-last-models/0.954_model_632_48.h5', ] subs = [] for model_path in mode...
new_preds=[] for x,y in zip(preds,res_predictions): new_preds.append(x[0]+(0.2*y)) print(sum(new_preds)/len(new_preds))
Deepfake Detection Challenge
8,684,188
submission = pd.concat(subs) submission = submission.groupby('StudyInstanceUID' ).mean() submission.to_csv('submission.csv') submission<install_modules>
for x,y in zip(new_preds,filenames): submission.loc[submission['filename']==y,'label']=x
Deepfake Detection Challenge
8,684,188
<install_modules><EOS>
submission.to_csv('submission.csv', index=False) !rm -r videos
Deepfake Detection Challenge
8,119,370
<SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<install_modules>
%matplotlib inline
Deepfake Detection Challenge
8,119,370
!pip install.. /input/efficientnet-pyotrch/EfficientNet-PyTorch-master/ > /dev/null<install_modules>
test_dir = "/kaggle/input/deepfake-detection-challenge/test_videos/" test_videos = sorted([x for x in os.listdir(test_dir)if x[-4:] == ".mp4"]) frame_h = 5 frame_l = 5 len(test_videos )
Deepfake Detection Challenge
8,119,370
!pip install.. /input/segmentation-models-pytorch/segmentation_models.pytorch-master/ > /dev/null<import_modules>
print("PyTorch version:", torch.__version__) print("CUDA version:", torch.version.cuda) print("cuDNN version:", torch.backends.cudnn.version() )
Deepfake Detection Challenge
8,119,370
class RANZCRDataset(torch.utils.data.Dataset): def __init__( self, df, root, ext, path_col, use_timm_aug=False, transforms=None, augmentations=None, ): super().__init__() df = df.reset_index(drop=True ).copy() self.transforms = transforms self.augmentations = augmentations self.root = root self.use_timm_aug = use_tim...
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu
Deepfake Detection Challenge
8,119,370
EFFNETB6_EMB_DIM = 2304 EFFNETB5_EMB_DIM = 2048 EFFNETB4_EMB_DIM = 1792 EFFNETB3_EMB_DIM = 1536 EFFNETB1_EMB_DIM = 1280 RESNET50_EMB_DIM = 2048 REXNET200_EMB_DIM = 2560 VIT_EMB_DIM = 768 NF_RESNET50_EMB_DIM = 2048 EPS = 1e-6 class TaylorSoftmax(nn.Module): def __init__(self, dim=1, n=2): super(TaylorSoftmax, self ).__i...
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,119,370
def get_validation_models( model_initilizer: Callable, model_config: Mapping[str, Any], model_ckp_dicts: List[OrderedDict], device: str, ): t_models = [] for mcd in model_ckp_dicts: t_model = model_initilizer(**model_config, device=device) t_model.load_state_dict(mcd) t_model = t_model.to(device) t_model.eval() t_...
frames_per_video = 64 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,119,370
%matplotlib inline<define_variables>
input_size = 224
Deepfake Detection Challenge
8,119,370
SKIP_VAL = True<load_from_csv>
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )
Deepfake Detection Challenge
8,119,370
def public_notebook() : device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') BATCH_SIZE = 64 TEST_PATH = '.. /input/ranzcr-clip-catheter-line-classification/test' test = pd.read_csv('.. /input/ranzcr-clip-catheter-line-classification/sample_submission.csv') class TestDataset(Dataset): def __init__(se...
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
8,119,370
<define_variables>
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
8,119,370
RESIZE_SIZE = 640<load_from_csv>
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,119,370
PATH2DIR = '.. /input/ranzcr-clip-catheter-line-classification/' os.listdir(PATH2DIR) train = pd.read_csv(pjoin(PATH2DIR, 'train.csv')) sample_sub = pd.read_csv(pjoin(PATH2DIR, 'sample_submission.csv')) split = np.load('.. /input/ranzcr-models/naive_cv_split.npy', allow_pickle=True )<define_variables>
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,119,370
DEVICE = 'cuda'<load_pretrained>
predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
8,119,370
models_512 = [] ckp_names = glob('.. /input/ranzcr-models/timm_efficientnet_b5_unet_32bs_640res_lesslaugs_ls005_shedchanged_startpoint_difflrs_segbranch_125coefs_1e4noseg_bigholes_firstpseudo_swa_roc_auc_score/timm_efficientnet_b5_unet_32bs_640res_lesslaugs_ls005_shedchanged_startpoint_difflrs_segbranch_125coefs_1e4nos...
submission_df_resnext = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df_resnext.to_csv("submission_resnext.csv", index=False )
Deepfake Detection Challenge
8,119,370
if not SKIP_VAL: val_dfs = [ train.iloc[split[i][1]] for i in range(5) ] val_loaders = create_val_loaders( loader_initilizer=RANZCRDataset, loader_config={ "root":'train_images_512_512', "path_col": "StudyInstanceUID", "ext": ".jpeg", "transforms":T.ToTensor() }, dfs=val_dfs, batch_size=32 ) train_logits = predict_...
!pip install.. /input/deepfake-xception-trained-model/pytorchcv-0.0.55-py2.py3-none-any.whl --quiet
Deepfake Detection Challenge
8,119,370
def predict_test_with_multiple_models( my_models: List[List[torch.nn.Module]], my_loaders: List[torch.utils.data.DataLoader], predict_func: Callable, device: str, ): logits = [] for my_loader in my_loaders: temp_logits = [] for batch in tqdm(my_loader): temp_logits_inner = [] for exp_models in my_models: logit = np.s...
%matplotlib inline warnings.filterwarnings("ignore" )
Deepfake Detection Challenge
8,119,370
INF_BS = 32<create_dataframe>
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,119,370
all_test_loaders_512 = [] test_original = RANZCRDataset(**{ "df":sample_sub, "root":'test_images_512_512', "path_col": "StudyInstanceUID", "ext": ".jpeg", "transforms":T.ToTensor() }) all_test_loaders_512.append(torch.utils.data.DataLoader( test_original, batch_size=INF_BS, drop_last=False, shuffle=False, num_workers...
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" )
Deepfake Detection Challenge
8,119,370
test_logits_512 = predict_test_with_multiple_models( models_512, all_test_loaders_512, cnn_model_predict, DEVICE ) <import_modules>
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,119,370
from scipy.special import expit<compute_test_metric>
frames_per_video = 64 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,119,370
test_logits = expit(test_logits_512 ).mean(0 ).mean(1 )<prepare_x_and_y>
input_size = 150
Deepfake Detection Challenge
8,119,370
my_exp_1 = test_logits[0] my_exp_2 = test_logits[1] my_exp_3 = test_logits[2] my_exp_4 = test_logits[3]<define_variables>
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )
Deepfake Detection Challenge
8,119,370
blend =( my_exp_1**0.5 + my_exp_2**0.5 + my_exp_3**0.5 + my_exp_3**0.5 )<feature_engineering>
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,119,370
sample_sub.iloc[:,1:] = blend sample_sub<count_unique_values>
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,119,370
sample_sub.nunique(axis=0 )<save_to_csv>
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,119,370
!rm -rf test_images_512_512 sample_sub.to_csv('submission.csv', index=False) os.listdir('./' )<define_variables>
%%time model.eval() predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
8,119,370
ROOT = Path.cwd().parent INPUT = ROOT / "input" OUTPUT = ROOT / "output" DATA = INPUT / "ranzcr-clip-catheter-line-classification" TRAIN = DATA / "train" TEST = DATA / "test" TRAINED_MODEL = INPUT/ 'ranzer-models' TMP = ROOT / "tmp" TMP.mkdir(exist_ok=True) RANDAM_SEED = 1086 N_CLASSES = 11 FOLDS = [0, 1, 2, 3, 4] N_F...
submission_df_xception = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df_xception.to_csv("submission_xception.csv", index=False )
Deepfake Detection Challenge
8,119,370
for p in DATA.iterdir() : print(p.name) train = pd.read_csv(DATA / "train.csv") smpl_sub = pd.read_csv(DATA / "sample_submission.csv" )<split>
submission_df = pd.DataFrame({"filename": test_videos} )
Deepfake Detection Challenge
8,119,370
if FAST_COMMIT and len(smpl_sub)== 3582: smpl_sub = smpl_sub.iloc[:64 * 2].reset_index(drop=True )<categorify>
submission_df["label"] = 0.70*submission_df_resnext["label"] + 0.30*submission_df_xception["label"]
Deepfake Detection Challenge
8,119,370
def multi_label_stratified_group_k_fold(label_arr: np.array, gid_arr: np.array, n_fold: int, seed: int=42): np.random.seed(seed) random.seed(seed) start_time = time.time() n_train, n_class = label_arr.shape gid_unique = sorted(set(gid_arr)) n_group = len(gid_unique) gid2aid = dict(zip(gid_unique, range(n_group))) ...
submission_df.to_csv("submission.csv", index=False )
Deepfake Detection Challenge
8,522,656
label_arr = train[CLASSES].values group_id = train.PatientID.values train_val_indexs = list( multi_label_stratified_group_k_fold(label_arr, group_id, N_FOLD, RANDAM_SEED))<feature_engineering>
TEST_DIR = "/kaggle/input/deepfake-detection-challenge/test_videos/" CHECKPOINT = '/kaggle/input/kha-deepfake-dataset/checkpoint_mobilev3_alldata_1903_withfaceforensics_3epochs_.pth' CHECKPOINT2 = '/kaggle/input/kha-deepfake-dataset/cpt_mbn_sqrimg_2503)2epochs_.pth' CHECKPOINT3 = '/kaggle/input/kha-deepfake-dataset/che...
Deepfake Detection Challenge