kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
8,522,656
train["fold"] = -1 for fold_id,(trn_idx, val_idx)in enumerate(train_val_indexs): train.loc[val_idx, "fold"] = fold_id train.groupby("fold")[CLASSES].sum()<train_model>
package_path = '.. /input/kha-efficientnet/EfficientNet-PyTorch/' sys.path.append(package_path)
Deepfake Detection Challenge
8,522,656
def resize_images(img_id, input_dir, output_dir, resize_to=(640, 640), ext="png"): img_path = input_dir / f"{img_id}.jpg" save_path = output_dir / f"{img_id}.{ext}" img = cv2.imread(str(img_path), cv2.IMREAD_GRAYSCALE) img = cv2.resize(img, resize_to) cv2.imwrite(str(save_path), img,) TEST_RESIZED = TMP / "test_{0}x...
%%capture !pip install /kaggle/input/khafacenet/facenet_pytorch-2.2.7-py3-none-any.whl !pip install /kaggle/input/imutils/imutils-0.5.3
Deepfake Detection Challenge
8,522,656
def get_activation(activ_name: str="relu"): act_dict = { "relu": nn.ReLU(inplace=True), "tanh": nn.Tanh() , "sigmoid": nn.Sigmoid() , "identity": nn.Identity() } if activ_name in act_dict: return act_dict[activ_name] else: raise NotImplementedError class Conv2dBNActiv(nn.Module): def __init__( self, in_channels: i...
Deepfake Detection Challenge
8,522,656
class MultiHeadResNet200D(nn.Module): def __init__( self, out_dims_head: tp.List[int]=[3, 4, 3, 1], pretrained=False ): self.base_name = "resnet200d_320" self.n_heads = len(out_dims_head) super(MultiHeadResNet200D, self ).__init__() base_model = timm.create_model( self.base_name, num_classes=sum(out_dims_head), p...
Deepfake Detection Challenge
8,522,656
class LabeledImageDataset(data.Dataset): def __init__( self, file_list: tp.List[ tp.Tuple[tp.Union[str, Path], tp.Union[int, float, np.ndarray]]], transform_list: tp.List[tp.Dict], ): self.file_list = file_list self.transform = ImageTransformForCls(transform_list) def __len__(self): return len(self.file_list) ...
%matplotlib inline device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
Deepfake Detection Challenge
8,522,656
def get_dataloaders_for_inference( file_list: tp.List[tp.List], batch_size=64, ): dataset = LabeledImageDataset( file_list, transform_list=[ ["Normalize", { "always_apply": True, "max_pixel_value": 255.0, "mean": ["0.4887381077884414"], "std": ["0.23064819430546407"]}], ["ToTensorV2", {"always_apply": True}], ]) ...
def conv_bn(inp, oup, stride, conv_layer=nn.Conv2d, norm_layer=nn.BatchNorm2d, nlin_layer=nn.ReLU): return nn.Sequential( conv_layer(inp, oup, 3, stride, 1, bias=False), norm_layer(oup), nlin_layer(inplace=True) ) def conv_1x1_bn(inp, oup, conv_layer=nn.Conv2d, norm_layer=nn.BatchNorm2d, nlin_layer=nn.ReLU): return n...
Deepfake Detection Challenge
8,522,656
class ImageTransformBase: def __init__(self, data_augmentations: tp.List[tp.Tuple[str, tp.Dict]]): augmentations_list = [ self._get_augmentation(aug_name )(**params) for aug_name, params in data_augmentations] self.data_aug = albumentations.Compose(augmentations_list) def __call__(self, pair: tp.Tuple[np.ndarray]...
net = mobilenetv3(mode='small', pretrained=False) net.classifier[1] = torch.nn.Linear(in_features=1280, out_features=1) net = net.to(device) state_dict = torch.load(CHECKPOINT) net.load_state_dict(state_dict) net.cuda() net.eval()
Deepfake Detection Challenge
8,522,656
def load_setting_file(path: str): with open(path)as f: settings = yaml.safe_load(f) return settings def set_random_seed(seed: int = 42, deterministic: bool = False): random.seed(seed) np.random.seed(seed) os.environ["PYTHONHASHSEED"] = str(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backe...
net2 = mobilenetv3(mode='small', pretrained=False) net2.classifier[1] = torch.nn.Linear(in_features=1280, out_features=1) net2 = net2.to(device) state_dict = torch.load(CHECKPOINT2) net2.load_state_dict(state_dict) net2.cuda() net2.eval()
Deepfake Detection Challenge
8,522,656
if not torch.cuda.is_available() : device = torch.device("cpu") else: device = torch.device("cuda") print(device )<load_pretrained>
net3 = EfficientNet.from_name("efficientnet-b0") net3._fc = torch.nn.Linear(in_features=net3._fc.in_features, out_features=1) net3.load_state_dict(torch.load(CHECKPOINT3)) net3.cuda() net3.eval()
Deepfake Detection Challenge
8,522,656
model_dir = TRAINED_MODEL test_dir = TEST_RESIZED test_file_list = [ (test_dir / f"{img_id}.png", [-1] * 11) for img_id in smpl_sub["StudyInstanceUID"].values] test_loader = get_dataloaders_for_inference(test_file_list, batch_size=32) test_preds_arr = np.zeros(( N_FOLD , len(smpl_sub), N_CLASSES)) for fold_id in [0,...
net6 = EfficientNet.from_name("efficientnet-b1") net6._fc = torch.nn.Linear(in_features=net6._fc.in_features, out_features=1) net6.load_state_dict(torch.load(CHECKPOINT6)) net6.cuda() net6.eval()
Deepfake Detection Challenge
8,522,656
if CONVERT_TO_RANK: test_preds_arr = test_preds_arr.argsort(axis=1 ).argsort(axis=1) sub = smpl_sub.copy() sub[CLASSES] = test_preds_arr.mean(axis=0) sub.to_csv("submission.csv", index=False )<load_pretrained>
class SeparableConv2d(nn.Module): def __init__(self,in_channels,out_channels,kernel_size=1,stride=1,padding=0,dilation=1,bias=False): super(SeparableConv2d,self ).__init__() self.conv1 = nn.Conv2d(in_channels,in_channels,kernel_size,stride,padding,dilation,groups=in_channels,bias=bias) self.pointwise = nn.Conv2d(in_ch...
Deepfake Detection Challenge
8,522,656
model_dir = TRAINED_MODEL test_dir = TEST_RESIZED test_file_list = [ (test_dir / f"{img_id}.png", [-1] * 11) for img_id in smpl_sub["StudyInstanceUID"].values] test_loader = get_dataloaders_for_inference(test_file_list, batch_size=4) N_FOLD = len([1024]) test_preds_arr = np.zeros(( N_FOLD , len(smpl_sub), N_CLASSES...
class MaxPoolPad(nn.Module): def __init__(self): super(MaxPoolPad, self ).__init__() self.pad = nn.ZeroPad2d(( 1, 0, 1, 0)) self.pool = nn.MaxPool2d(3, stride=2, padding=1) def forward(self, x): x = self.pad(x) x = self.pool(x) x = x[:, :, 1:, 1:].contiguous() return x class AvgPoolPad(nn.Module): def __init__(self,...
Deepfake Detection Challenge
8,522,656
sub_2 = smpl_sub.copy() sub_2[CLASSES] = test_preds_arr.mean(axis=0 )<feature_engineering>
class CFG: seq_len=10 lstm_in = 16 lstm_out = 16 class LSTM_Model(nn.Module): def __init__(self): super(LSTM_Model, self ).__init__() self.cnn_net = mobilenetv3(mode='small', pretrained=False) self.cnn_net.classifier[1] = nn.Linear(in_features=1280, out_features=1) self.cnn_net.classifier[1] = nn.Linear(in_features=1...
Deepfake Detection Challenge
8,522,656
sub[CLASSES] = 0.6 * sub[CLASSES] + 0.4 * sub_2[CLASSES]<save_to_csv>
Deepfake Detection Challenge
8,522,656
sub.to_csv("submission.csv", index=False )<import_modules>
net11 = torchvision.models.resnet18(pretrained=False) net11.fc = nn.Linear(in_features=512, out_features=1, bias=True) net11.load_state_dict(torch.load(CHECKPOINT11)) net11 = net11.to(device) net11.cuda() net11.eval()
Deepfake Detection Challenge
8,522,656
import pandas as pd from IPython.display import display from sklearn.feature_selection import VarianceThreshold from sklearn.ensemble import ExtraTreesClassifier from sklearn import svm from sklearn import preprocessing from sklearn.model_selection import train_test_split from sklearn.metrics import roc_auc_score, mean...
import albumentations from albumentations.augmentations.transforms import ShiftScaleRotate, HorizontalFlip, RandomBrightnessContrast, MotionBlur, Blur, GaussNoise, JpegCompression
Deepfake Detection Challenge
8,522,656
types = {'ID':np.uint32, 'target':np.uint8, 'VAR_0002':np.uint16, 'VAR_0003':np.uint16, 'VAR_0532':np.uint8, 'VAR_0533':np.uint8, 'VAR_0534':np.uint8, 'VAR_0535':np.uint8, 'VAR_0536':np.uint8, 'VAR_0537':np.uint8,'VAR_0538':np.uint8, 'VAR_0539':np.uint8, 'VAR_0540':np.uint8, 'VAR_0545':np.uint16, 'VAR_0546':np.uint16, ...
def predict_on_video(model, model2, model3, model4, model5, model6, model7, model8, model9, model10, model11, video_path): try: x, x_sqr, x_299_sqr, x_lstm, frame_skip = extract_frames(video_path) if x is None or x_sqr is None: return 0.5 else: with torch.no_grad() : y_pred = model(x.to(device)) y_pred = torch.sigmoid...
Deepfake Detection Challenge
8,522,656
train = pd.read_csv(".. /input/springleaf-marketing-response/train.csv.zip") mixCol = [8,9,10,11,12,18,19,20,21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 38, 39, 40, 41, 42, 43, 44, 45, 73, 74, 98, 99, 100, 106, 107, 108, 156, 157, 158, 159, 166, 167, 168, 169, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186,...
class FastMTCNN(object): def __init__(self, resize=1, *args, **kwargs): self.resize = resize self.mtcnn = MTCNN(*args, **kwargs) def __call__(self, frames): if self.resize != 1: frames = [f.resize([int(d * self.resize)for d in f.size])for f in frames] boxes, probs = self.mtcnn.detect(frames) boxes = [b.astype(int ).t...
Deepfake Detection Challenge
8,522,656
nrows = 500 trainData = pd.read_csv(".. /input/springleaf-marketing-response/train.csv.zip", skiprows=[107], usecols=strColName, nrows=nrows, dtype=types) label = pd.read_csv(".. /input/springleaf-marketing-response/train.csv.zip", skiprows=[107], usecols=['target'], nrows=nrows) testData = pd.read_csv(".. /input/spr...
test_videos = sorted([x for x in os.listdir(TEST_DIR)if x[-4:] == ".mp4"]) len(test_videos )
Deepfake Detection Challenge
8,522,656
clf = svm.SVC(C=1.0, kernel='linear', degree=10, gamma=1.00, coef0=0.0, shrinking=True, probability=False, tol=0.001, cache_size=1000, class_weight=None, verbose=False, max_iter=-1, random_state=None) clf.fit(X_train, y_train) predictions = clf.predict(X_test) print('roc_auc_score', roc_auc_score(y_test, predictions...
def predict_on_video_set(model, model2, model3, model4, model5, model6, model7, model8, model9, model10, model11, videos, num_workers): def process_file(i): filename = videos[i] y_pred = predict_on_video(model, model2, model3, model4, model5, model6, model7, model8, model9, model10, model11, os.path.join(TEST_DIR, file...
Deepfake Detection Challenge
8,522,656
testData = pd.read_csv(".. /input/springleaf-marketing-response/test.csv.zip", usecols=strColName, engine='python', dtype=types) numericFeatures = testData._get_numeric_data() removeNA = numericFeatures.fillna(0) features = sel.transform(removeNA) y = np.array(label ).ravel() X_scaled = preprocessing.scale(features)...
predictions = np.clip(predictions, 0.005, 0.995) submission_df = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df.to_csv("submission.csv", index=False )
Deepfake Detection Challenge
8,681,162
predictions = clf.predict(X_norm )<load_from_csv>
import random import re from copy import deepcopy from typing import Union, List, Tuple, Optional, Callable from collections import OrderedDict, defaultdict import math import cv2 import torch import torch.nn as nn from torch.utils.data import Dataset,DataLoader from torch.utils.data.sampler import SequentialSampler, R...
Deepfake Detection Challenge
8,681,162
df_submit = pd.read_csv('.. /input/springleaf-marketing-response/sample_submission.csv.zip') df_submit['target'] = predictions<save_to_csv>
TARGET_H, TARGET_W = 224, 224 FRAMES_PER_VIDEO = 30 TEST_VIDEOS_PATH = '.. /input/deepfake-detection-challenge/test_videos' NN_MODEL_PATHS = [ '.. /input/kdold-deepfake-effb2/fold0-effb2-000epoch.pt', '.. /input/kdold-deepfake-effb2/fold0-effb2-001epoch.pt', '.. /input/kdold-deepfake-effb2/fold0-effb2-002epoch.pt', '.....
Deepfake Detection Challenge
8,681,162
df_submit.to_csv('submission.csv', index=False )<set_options>
SEED = 42 def seed_everything(seed): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = False torch.backends.cudnn.benchmark = True seed_everything(SEED )
Deepfake Detection Challenge
8,681,162
%matplotlib inline<import_modules>
!pip install.. /input/pytorchefficientnet/EfficientNet-PyTorch-master > /dev/null def get_net() : net = EfficientNet.from_name('efficientnet-b2') net._fc = nn.Linear(in_features=net._fc.in_features, out_features=2, bias=True) return net
Deepfake Detection Challenge
8,681,162
from xgboost import XGBRegressor from sklearn.kernel_ridge import KernelRidge from sklearn.model_selection import GridSearchCV from sklearn.feature_selection import RFECV from sklearn.preprocessing import StandardScaler from sklearn.metrics import mean_squared_error, make_scorer from mlxtend.preprocessing import minmax...
class DatasetRetriever(Dataset): def __init__(self, df): self.video_paths = df['video_path'] self.filenames = df.index self.face_dr = FaceDetector(frames_per_video=FRAMES_PER_VIDEO) mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] self.normalize_transform = Normalize(mean, std) self.video_reader = VideoReader...
Deepfake Detection Challenge
8,681,162
warnings.filterwarnings("ignore" )<count_unique_values>
class DeepFakePredictor: def __init__(self): self.models = [self.prepare_model(get_net() , path)for path in NN_MODEL_PATHS] self.models_count = len(self.models) def predict(self, dataset): result = [] with torch.no_grad() : for filename, video in dataset: video = video.to(self.device, dtype=torch.float32) try: label ...
Deepfake Detection Challenge
8,681,162
def show_uniqs(cols): for col in cols: print(col) show_uniq(col) print('=======================================' )<load_from_csv>
deep_fake_predictor = DeepFakePredictor()
Deepfake Detection Challenge
8,681,162
train = pd.read_csv('/kaggle/input/house-prices-advanced-regression-techniques/train.csv' )<count_missing_values>
def process_dfs(df, num_workers=2): def process_df(sub_df): dataset = DatasetRetriever(sub_df) result = deep_fake_predictor.predict(dataset) return result with ThreadPoolExecutor(max_workers=num_workers)as ex: results = ex.map(process_df, np.split(df, num_workers)) return results
Deepfake Detection Challenge
8,681,162
<define_variables><EOS>
result.to_csv('submission.csv' )
Deepfake Detection Challenge
8,236,131
<SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<load_from_csv>
!pip install.. /input/pytorchcv/pytorchcv-0.0.55-py2.py3-none-any.whl --quiet
Deepfake Detection Challenge
8,236,131
test = pd.read_csv('/kaggle/input/house-prices-advanced-regression-techniques/test.csv' )<count_missing_values>
device = 'cuda' if torch.cuda.is_available() else 'cpu'
Deepfake Detection Challenge
8,236,131
count_empty_columns_test = test[empty_columns_test].isnull().sum(axis = 0) count_empty_columns_test<define_variables>
def gem(x, p=3, eps=1e-6): return F.avg_pool2d(x.clamp(min=eps ).pow(p),(x.size(-2), x.size(-1)) ).pow(1./p) class GeM(nn.Module): def __init__(self, p=3, eps=1e-6): super(GeM,self ).__init__() self.p = Parameter(torch.ones(1)*p) self.eps = eps def forward(self, x): return gem(x, p=self.p, eps=self.eps) def __repr__...
Deepfake Detection Challenge
8,236,131
for col in count_empty_columns_test.index: if col not in count_empty_columns_train: print(col )<define_variables>
Deepfake Detection Challenge
8,236,131
garage_colums = [] regexp = re.compile(r"([-a-zA-Z]+)?"+r"Garage"+r"([-a-zA-Z]+)?") for col in train.columns: if regexp.search(col): garage_colums.append(col) garage_colums = np.array(garage_colums) garage_colums<data_type_conversions>
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )
Deepfake Detection Challenge
8,236,131
for col in garage_num_cols: train[col] = train[col].fillna(0) test[col] = test[col].fillna(0 )<count_unique_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,236,131
<define_variables><EOS>
probs = np.asarray(probs) probs[probs!=probs] = 0.5 plt.hist(probs, 40) filenames = [os.path.basename(f)for f in filenames] submission = pd.DataFrame({'filename': filenames, 'label': probs}) submission.to_csv('submission.csv', index=False) submission
Deepfake Detection Challenge
8,474,447
<SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<data_type_conversions>
from fastai.vision import *
Deepfake Detection Challenge
8,474,447
for col in basement_num_cols: train[col] = train[col].fillna(0) test[col] = test[col].fillna(0 )<define_variables>
train_sample_metadata = pd.read_json('.. /input/deepfake-detection-challenge/train_sample_videos/metadata.json' ).T.reset_index() train_sample_metadata.columns = ['fname','label','split','original'] train_sample_metadata.head()
Deepfake Detection Challenge
8,474,447
masvnr_colums = [] regexp = re.compile(r"([-a-zA-Z]+)?"+r"MasVnr"+r"([-a-zA-Z]+)?") for col in train.columns: if regexp.search(col): masvnr_colums.append(col) masvnr_colums = np.array(masvnr_colums) masvnr_colums<filter>
fake_sample_df = train_sample_metadata[train_sample_metadata.label == 'FAKE'] real_sample_df = train_sample_metadata[train_sample_metadata.label == 'REAL']
Deepfake Detection Challenge
8,474,447
all(train.loc[train['MasVnrArea'].isnull() ].index == train.loc[train['MasVnrType'].isnull() ].index )<data_type_conversions>
train_dir = Path('/kaggle/input/deepfake-detection-challenge/train_sample_videos/') test_dir = Path('/kaggle/input/deepfake-detection-challenge/test_videos/') train_video_files = get_files(train_dir, extensions=['.mp4']) test_video_files = get_files(test_dir, extensions=['.mp4'] )
Deepfake Detection Challenge
8,474,447
train['MasVnrArea'] = train['MasVnrArea'].fillna(0) test['MasVnrArea'] = test['MasVnrArea'].fillna(0 )<data_type_conversions>
dummy_video_file = train_video_files[0]
Deepfake Detection Challenge
8,474,447
train['MasVnrType'] = train['MasVnrType'].fillna('None') test['MasVnrType'] = test['MasVnrType'].fillna('None' )<define_variables>
sys.path.insert(0,'/kaggle/working/reader/python') set_bridge('torch') device = torch.device("cuda" )
Deepfake Detection Challenge
8,474,447
pool_colums = [] regexp = re.compile(r"([-a-zA-Z]+)?"+r"Pool"+r"([-a-zA-Z]+)?") for col in train.columns: if regexp.search(col): pool_colums.append(col) pool_colums = np.array(pool_colums) pool_colums<data_type_conversions>
retinaface_stats = tensor([123,117,104] ).to(device) def decord_cpu_video_reader(path, freq=None): video = VideoReader(str(path), ctx=cpu()) len_video = len(video) if freq: t = video.get_batch(range(0, len(video), freq)).permute(0,3,1,2) else: t = video.get_batch(range(len_video)) return t, len_video def get_decord...
Deepfake Detection Challenge
8,474,447
train['PoolQC'] = train['PoolQC'].fillna('NA') test['PoolQC'] = test['PoolQC'].fillna('NA' )<data_type_conversions>
sys.path.insert(0,"/kaggle/input/retina-face-2/Pytorch_Retinaface_2/" )
Deepfake Detection Challenge
8,474,447
train['Alley'] = train['Alley'].fillna('NA') test['Alley'] = test['Alley'].fillna('NA' )<define_variables>
import os import torch import torch.backends.cudnn as cudnn import numpy as np from data import cfg_mnet, cfg_re50 from layers.functions.prior_box import PriorBox from utils.nms.py_cpu_nms import py_cpu_nms import cv2 from models.retinaface import RetinaFace from utils.box_utils import decode, decode_landm import time
Deepfake Detection Challenge
8,474,447
fireplace_colums = [] regexp = re.compile(r"([-a-zA-Z]+)?"+r"Fireplace"+r"([-a-zA-Z]+)?") for col in train.columns: if regexp.search(col): fireplace_colums.append(col) fireplace_colums = np.array(fireplace_colums) fireplace_colums<data_type_conversions>
def check_keys(model, pretrained_state_dict): ckpt_keys = set(pretrained_state_dict.keys()) model_keys = set(model.state_dict().keys()) used_pretrained_keys = model_keys & ckpt_keys unused_pretrained_keys = ckpt_keys - model_keys missing_keys = model_keys - ckpt_keys print('Missing keys:{}'.format(len(missing_keys)))...
Deepfake Detection Challenge
8,474,447
train['FireplaceQu'] = train['FireplaceQu'].fillna('NA') test['FireplaceQu'] = test['FireplaceQu'].fillna('NA' )<data_type_conversions>
cudnn.benchmark = True
Deepfake Detection Challenge
8,474,447
train['Fence'] = train['Fence'].fillna('NA') test['Fence'] = test['Fence'].fillna('NA' )<define_variables>
def get_model(modelname="mobilenet"): torch.set_grad_enabled(False) cfg = None cfg_mnet['pretrain'] = False cfg_re50['pretrain'] = False if modelname == "mobilenet": pretrained_path = ".. /input/retina-face-2/Pytorch_Retinaface_2/weights/mobilenet0.25_Final.pth" cfg = cfg_mnet if modelname == "resnet50": pretrained_pa...
Deepfake Detection Challenge
8,474,447
misc_colums = [] regexp = re.compile(r"([-a-zA-Z]+)?"+r"Misc"+r"([-a-zA-Z]+)?") for col in train.columns: if regexp.search(col): misc_colums.append(col) misc_colums = np.array(misc_colums) misc_colums<data_type_conversions>
def predict(model, t, sz, cfg, confidence_threshold = 0.5, top_k = 5, nms_threshold = 0.5, keep_top_k = 5): "get prediction for a batch t by model with image sz" resize = 1 scale_rate = 1 im_height, im_width = sz, sz scale = torch.Tensor([sz, sz, sz, sz]) scale = scale.to(device) locs, confs, landmss = torch.Tensor([...
Deepfake Detection Challenge
8,474,447
train['MiscFeature'] = train['MiscFeature'].fillna('NA') test['MiscFeature'] = test['MiscFeature'].fillna('NA' )<drop_column>
%%time model, cfg = get_model("mobilenet" )
Deepfake Detection Challenge
8,474,447
train = train.drop(train.loc[train['Electrical'].isnull() ].index )<feature_engineering>
def bboxes_to_original_scale(bboxes, H, W, sz): res = [] for bb in bboxes: h_scale, w_scale = H/sz, W/sz orig_bboxes =(bb*array([w_scale, h_scale, w_scale, h_scale])[None,...] ).astype(int) res.append(orig_bboxes) return res
Deepfake Detection Challenge
8,474,447
for i in test['Neighborhood'].unique() : if test.MSZoning[test['Neighborhood'] == i].isnull().sum() > 0: test.loc[test['Neighborhood'] == i,'MSZoning'] = \ test.loc[test['Neighborhood'] == i,'MSZoning'].fillna(test.loc[test['Neighborhood'] == i,'MSZoning'].mode() [0] )<data_type_conversions>
def landmarks_to_original_scale(landmarks, H, W, sz): res = [] for landms in landmarks: h_scale, w_scale = H/sz, W/sz orig_landms =(landms*array([w_scale, h_scale]*5)[None,...] ).astype(int) res.append(orig_landms) return res
Deepfake Detection Challenge
8,474,447
train['LotFrontage'].fillna(train['LotFrontage'].median() , inplace=True) test['LotFrontage'].fillna(test['LotFrontage'].median() , inplace=True )<prepare_x_and_y>
from tqdm import tqdm
Deepfake Detection Challenge
8,474,447
y_train = train['SalePrice'] train = train.drop('SalePrice',axis=1) train = train.drop('Id',axis=1 )<drop_column>
freq = 5 model_args = dict(confidence_threshold = 0.5, top_k = 5, nms_threshold = 0.5, keep_top_k = 5) sz = cfg['image_size'] imgnet_stats = [tensor(o)for o in imagenet_stats] rescale_param = 1.3
Deepfake Detection Challenge
8,474,447
test_id = test['Id'] test = test.drop('Id', axis=1 )<concatenate>
!pip install -q.. /input/efficientnetpytorchpip/efficientnet_pytorch-0.6.3/
Deepfake Detection Challenge
8,474,447
df = train.append(test )<categorify>
from fastai.vision.models.efficientnet import *
Deepfake Detection Challenge
8,474,447
df['GarageCond'] = df['GarageCond'].map({'NA':0, 'Po':1, 'Fa':2, 'TA':3, 'Gd':4, 'Ex':5}) df['GarageQual'] = df['GarageQual'].map({'NA':0, 'Po':1, 'Fa':2, 'TA':3, 'Gd':4, 'Ex':5}) df['BsmtCond'] = df['BsmtCond'].map({'NA':0, 'Po':1, 'Fa':2, 'TA':3, 'Gd':4, 'Ex':5}) df['BsmtExposure'] = df['BsmtExposure'].map({'NA':0...
class DummyDatabunch: c = 2 path = '.' device = defaults.device loss_func = None data = DummyDatabunch()
Deepfake Detection Challenge
8,474,447
df = df.reset_index() df = df.drop('index',axis = 1 )<filter>
effnet_model = EfficientNet.from_name("efficientnet-b5", override_params={'num_classes': 2}) learner = Learner(data, effnet_model); learner.model_dir = '.' learner.load('.. /input/deepfakerandmergeaugmodels/single_frame_effnetb5_randmerge') effnetb5_inference_model = learner.model.eval()
Deepfake Detection Challenge
8,474,447
drop_id = df[df['LotArea'] > 100000].index<drop_column>
effnet_model = EfficientNet.from_name("efficientnet-b7", override_params={'num_classes': 2}) learner = Learner(data, effnet_model); learner.model_dir = '.' learner.load('.. /input/deepfakerandmergeaugmodels/single_frame_effnetb7_randmerge_fp16') effnetb7_inference_model = learner.model.float().eval()
Deepfake Detection Challenge
8,474,447
drop_id = drop_id[drop_id < 1459]<feature_engineering>
learner = cnn_learner(data, models.resnet34, pretrained=False); learner.model_dir = '.' learner.load('.. /input/deepfakerandmergeaugmodels/single_frame_resnet34_randmerge') resnet_inference_model = learner.model.eval()
Deepfake Detection Challenge
8,474,447
df['MasVnrArea'][df[df['MasVnrArea'] > 1500].index] = df['MasVnrArea'].mean() df['Utilities'][df[df['Utilities']==2].index] = df['Utilities'].mean()<drop_column>
predictions = [] video_fnames = []
Deepfake Detection Challenge
8,474,447
df = df.drop(drop_id )<drop_column>
fname2pred = dict(zip(video_fnames, predictions))
Deepfake Detection Challenge
8,474,447
y_train = y_train.drop(drop_id )<categorify>
submission_df = pd.read_csv("/kaggle/input/deepfake-detection-challenge/sample_submission.csv" )
Deepfake Detection Challenge
8,474,447
dummy_drop = [] for i in cat_columns: dummy_drop += [ i+'_'+str(df[i].unique() [-1])] df = pd.get_dummies(df,columns=cat_columns) df = df.drop(dummy_drop,axis=1 )<normalization>
submission_df.label = submission_df.filename.map(fname2pred )
Deepfake Detection Challenge
8,474,447
X_train = df[:-1459].drop(['index'], axis=1) X_test = df[-1459:].drop(['index'], axis=1) scaler = StandardScaler() X_train[num_columns]= scaler.fit_transform(X_train[num_columns]) X_test[num_columns]= scaler.transform(X_test[num_columns]) X_train.shape, X_test.shape<feature_engineering>
submission_df['label'] = np.clip(submission_df['label'], 0.01, 0.99 )
Deepfake Detection Challenge
8,474,447
<train_model><EOS>
submission_df.to_csv("submission.csv",index=False )
Deepfake Detection Challenge
8,212,093
<SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<train_on_grid>
%matplotlib inline
Deepfake Detection Challenge
8,212,093
ans = {} for i in range(1, 222): imp_col = imp_feature.iloc[:i].index ridge = KernelRidge(alpha = 0.5263157894736842, coef0 = 3.5, degree = 2, kernel ='polynomial') ridge = ridge.fit(X_train[imp_col], y_train_log) ans[i] = np.sqrt(mean_squared_error(y_train_log,ridge.predict(X_train[imp_col])) )<define_variables>
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,212,093
minimum = ans[1] ind_min = 1 for ind in range(1,len(ans.values())) : if ans[ind] < minimum: minimum = ans[ind] ind_min = ind<features_selection>
print("PyTorch version:", torch.__version__) print("CUDA version:", torch.version.cuda) print("cuDNN version:", torch.backends.cudnn.version() )
Deepfake Detection Challenge
8,212,093
imp_col = imp_feature.iloc[:ind_min+1].index<compute_test_metric>
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu
Deepfake Detection Challenge
8,212,093
def neg_rmse(y_true, y_pred): return -1.0*np.sqrt(mean_squared_error(y_true,y_pred)) neg_rmse = make_scorer(neg_rmse )<train_model>
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,212,093
model = KernelRidge(alpha = 0.6842105263157894, coef0 = 3.5, degree = 2, kernel = 'polynomial') model.fit(X_train[imp_col], y_train_log) print("RMSE of the whole training set: {}".format(np.sqrt(mean_squared_error(y_train_log,model.predict(X_train[imp_col])))) )<predict_on_test>
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
8,212,093
y_pred = np.exp(model.predict(X_test[imp_col]))<save_to_csv>
input_size = 224
Deepfake Detection Challenge
8,212,093
def save_ans(ans, pasanger_id, name_alg): submission = pd.DataFrame({'Id':pasanger_id,'SalePrice':ans}) print(submission.shape) filename = r'./{}.csv'.format(name_alg) submission.to_csv(filename,index=False) print('Saved file: ' + filename )<compute_test_metric>
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )
Deepfake Detection Challenge
8,212,093
save_ans(y_pred, test_id,'submission' )<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
8,212,093
train_df = pd.read_csv('.. /input/house-prices-advanced-regression-techniques/train.csv') test_df = pd.read_csv('.. /input/house-prices-advanced-regression-techniques/test.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
8,212,093
def preprocessing_null(data_df): data_df.drop(['Alley', 'PoolQC', 'Fence', 'MiscFeature', 'Id'], axis=1, inplace=True) Bsmtlist = ['BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2'] Bsmtlist2=['BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF'] Garagelist = ['GarageType', 'GarageFinish', 'GarageQual', 'Garag...
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,212,093
train_target = train_df['SalePrice'] train_feature = train_df.drop('SalePrice', axis=1 )<categorify>
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,212,093
train_feature = preprocessing_null(train_feature) test_feature = preprocessing_null(test_df )<set_options>
speed_test = False
Deepfake Detection Challenge
8,212,093
%matplotlib inline<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,212,093
pd.set_option('display.max_columns', 500) corr[corr>0.7]<drop_column>
predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
8,212,093
<split><EOS>
submission_df = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df.to_csv("submission.csv", index=False )
Deepfake Detection Challenge
8,069,381
<SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<split>
%matplotlib inline
Deepfake Detection Challenge
8,069,381
train_feature_num, train_feature_obj = split_num_obj(train_feature) test_feature_num, test_feature_obj = split_num_obj(test_feature )<categorify>
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,069,381
train_dummies = pd.get_dummies(train_feature_obj) test_dummies = pd.get_dummies(test_feature_obj) not_in_train = [column for column in train_dummies.columns if column not in test_dummies.columns] not_in_test = [column for column in test_dummies.columns if column not in train_dummies.columns] print(' ',train_dummies.s...
print("PyTorch version:", torch.__version__) print("CUDA version:", torch.version.cuda) print("cuDNN version:", torch.backends.cudnn.version() )
Deepfake Detection Challenge
8,069,381
df_num_cat_col = df_num_col[[0, 3, 4, 15, 16, 17, 18, 19, 20, 21, 22, 28, 29, 30, 31]]<split>
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu
Deepfake Detection Challenge
8,069,381
def split_num_cat(data_df_num): data_df_num_cat = data_df_num[df_num_cat_col] data_df_num_non_cat = data_df_num.drop(df_num_cat_col, axis=1) return data_df_num_cat, data_df_num_non_cat train_feature_num_cat, train_feature_num_non_cat = split_num_cat(train_feature_num) test_feature_num_cat, test_feature_num_non_cat = ...
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,069,381
all_data = pd.concat(( train_df, test_df)).reset_index(drop=True) all_data.drop('SalePrice', axis=1, inplace=True) print(all_data.shape) all_data = preprocessing_null(all_data) all_data = drop_corr_ftr(all_data) print(all_data.shape) all_data_num, all_data_obj = split_num_obj(all_data) print(all_data_obj.shape )...
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,069,381
warnings.filterwarnings(action='ignore') label = LabelEncoder() for col in all_data_obj.columns: label.fit(all_data_obj.loc[:, col]) train_feature_obj.loc[:, col] = label.transform(train_feature_obj.loc[:, col]) test_feature_obj.loc[:, col] = label.transform(test_feature_obj.loc[:, col] )<feature_engineering>
input_size = 224
Deepfake Detection Challenge
8,069,381
train_target = np.log1p(train_target) train_feature_num_non_cat = np.log1p(train_feature_num_non_cat) test_feature_num_non_cat = np.log1p(test_feature_num_non_cat )<concatenate>
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )
Deepfake Detection Challenge
8,069,381
train_feature_fin = pd.concat([train_feature_num_cat, train_feature_num_non_cat, train_feature_obj], axis=1) test_feature_fin = pd.concat([test_feature_num_cat, test_feature_num_non_cat, test_feature_obj], axis=1 )<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
8,069,381
cond1 = train_target>500000 cond2 = train_feature_num_non_cat['GrLivArea']>4000<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
8,069,381
train_feature_fin = train_feature_fin.drop(train_feature_num_non_cat[cond1|cond2].index, axis=0 )<train_on_grid>
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,069,381
def get_best_estimator(model, params): grid_model = GridSearchCV(model, param_grid=params, scoring="neg_mean_squared_error", cv=5) grid_model.fit(train_feature_fin, train_target) rmse = np.sqrt(-1*grid_model.best_score_) print('{0}, param:{1}, rmse:{2}'.format(model.__class__.__name__, grid_model.best_params_,\ np.r...
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,069,381
lgbm_params = { 'max_depth':[5, 10, 15, 20, 25, 30], 'learning_rate':[0.01, 0.05, 0.1, 0.5, 1], } lgbm_reg = LGBMRegressor(n_estimators=1000) lgbm_be = get_best_estimator(lgbm_reg, lgbm_params )<predict_on_test>
predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
8,069,381
preds = np.expm1(lgbm_be.predict(test_feature_fin))<save_to_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,069,381
test=pd.read_csv('.. /input/house-prices-advanced-regression-techniques/test.csv') my_submission = pd.DataFrame({'Id': test.Id, 'SalePrice': preds}) my_submission.to_csv('submission.csv', index=False )<load_from_csv>
!pip install.. /input/deepfake-xception-trained-model/pytorchcv-0.0.55-py2.py3-none-any.whl --quiet
Deepfake Detection Challenge
8,069,381
train=pd.read_csv('/kaggle/input/house-prices-advanced-regression-techniques/train.csv',index_col=0) test=pd.read_csv('/kaggle/input/house-prices-advanced-regression-techniques/test.csv',index_col=0) submission=pd.read_csv('/kaggle/input/house-prices-advanced-regression-techniques/sample_submission.csv') Id_test = p...
%matplotlib inline warnings.filterwarnings("ignore" )
Deepfake Detection Challenge
8,069,381
%matplotlib inline <drop_column>
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