kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
8,546,370
columns = [col for col in train.columns.to_list() if col not in ['id','target']]<prepare_x_and_y>
print("PyTorch version:", torch.__version__) print("CUDA version:", torch.version.cuda) print("cuDNN version:", torch.backends.cudnn.version() )
Deepfake Detection Challenge
8,546,370
data=train[columns] target=train['target']<split>
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu
Deepfake Detection Challenge
8,546,370
def objective(trial,data=data,target=target): train_x, test_x, train_y, test_y = train_test_split(data, target, test_size=0.15,random_state=42) param = { 'tree_method':'gpu_hist', 'lambda': trial.suggest_loguniform('lambda', 1e-3, 10.0), 'alpha': trial.suggest_loguniform('alpha', 1e-3, 10.0), 'colsample_bytree': trial...
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,546,370
Best_trial= {'lambda': 0.0042687338951820425, 'alpha': 6.2637008222060935, 'colsample_bytree': 0.4, 'subsample': 0.6, 'n_estimators': 4000, 'learning_rate': 0.01, 'max_depth': 11, 'random_state': 2020, 'min_child_weight': 171, 'tree_method':'gpu_hist' }<train_model>
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,546,370
preds = np.zeros(test.shape[0]) kf = KFold(n_splits=5,random_state=48,shuffle=True) rmse=[] models = [] n=0 for trn_idx, test_idx in kf.split(train[columns],train['target']): X_tr,X_val=train[columns].iloc[trn_idx],train[columns].iloc[test_idx] y_tr,y_val=train['target'].iloc[trn_idx],train['target'].iloc[test_idx] m...
input_size = 224
Deepfake Detection Challenge
8,546,370
sub['target']=preds sub.to_csv('submission.csv', index=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,546,370
import matplotlib.pyplot as plt<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,546,370
train_df = pd.read_csv("/kaggle/input/tabular-playground-series-jan-2021/train.csv", index_col=["id"]) test_df = pd.read_csv("/kaggle/input/tabular-playground-series-jan-2021/test.csv", index_col=["id"]) X = train_df.iloc[:, :-1].to_numpy() y = train_df.iloc[:, -1].to_numpy() X_test = test_df.to_numpy()<train_model>
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,546,370
def train(model): X_train, X_test, y_train, y_test = train_test_split(X, y.flatten() , test_size=0.1, random_state=156) y_train = y_train.reshape(-1, 1) y_test = y_test.reshape(-1, 1) model = model.fit(X_train, y_train, early_stopping_rounds=100, verbose=False, eval_set=[(X_test, y_test)]) score = mean_squared_erro...
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,546,370
def objectiveXGB(trial: Trial, X, y, test): param = { "n_estimators" : trial.suggest_int('n_estimators', 500, 4000), 'max_depth':trial.suggest_int('max_depth', 8, 16), 'min_child_weight':trial.suggest_int('min_child_weight', 1, 300), 'gamma':trial.suggest_int('gamma', 1, 3), 'learning_rate': 0.01, 'colsample_bytree':tr...
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,546,370
study = optuna.create_study(direction='minimize',sampler=TPESampler()) study.optimize(lambda trial : objectiveXGB(trial, X, y, X_test), n_trials=50) print('Best trial: score {}, params {}'.format(study.best_trial.value,study.best_trial.params)) best_param = study.best_trial.params xgbReg = train(xgb.XGBRegressor(**be...
predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
8,546,370
def objectiveLGBM(trial: Trial, X, y, test): param = { 'objective': 'regression', 'metric': 'root_mean_squared_error', 'verbosity': -1, 'boosting_type': 'gbdt', 'lambda_l1': trial.suggest_loguniform('lambda_l1', 1e-8, 10.0), 'lambda_l2': trial.suggest_loguniform('lambda_l2', 1e-8, 10.0), 'num_leaves': trial.suggest_int...
submission_df_resnext = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df_resnext.to_csv("submission_resnext.csv", index=False )
Deepfake Detection Challenge
8,546,370
study = optuna.create_study(direction='minimize',sampler=TPESampler()) study.optimize(lambda trial : objectiveLGBM(trial, X, y, X_test), n_trials=20) print('Best trial: score {}, params {}'.format(study.best_trial.value,study.best_trial.params)) best_param2 = study.best_trial.params lgbm = LGBMRegressor(**best_param2...
!pip install.. /input/deepfake-xception-trained-model/pytorchcv-0.0.55-py2.py3-none-any.whl --quiet
Deepfake Detection Challenge
8,546,370
final_model = xgb.XGBRegressor(n_estimators= 2000, max_depth= 16,tree_method='gpu_hist', predictor='gpu_predictor') sgd = SGDRegressor(max_iter=1000) hgb = HistGradientBoostingRegressor(max_depth=3, min_samples_leaf=1) cat = CatBoostRegressor(task_type="GPU", verbose=False) estimators = [ lgbm, cat, sgd, hgb, xgbRe...
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,546,370
submission = pd.read_csv("/kaggle/input/tabular-playground-series-jan-2021/test.csv", index_col=["id"]) y_hat = final_model.predict(S_test) submission["target"] = y_hat submission[["target"]].to_csv("/kaggle/working/submission_stacking.csv") joblib.dump(final_model, '/kaggle/working/skacking.pkl' )<save_to_csv>
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu
Deepfake Detection Challenge
8,546,370
submission = pd.read_csv("/kaggle/input/tabular-playground-series-jan-2021/test.csv", index_col=["id"]) lgbm = LGBMRegressor(**best_param2, device="gpu",gpu_use_dp=True, objective='regression', learning_rate= 0.01, metric='root_mean_squared_error', boosting_type='gbdt') lgbm = lgbm.fit(X, y, verbose=False) y_hat = l...
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,546,370
submission = pd.read_csv("/kaggle/input/tabular-playground-series-jan-2021/test.csv", index_col=["id"]) params = {'n_estimators': 3520, 'max_depth': 11, 'min_child_weight': 231, 'gamma': 2, 'colsample_bytree': 0.7, 'lambda': 0.014950936465569798, 'alpha': 0.28520156840812494, 'subsample': 0.6} xgbReg = train(xgb.XGBRe...
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,546,370
sns.set(font_scale=1.4) warnings.filterwarnings("ignore") <compute_test_metric>
input_size = 150
Deepfake Detection Challenge
8,546,370
def root_mean_squared_error(y_true, y_pred): return K.sqrt(K.mean(K.square(y_pred - y_true)) )<categorify>
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )
Deepfake Detection Challenge
8,546,370
def add_pca(train_df, test_df, cols, n_comp=20, fit_test = True, prefix='pca_', fit_test_first=False): pca = PCA(n_components=n_comp, random_state=42) pca_titles = [prefix+'_pca_'+str(x)for x in range(n_comp)] temp_train = train_df.copy() temp_test = test_df.copy() for c in cols: fv = temp_train[c].mean() temp_train[c...
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,546,370
PATH = '/kaggle/input/tabular-playground-series-jan-2021/' train = pd.read_csv(PATH+'train.csv') test = pd.read_csv(PATH+'test.csv') submission = pd.read_csv(PATH+'sample_submission.csv') FT_COLS = [x for x in train.columns if 'cont' in x] TARGET='target' print(train.shape) train.head(10 )<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
8,546,370
original_feature_dict = {'cont1': 5, 'cont2': 10, 'cont3': 8, 'cont4': 8, 'cont5': 5, 'cont6': 6, 'cont7': 4, 'cont8': 3, 'cont9': 7, 'cont10':3, 'cont11': 4, 'cont12': 2, 'cont13': 3, 'cont14': 5,} pca_dict = { 'extra_pca_0': 4, 'extra_pca_1': 1, 'extra_pca_2': 1, 'extra_pca_3': 2, 'extra_pca_4': 1, 'extra_pca_5': 1 }...
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,546,370
mixture_title_cols=[] for f in FT_COLS+pca_titles2: train, test, titles = split_distributions(train, test,f,TARGET, n_comp=ft_dict[f], prefix=f+'_dim', add_labels=True) mixture_title_cols+=titles mixture_value_cols = [] for count,f in enumerate(FT_COLS+pca_titles2): for d in range(ft_dict[f]): t_median = train[f][trai...
speed_test = False
Deepfake Detection Challenge
8,546,370
print('Total Original Features', len(FT_COLS)) print('Total Submixtures Labels', len(mixture_title_cols)) print('Total Submixtures Values', len(mixture_value_cols)) print('Total Feature Columns', len(FT_COLS)+len(mixture_title_cols)+len(mixture_value_cols))<data_type_conversions>
%%time model.eval() predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
8,546,370
NAN_VALUE = 0.0 for d in mixture_value_cols: train[d] = train[d].fillna(value=NAN_VALUE) test[d] = test[d].fillna(value=NAN_VALUE )<normalization>
submission_df_xception = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df_xception.to_csv("submission_xception.csv", index=False )
Deepfake Detection Challenge
8,546,370
SCALE = True if SCALE: train, test = st_scale(train, test, FT_COLS) for f in FT_COLS: train[f] = np.clip(train[f], -2, 2) test[f] = np.clip(test[f], -2, 2) SCALE_DISTS = True if SCALE_DISTS: for d in mixture_value_cols: TEMP_MAX = np.abs(train[d] ).max() train[d] = train[d] / TEMP_MAX test[d] = test[d] / TEMP_MAX<fe...
submission_df = pd.DataFrame({"filename": test_videos}) submission_df["label"] = 0.53*submission_df_resnext["label"] + 0.49*submission_df_xception["label"]
Deepfake Detection Challenge
8,546,370
<compute_train_metric><EOS>
submission_df.to_csv("submission.csv", index=False )
Deepfake Detection Challenge
8,526,543
<SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<train_model>
from IPython.display import Image
Deepfake Detection Challenge
8,526,543
def run_training(model, train_df, test_df,sample_submission, fold_col, orig_features, mixture_val_cols,mixture_label_cols, target_col, benchmark, outlier_col=None, nn=False, epochs=10,batch_size=32, verbose=False, dense=70, dout=0.15, dense_reg = 0.000001,act='elu'): FOLD_VALUES = sorted([x for x in train_df[fold_col]....
Image('.. /input/deepfake-kernel-data/google_cloud_compute_engine_launch_vm.png' )
Deepfake Detection Challenge
8,526,543
def keras_model(ft_orig, mixture_values, mixture_labels, n_layer=3,bnorm=True,dout=0.2, dense=20,act='elu', dense_reg = 0.000001, descend_fraction = 0.9): input1 = L.Input(shape=(len(ft_orig)) , name='input_orig') input1_do = L.Dropout(0.1 )(input1) XA = L.Dense(dense, activation=act, activity_regularizer=tf.keras.re...
Image('.. /input/deepfake-kernel-data/google_cloud_vm.png' )
Deepfake Detection Challenge
8,526,543
oof, test_predictions, fold_errors = run_training(model, train, test,submission, 'fold', FT_COLS, mixture_value_cols, mixture_title_cols, TARGET, cv_bm, outlier_col='outlier_filter', epochs=25, batch_size=256, verbose=False, dense=70, dout=0.15, dense_reg = 0.000001, act='elu', )<save_to_csv>
Image('.. /input/deepfake-kernel-data/lr_15e-2_epochs_42_patience_5.png' )
Deepfake Detection Challenge
8,526,543
print('Save Out of Fold Predictions') oof = pd.DataFrame(columns=['oof_prediction'], index=train['id'], data=oof + TARGET_MEAN) oof.to_csv('oof_predictions.csv', index=True) oof.head(10 )<compute_test_metric>
Image('.. /input/deepfake-kernel-data/lr_2e-3_epochs_10_patience_5.png' )
Deepfake Detection Challenge
8,526,543
print('fold errors', fold_errors) print('fold error std', np.array(fold_errors ).std() )<save_to_csv>
Image('.. /input/deepfake-kernel-data/lr_2e-3_epochs_20_patience_5.png' )
Deepfake Detection Challenge
8,526,543
submission['target'] = test_predictions + TARGET_MEAN submission.to_csv('submission.csv', index=False) submission.head(5 )<import_modules>
Image('.. /input/deepfake-kernel-data/lr_4e-3_epochs_12_patience_2.png' )
Deepfake Detection Challenge
8,526,543
import numpy as np import pandas as pd from math import sqrt from xgboost import XGBRegressor from lightgbm import LGBMRegressor from sklearn.impute import SimpleImputer from sklearn.ensemble import VotingRegressor from sklearn.feature_selection import VarianceThreshold from sklearn.metrics import make_scorer, mean_squ...
Image('.. /input/deepfake-kernel-data/lr_4e-3_epochs_30_patience_2.png' )
Deepfake Detection Challenge
8,526,543
RANDOM_STATE = 2021 CROSS_VALIDATION = 3<define_variables>
Image('.. /input/deepfake-kernel-data/google_cloud_vm_deepfake_training_screenshot.png' )
Deepfake Detection Challenge
8,526,543
data_dir = '/kaggle/input/tabular-playground-series-jan-2021'<load_from_csv>
%matplotlib inline warnings.filterwarnings("ignore" )
Deepfake Detection Challenge
8,526,543
df = pd.read_csv(f"{data_dir}/train.csv" ).set_index('id' ).convert_dtypes() display(df.shape) df.head(2 )<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"]) frame_h = 5 frame_l = 5 len(test_videos )
Deepfake Detection Challenge
8,526,543
X = df.copy() y = X.pop('target') X_train, X_valid, y_train, y_valid = train_test_split( X, y, train_size=0.8, test_size=0.2, random_state=RANDOM_STATE, )<define_variables>
print("PyTorch version:", torch.__version__) print("CUDA version:", torch.version.cuda) print("cuDNN version:", torch.backends.cudnn.version() )
Deepfake Detection Challenge
8,526,543
preprocessor = Pipeline(steps=[ ('imputer', SimpleImputer()), ('log', FunctionTransformer(np.log1p)) , ('scaler', StandardScaler()), ] )<choose_model_class>
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu
Deepfake Detection Challenge
8,526,543
pipeline = Pipeline([ ('preprocessor', preprocessor), ('variance_drop', VarianceThreshold(threshold=(0.95 *(1 - 0.95)))) , ('voting', 'passthrough'), ] )<choose_model_class>
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,526,543
parameters = [ { 'voting': [VotingRegressor([ ('lgbm', LGBMRegressor(random_state=RANDOM_STATE)) , ('xgb', XGBRegressor(random_state=RANDOM_STATE)) ])], 'voting__lgbm__n_estimators': [2000], 'voting__lgbm__max_depth': [12], 'voting__lgbm__learning_rate': [0.01], 'voting__lgbm__num_leaves': [256], 'voting__lgbm__min_c...
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,526,543
total = CROSS_VALIDATION * len(ParameterGrid(parameters)) display(f"Number of combination that will be run by the GridSearch: {total}" )<compute_test_metric>
input_size = 224
Deepfake Detection Challenge
8,526,543
custom_scoring = make_scorer( score_func=lambda y, y_pred: mean_squared_error(y, y_pred, squared=False), greater_is_better=False, )<choose_model_class>
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )
Deepfake Detection Challenge
8,526,543
grid_search = GridSearchCV( pipeline, param_grid=parameters, cv=CROSS_VALIDATION, scoring=custom_scoring, n_jobs=-1, verbose=True, )<train_on_grid>
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,526,543
grid_search.fit(X_train, y_train )<find_best_params>
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,526,543
display(abs(grid_search.best_score_)) display(grid_search.best_params_ )<compute_train_metric>
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,526,543
preds = grid_search.best_estimator_.predict(X_valid) mean_squared_error(y_valid, preds, squared=False )<load_from_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,526,543
X_test = pd.read_csv(f"{data_dir}/test.csv" ).set_index('id' ).convert_dtypes() display(X_test.shape) X_test.head(2 )<save_to_csv>
speed_test = False
Deepfake Detection Challenge
8,526,543
preds_test = grid_search.best_estimator_.predict(X_test) output = pd.DataFrame( {'Id': X_test.index, 'target': preds_test}) output.to_csv(f"submission.csv", index=False )<install_modules>
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,526,543
!pip install pytorch_tabular !pip install torch_optimizer<import_modules>
predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
8,526,543
import numpy as np import pandas as pd import time import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import KFold from sklearn.metrics import mean_squared_error from sklearn.preprocessing import StandardScaler from pytorch_tabular import TabularModel from pytorch_tabular.models import C...
submission_df_resnext = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df_resnext.to_csv("submission_resnext.csv", index=False )
Deepfake Detection Challenge
8,526,543
df_train = pd.read_csv('.. /input/tabular-playground-series-jan-2021/train.csv') display(df_train.head()) df_test = pd.read_csv('.. /input/tabular-playground-series-jan-2021/test.csv') display(df_test.head()) features = ['cont1', 'cont2', 'cont3', 'cont4', 'cont5', 'cont6', 'cont7', 'cont8', 'cont9', 'cont10', 'con...
!pip install.. /input/deepfake-xception-trained-model/pytorchcv-0.0.55-py2.py3-none-any.whl --quiet
Deepfake Detection Challenge
8,526,543
enc = KBinsDiscretizer(n_bins=10, encode='ordinal', strategy="quantile") enc.fit(df_train[features]) binned_df_train = enc.transform(df_train[features]) binned_df_test = enc.transform(df_test[features]) for i, feature in enumerate(features): df_train[f"{feature}_binned"] = binned_df_train[:,i] df_test[f"{feature}_b...
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,526,543
def get_configs(train): epochs = 25 batch_size = 512 steps_per_epoch = int(( len(train)//batch_size)*0.9) data_config = DataConfig( target=['target'], continuous_cols=['cont1', 'cont2', 'cont3', 'cont4', 'cont5', 'cont6', 'cont7', 'cont8', 'cont9', 'cont10', 'cont11', 'cont12', 'cont13', 'cont14'], categorical_cols=[...
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu
Deepfake Detection Challenge
8,526,543
rnd_seed_cv = 1234 rnd_seed_reg = 1234 kf = KFold(n_splits=5, random_state=rnd_seed_cv, shuffle=True) df_train.drop(columns='id', inplace=True) df_test.drop(columns='id', inplace=True) df_test['target'] = 0<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,526,543
def node(train, valid, df_test): data_config, trainer_config, optimizer_config, model_config = get_configs(train) tabular_model = TabularModel( data_config=data_config, model_config=model_config, optimizer_config=optimizer_config, trainer_config=trainer_config ) tabular_model.fit(train=train, validation=valid, opti...
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,526,543
CV_node = [] CV_lgb = [] CV_cb = [] preds_train_node = [] preds_train_lgb = [] preds_train_cb = [] preds_test_node = [] preds_test_lgb = [] preds_test_cb = [] cross_validated_preds = [] t1 = time.time() for train_index, test_index in kf.split(df_train): train = df_train.iloc[train_index] valid = df_train.iloc[test_inde...
input_size = 150
Deepfake Detection Challenge
8,526,543
print('CV performance [RMSE]: ', np.mean(CV_node, axis=0)) print('CV performance [RMSE]: ', np.mean(CV_lgb, axis=0)) print('CV performance [RMSE]: ', np.mean(CV_cb, axis=0))<save_to_csv>
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )
Deepfake Detection Challenge
8,526,543
cross_val_pred_df = pd.concat(cross_validated_preds, sort=False) cross_val_pred_df.to_csv("cross_val_preds.csv") joblib.dump(preds_test_node, "preds_test_node.sav") joblib.dump(preds_test_lgb, "preds_test_lgb.sav") joblib.dump(preds_test_cb, "preds_test_cb.sav" )<prepare_output>
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,526,543
avg_cb_pred = np.mean(preds_test_cb, axis=0) avg_lgb_pred = np.mean(preds_test_lgb, axis=0) avg_node_pred = np.mean(preds_test_node, axis=0) pred_test = np.average([avg_node_pred, avg_lgb_pred, avg_cb_pred], axis=0, weights=[-0.15447081, 1.1021915 , 0.06145868] )<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,526,543
df_sub = pd.read_csv('.. /input/tabular-playground-series-jan-2021/sample_submission.csv') df_sub.target = pred_test df_sub.head()<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,526,543
df_sub.to_csv('submission.csv', index=False )<load_from_csv>
speed_test = False
Deepfake Detection Challenge
8,526,543
train = pd.read_csv('/kaggle/input/tabular-playground-series-jan-2021/train.csv', index_col='id') test = pd.read_csv('/kaggle/input/tabular-playground-series-jan-2021/test.csv', index_col='id' )<import_modules>
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,526,543
import seaborn as sns<filter>
%%time model.eval() predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
8,526,543
train[train['target'] <= 4.5]<drop_column>
submission_df_xception = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df_xception.to_csv("submission_xception.csv", index=False )
Deepfake Detection Challenge
8,526,543
train.drop([241352, 284103, 300936, 307139, 355831], axis = 0, inplace=True) train[train['target'] <= 4.5]<drop_column>
submission_df = pd.DataFrame({"filename": test_videos}) submission_df["label"] = 0.51*submission_df_resnext["label"] + 0.5*submission_df_xception["label"]
Deepfake Detection Challenge
8,526,543
target = train['target'] train.drop('target', axis=1, inplace=True )<split>
submission_df.to_csv("submission.csv", index=False )
Deepfake Detection Challenge
8,342,909
X_train, X_valid, y_train, y_valid = train_test_split(train, target, test_size=0.15, random_state=0 )<train_model>
%matplotlib inline
Deepfake Detection Challenge
8,342,909
lgbm = LGBMRegressor(tree_method='gpu_hist',learning_rate=0.07, max_depth=15, random_state=0, n_estimators=2000, n_jobs=-1) lgbm.fit(X_train, y_train, eval_set=[(X_valid, y_valid)]) lgbm.score(X_valid, y_valid )<train_model>
package_path = '.. /input/efficientnet-pytorch/EfficientNet-PyTorch/EfficientNet-PyTorch-master' sys.path.append(package_path)
Deepfake Detection Challenge
8,342,909
xgb = XGBRegressor(learning_rate=0.005, max_depth=8, n_estimators=6000, n_jobs=-1, tree_method='gpu_hist', random_state=3) xgb.fit(X_train, y_train, eval_set=[(X_valid, y_valid)]) xgb.score(X_valid, y_valid )<train_model>
def seed_everything(seed=1234): 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 = True
Deepfake Detection Challenge
8,342,909
ensemble = VotingRegressor(estimators=[("xgb", xgb),("lgbm", lgbm)], weights=[1.1,1]) ensemble.fit(X_train, y_train) ensemble.score(X_valid, y_valid )<train_model>
seed_everything(0 )
Deepfake Detection Challenge
8,342,909
model = ensemble.fit(train, target) model.score(train, target )<predict_on_test>
weight_path = 'efficientnet_b0_epoch_15_loss_0.158.pth' trained_weights_path = os.path.join('.. /input/deepfake-detection-model-weight', weight_path) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") torch.backends.cudnn.benchmark=True
Deepfake Detection Challenge
8,342,909
pred = model.predict(test) pred<load_from_csv>
test_dir = '.. /input/deepfake-detection-challenge/test_videos' os.listdir(test_dir)[:5]
Deepfake Detection Challenge
8,342,909
id = pd.read_csv('/kaggle/input/tabular-playground-series-jan-2021/test.csv')['id']<save_to_csv>
class ImageTransform: def __init__(self, size, mean, std): self.data_transform = transforms.Compose([ transforms.Resize(( size, size), interpolation=Image.BILINEAR), transforms.ToTensor() , transforms.Normalize(mean, std) ]) def __call__(self, img): return self.data_transform(img )
Deepfake Detection Challenge
8,342,909
output = pd.DataFrame({'id': id, 'target': pred}) output.to_csv("submission.csv", index=False) print("saved" )<import_modules>
class DeepfakeDataset(Dataset): def __init__(self, file_list, device, detector, transform, img_num=20, frame_window=10): self.file_list = file_list self.device = device self.detector = detector self.transform = transform self.img_num = img_num self.frame_window = frame_window def __len__(self): return len(self.file_lis...
Deepfake Detection Challenge
8,342,909
for dirname, _, filenames in os.walk('/kaggle/input'): for filename in filenames: print(os.path.join(dirname, filename)) input_path = Path('/kaggle/input/tabular-playground-series-jan-2021/' )<load_from_csv>
model = EfficientNet.from_name('efficientnet-b0') model._fc = nn.Linear(in_features=model._fc.in_features, out_features=1) model.load_state_dict(torch.load(trained_weights_path, map_location=torch.device(device)) )
Deepfake Detection Challenge
8,342,909
train = pd.read_csv(input_path / 'train.csv', index_col='id') print(train.shape) train.head()<load_from_csv>
test_file = [os.path.join(test_dir, path)for path in os.listdir(test_dir)]
Deepfake Detection Challenge
8,342,909
test = pd.read_csv(input_path / 'test.csv', index_col='id') print(test.shape) test.head()<count_missing_values>
def predict_dfdc(dataset, model): torch.cuda.empty_cache() pred_list = [] path_list = [] model = model.to(device) model.eval() with torch.no_grad() : for i in tqdm(range(len(dataset))): pred = 0 imgs, mov_path = dataset.__getitem__(i) if len(imgs)== 0: pred_list.append(0.5) path_list.append(mov_path) continue for i...
Deepfake Detection Challenge
8,342,909
train.isnull().sum()<feature_engineering>
res = pd.DataFrame({ 'filename': path_list, 'label': pred_list, }) res.sort_values(by='filename', ascending=True, inplace=True )
Deepfake Detection Challenge
8,342,909
<feature_engineering><EOS>
res.to_csv('submission.csv', index=False )
Deepfake Detection Challenge
7,469,803
<SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<split>
%%capture !pip install /kaggle/input/facenet-pytorch-vggface2/facenet_pytorch-1.0.1-py3-none-any.whl !mkdir -p /tmp/.cache/torch/checkpoints/ !cp /kaggle/input/facenet-pytorch-vggface2/20180402-114759-vggface2-logits.pth /tmp/.cache/torch/checkpoints/vggface2_DG3kwML46X.pt !cp /kaggle/input/facenet-pytorch-vggface2/201...
Deepfake Detection Challenge
7,469,803
X_train, X_test, y_train, y_test = train_test_split(trainNorm, target, test_size=0.2, random_state=7) print('X_train: ', X_train.shape) print('X_test: ', X_test.shape) print('y_train: ', y_train.shape) print('y_test: ', y_test.shape )<compute_train_metric>
device = 'cuda:0' if torch.cuda.is_available() else 'cpu' print(f'Running on device: {device}' )
Deepfake Detection Challenge
7,469,803
def rmse_cv(model,X,y): rmse = np.sqrt(-cross_val_score(model, X, y, scoring="neg_mean_squared_error", cv=5)) return rmse<define_variables>
mtcnn = MTCNN(device=device ).eval() resnet = InceptionResnetV1(pretrained='vggface2', num_classes=2, device=device ).eval()
Deepfake Detection Challenge
7,469,803
models = [LinearRegression() , Ridge() , Lasso() , ElasticNet() , SGDRegressor() , BayesianRidge() , cb.CatBoostRegressor() , RandomForestRegressor() , ] names = ["LR", "Ridge", "Lasso", "ElasticNet", "SGD","BayesianRidge", "catboost","RandomForestRegressor"]<compute_train_metric>
bias = -0.4 weight = 0.068235746 submission = [] for filename, x_i in zip(filenames, X): if x_i is not None and len(x_i)== 10: prob = 1 /(1 + np.exp(-(bias +(weight * x_i ).sum()))) else: prob = 0.6 submission.append([os.path.basename(filename), prob] )
Deepfake Detection Challenge
7,469,803
<compute_train_metric><EOS>
submission = pd.DataFrame(submission, columns=['filename', 'label']) submission.sort_values('filename' ).to_csv('submission.csv', index=False )
Deepfake Detection Challenge
7,025,346
<SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<save_to_csv>
!pip install /kaggle/input/dfdcdataset/dlib-19.19.0-cp36-cp36m-linux_x86_64.whl
Deepfake Detection Challenge
7,025,346
<choose_model_class><EOS>
DATA_PREFIX = '/kaggle/input' SKIP_FRAMES = 75 detector = dlib.cnn_face_detection_model_v1(os.path.join(DATA_PREFIX, 'dfdcdataset', 'mmod_human_face_detector.dat')) sp = dlib.shape_predictor(os.path.join(DATA_PREFIX, 'dfdcdataset', 'shape_predictor_5_face_landmarks.dat')) predictor = dlib.deep_fake_detection_model_v1(o...
Deepfake Detection Challenge
8,201,023
<SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<train_model>
%matplotlib inline warnings.filterwarnings("ignore" )
Deepfake Detection Challenge
8,201,023
history = model.fit(X_train, y_train, validation_split=0.2, verbose=1, epochs=10 )<compute_test_metric>
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,201,023
final_predictions = model.predict(X_test) final_mse = mean_squared_error(y_test, final_predictions) final_rmse = np.sqrt(final_mse) print("RMSE on X_test ", round(final_rmse, 4))<predict_on_test>
print("PyTorch version:", torch.__version__) print("CUDA version:", torch.version.cuda) print("cuDNN version:", torch.backends.cudnn.version() )
Deepfake Detection Challenge
8,201,023
final_predictions = model.predict(testNorm) final_predictions.shape<load_from_csv>
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu
Deepfake Detection Challenge
8,201,023
subm = pd.read_csv(input_path / 'sample_submission.csv') print(subm.shape) subm.head()<prepare_output>
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
id_col=subm.id subm=id_col.to_frame() subm['target'] = final_predictions subm.set_index('id',inplace=True) subm.head()<save_to_csv>
frames_per_video = 90 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
subm.to_csv('NNSubmission.csv' )<load_pretrained>
input_size = 250
Deepfake Detection Challenge
8,201,023
weight_base64 = base64.b64encode(bz2.compress(pickle.dumps(torch.load('.. /input/alphageese-training/alphageese_epoch30.pth', map_location=torch.device('cpu'))))) w = "weight= %s"%weight_base64 %store w >submission.py<set_options>
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
%%writefile -a submission.py <set_options>
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,201,023
%%writefile -a submission.py class MCTS() : def __init__(self, game, nn_agent, eps=1e-8, cpuct=1.0): self.game = game self.nn_agent = nn_agent self.eps = eps self.cpuct = cpuct self.Qsa = {} self.Nsa = {} self.Ns = {} self.Ps = {} self.Vs = {} self.last_obs = None def getActionProb(self, obs, timelimit=1.0): start_time...
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,201,023
%%writefile -a submission.py class HungryGeese(object): def __init__(self, rows=7, columns=11, actions=[Action.NORTH, Action.SOUTH, Action.WEST, Action.EAST], hunger_rate=40): self.rows = rows self.columns = columns self.actions = actions self.hunger_rate = hunger_rate def getActionSize(self): return len(self.actions) ...
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
%%writefile -a submission.py class TorusConv2d(nn.Module): def __init__(self, input_dim, output_dim, kernel_size, bn): super().__init__() self.edge_size =(kernel_size[0] // 2, kernel_size[1] // 2) self.conv = nn.Conv2d(input_dim, output_dim, kernel_size=kernel_size) self.bn = nn.BatchNorm2d(output_dim)if bn else None...
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