kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
8,069,381
train=train.drop(train[(train['GrLivArea']>4000)&(train['SalePrice']<300000)].index )<prepare_x_and_y>
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" )
Deepfake Detection Challenge
8,069,381
Ytrain=train['SalePrice'] train=train[list(test)] all_data=pd.concat(( train, test), axis=0) print(all_data.shape) Ytrain=np.log(Ytrain+1 )<count_missing_values>
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
cols=list(all_data) for col in list(all_data): if(all_data[col].isnull().sum())==0: cols.remove(col) else: pass print(len(cols))<data_type_conversions>
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
for col in('PoolQC', 'MiscFeature', 'Alley', 'Fence', 'FireplaceQu', 'GarageType', 'GarageFinish', 'GarageQual', 'GarageCond', 'BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2', 'MasVnrType', 'MSSubClass'): all_data[col] = all_data[col].fillna('None') for col in('GarageYrBlt', 'GarageArea', 'GarageCars', 'BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF','TotalBsmtSF', 'BsmtFullBath', 'BsmtHalfBath', 'MasVnrArea','LotFrontage'): all_data[col] = all_data[col].fillna(0) for col in('MSZoning', 'Electrical', 'KitchenQual', 'Exterior1st', 'Exterior2nd', 'SaleType', 'Functional', 'Utilities'): all_data[col] = all_data[col].fillna(all_data[col].mode() [0]) print(f"Total count of missing values in all_data : {all_data.isnull().sum().sum() }" )<feature_engineering>
input_size = 150
Deepfake Detection Challenge
8,069,381
all_data['TotalSF']=all_data['TotalBsmtSF'] + all_data['1stFlrSF'] + all_data['2ndFlrSF'] all_data['No2ndFlr']=(all_data['2ndFlrSF']==0 )<feature_engineering>
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
all_data['TotalBath']=all_data['BsmtFullBath'] + all_data['FullBath'] +(all_data['BsmtHalfBath']/2)+(all_data['HalfBath']/2 )<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) return(x1+x2)* 0.5 model[0].final_block.pool = nn.Sequential(nn.AdaptiveAvgPool2d(( 1,1))) class Head(torch.nn.Module): def __init__(self, in_f, out_f): super(Head, self ).__init__() self.f = nn.Flatten() self.l = nn.Linear(in_f, 512) self.d = nn.Dropout(0.5) self.o = nn.Linear(512, out_f) self.b1 = nn.BatchNorm1d(in_f) self.b2 = nn.BatchNorm1d(512) self.r = nn.ReLU() def forward(self, x): x = self.f(x) x = self.b1(x) x = self.d(x) x = self.l(x) x = self.r(x) x = self.b2(x) x = self.d(x) out = self.o(x) return out class FCN(torch.nn.Module): def __init__(self, base, in_f): super(FCN, self ).__init__() self.base = base self.h1 = Head(in_f, 1) def forward(self, x): x = self.base(x) return self.h1(x) net = [] model = FCN(model, 2048) model = model.cuda() model.load_state_dict(torch.load('.. /input/deepfake-xception-trained-model/model.pth')) net.append(model )
Deepfake Detection Challenge
8,069,381
all_data['YrBltAndRemod']=all_data['YearBuilt']+all_data['YearRemodAdd']<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 = isotropically_resize_image(face, input_size) resized_face = make_square_image(resized_face) if n < batch_size: x[n] = resized_face n += 1 else: print("WARNING: have %d faces but batch size is %d" %(n, batch_size)) if n > 0: x = torch.tensor(x, device=gpu ).float() x = x.permute(( 0, 3, 1, 2)) for i in range(len(x)) : x[i] = normalize_transform(x[i] / 255.) with torch.no_grad() : y_pred = model(x) y_pred = torch.sigmoid(y_pred.squeeze()) return y_pred[:n].mean().item() except Exception as e: print("Prediction error on video %s: %s" %(video_path, str(e))) return 0.481
Deepfake Detection Challenge
8,069,381
Basement = ['BsmtCond', 'BsmtExposure', 'BsmtFinSF1', 'BsmtFinSF2', 'BsmtFinType1', 'BsmtFinType2', 'BsmtQual', 'BsmtUnfSF', 'TotalBsmtSF'] Bsmt=all_data[Basement]<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(predictions )
Deepfake Detection Challenge
8,069,381
Bsmt=Bsmt.replace(to_replace='Po', value=1) Bsmt=Bsmt.replace(to_replace='Fa', value=2) Bsmt=Bsmt.replace(to_replace='TA', value=3) Bsmt=Bsmt.replace(to_replace='Gd', value=4) Bsmt=Bsmt.replace(to_replace='Ex', value=5) Bsmt=Bsmt.replace(to_replace='None', value=0) Bsmt=Bsmt.replace(to_replace='No', value=1) Bsmt=Bsmt.replace(to_replace='Mn', value=2) Bsmt=Bsmt.replace(to_replace='Av', value=3) Bsmt=Bsmt.replace(to_replace='Gd', value=4) Bsmt=Bsmt.replace(to_replace='Unf', value=1) Bsmt=Bsmt.replace(to_replace='LwQ', value=2) Bsmt=Bsmt.replace(to_replace='Rec', value=3) Bsmt=Bsmt.replace(to_replace='BLQ', value=4) Bsmt=Bsmt.replace(to_replace='ALQ', value=5) Bsmt=Bsmt.replace(to_replace='GLQ', value=6 )<feature_engineering>
%%time model.eval() predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
8,069,381
Bsmt['BsmtScore']= Bsmt['BsmtQual'] * Bsmt['BsmtCond'] * Bsmt['TotalBsmtSF'] all_data['BsmtScore']=Bsmt['BsmtScore'] Bsmt['BsmtFin'] =(Bsmt['BsmtFinSF1'] * Bsmt['BsmtFinType1'])+(Bsmt['BsmtFinSF2'] * Bsmt['BsmtFinType2']) all_data['BsmtFinScore']=Bsmt['BsmtFin'] all_data['BsmtDNF']=(all_data['BsmtFinScore']==0 )<define_variables>
submission_df_xception = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df_xception.to_csv("submission_xception.csv", index=False )
Deepfake Detection Challenge
8,069,381
garage=['GarageArea','GarageCars','GarageCond','GarageFinish','GarageQual','GarageType','GarageYrBlt'] Garage=all_data[garage] all_data['NoGarage']=(all_data['GarageArea']==0 )<categorify>
submission_df = pd.DataFrame({"filename": test_videos} )
Deepfake Detection Challenge
8,069,381
Garage=Garage.replace(to_replace='Po', value=1) Garage=Garage.replace(to_replace='Fa', value=2) Garage=Garage.replace(to_replace='TA', value=3) Garage=Garage.replace(to_replace='Gd', value=4) Garage=Garage.replace(to_replace='Ex', value=5) Garage=Garage.replace(to_replace='None', value=0) Garage=Garage.replace(to_replace='Unf', value=1) Garage=Garage.replace(to_replace='RFn', value=2) Garage=Garage.replace(to_replace='Fin', value=3) Garage=Garage.replace(to_replace='CarPort', value=1) Garage=Garage.replace(to_replace='Basment', value=4) Garage=Garage.replace(to_replace='Detchd', value=2) Garage=Garage.replace(to_replace='2Types', value=3) Garage=Garage.replace(to_replace='Basement', value=5) Garage=Garage.replace(to_replace='Attchd', value=6) Garage=Garage.replace(to_replace='BuiltIn', value=7) Garage['GarageScore']=(Garage['GarageArea'])*(Garage['GarageCars'])*(Garage['GarageFinish'])*(Garage['GarageQual'])*(Garage['GarageType']) all_data['GarageScore']=Garage['GarageScore']<drop_column>
submission_df["label"] = 0.65*submission_df_resnext["label"] + 0.35*submission_df_xception["label"]
Deepfake Detection Challenge
8,069,381
<data_type_conversions><EOS>
submission_df.to_csv("submission.csv", index=False )
Deepfake Detection Challenge
8,053,853
<SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<categorify>
%matplotlib inline
Deepfake Detection Challenge
8,053,853
non_numeric=all_data.select_dtypes(include='object') def onehot(col_list): global all_data while len(col_list)!=0: col=col_list.pop(0) data_encoded=pd.get_dummies(all_data[col], prefix=col) all_data=pd.merge(all_data, data_encoded, on='Id') all_data=all_data.drop(columns=col) print(all_data.shape) onehot(list(non_numeric))<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"]) len(test_videos )
Deepfake Detection Challenge
8,053,853
numeric=all_data.select_dtypes(exclude='object') def log_transform(col_list): transformed_col=[] while len(col_list)!=0: col=col_list.pop(0) if all_data[col].skew() > 0.5: all_data[col]=np.log(all_data[col]+1) transformed_col.append(col) else: pass print(f"{len(transformed_col)} features had been tranformed") print(all_data.shape) log_transform(list(numeric))<import_modules>
print("PyTorch version:", torch.__version__) print("CUDA version:", torch.version.cuda) print("cuDNN version:", torch.backends.cudnn.version() )
Deepfake Detection Challenge
8,053,853
from sklearn.model_selection import KFold, cross_val_score, GridSearchCV from sklearn.metrics import mean_squared_error from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor from xgboost import XGBRegressor from lightgbm import LGBMRegressor<choose_model_class>
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu
Deepfake Detection Challenge
8,053,853
kfold = KFold(n_splits=4 )<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,053,853
GBC = GradientBoostingRegressor() gb_param_grid = {'n_estimators' : [100, 200, 500], 'learning_rate': [0.01, 0.05, 0.1, 0.2], 'max_depth': [3, 5, 10, 15], 'min_samples_leaf': [100,150], 'max_features': [0.3, 0.1] } gsGBC = GridSearchCV(GBC,param_grid = gb_param_grid, cv=kfold, scoring="neg_mean_squared_error", n_jobs= 4, verbose = 1) gsGBC.fit(Xtrain,Ytrain) GBC_best = gsGBC.best_estimator_ gsGBC.best_score_<train_on_grid>
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,053,853
XGB=XGBRegressor() xgb_param_grid = {'learning_rate':[0.01, 0.05, 0.1, 0.2], 'n_estimators':[100, 1000, 2000], 'max_depth':[3, 5, 10, 15]} gsXGB = GridSearchCV(XGB,param_grid = xgb_param_grid, cv=kfold, scoring="neg_mean_squared_error", n_jobs=4, verbose =1) gsXGB.fit(Xtrain,Ytrain) XGB_best = gsXGB.best_estimator_ gsXGB.best_score_<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,053,853
LGB = LGBMRegressor() lgb_param_grid = { 'num_leaves' : [1,5,10], 'learning_rate': [1,0.1,0.01,0.001], 'n_estimators': [50, 100, 200, 500, 1000,5000], 'max_depth': [15,20,25], 'num_leaves': [50, 100, 200], 'min_split_gain': [0.3, 0.4] } gsLGB = GridSearchCV(LGB,param_grid = lgb_param_grid, cv=kfold, scoring="neg_mean_squared_error", n_jobs= 4, verbose = 1) gsLGB.fit(Xtrain,Ytrain) LGB_best = gsLGB.best_estimator_ gsLGB.best_score_<import_modules>
input_size = 224
Deepfake Detection Challenge
8,053,853
from sklearn.ensemble import VotingRegressor<train_model>
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,053,853
votingC = VotingRegressor(estimators=[('LGB', LGB_best), ('GBC',GBC_best), ('XGB', XGB_best)], n_jobs=4) votingC = votingC.fit(Xtrain, Ytrain) <predict_on_test>
checkpoint = torch.load("/kaggle/input/deepfakes-inference-demo/resnext.pth", map_location=gpu) model = MyResNeXt().to(gpu) model.load_state_dict(checkpoint) _ = model.eval() del checkpoint
Deepfake Detection Challenge
8,053,853
test_SalePrice = pd.Series(votingC.predict(Xtest), name="SalePrice" )<prepare_output>
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 = isotropically_resize_image(face, input_size) resized_face = make_square_image(resized_face) if n < batch_size: x[n] = resized_face n += 1 else: print("WARNING: have %d faces but batch size is %d" %(n, batch_size)) if n > 0: x = torch.tensor(x, device=gpu ).float() x = x.permute(( 0, 3, 1, 2)) for i in range(len(x)) : x[i] = normalize_transform(x[i] / 255.) with torch.no_grad() : y_pred = model(x) y_pred = torch.sigmoid(y_pred.squeeze()) return y_pred[:n].mean().item() except Exception as e: print("Prediction error on video %s: %s" %(video_path, str(e))) return 0.5
Deepfake Detection Challenge
8,053,853
submission = pd.DataFrame({ "Id" :Id_test, "SalePrice": test_SalePrice }) submission.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(predictions )
Deepfake Detection Challenge
8,053,853
submission.to_csv('submission_voting.csv', index=False )<load_from_csv>
%%time predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
8,053,853
train = pd.read_csv(".. /input/house-prices-advanced-regression-techniques/train.csv") test = pd.read_csv(".. /input/house-prices-advanced-regression-techniques/test.csv") print("train shape:" + str(train.shape)) print("test shape:" + str(test.shape))<import_modules>
submission_df_resnext = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df_resnext.to_csv("submission_resnext.csv", index=False )
Deepfake Detection Challenge
8,053,853
from scipy.stats import skew, norm import scipy.stats as stats from scipy.special import boxcox1p from scipy.stats import boxcox_normmax<filter>
!pip install.. /input/deepfake-xception-trained-model/pytorchcv-0.0.55-py2.py3-none-any.whl --quiet
Deepfake Detection Challenge
8,053,853
train[(train['GrLivArea'] > 4500)&(train['SalePrice'] < 250000)] [cols]<filter>
input_size = 150
Deepfake Detection Challenge
8,053,853
cols_outliers = cols[:] cols_outliers.extend(['YrSold', 'Neighborhood']) train[(train['OverallQual'] >= 9)&(train['GrLivArea'] > 3000)] [cols_outliers]<filter>
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) return(x1+x2)* 0.5 model[0].final_block.pool = nn.Sequential(nn.AdaptiveAvgPool2d(( 1,1))) class Head(torch.nn.Module): def __init__(self, in_f, out_f): super(Head, self ).__init__() self.f = nn.Flatten() self.l = nn.Linear(in_f, 512) self.d = nn.Dropout(0.5) self.o = nn.Linear(512, out_f) self.b1 = nn.BatchNorm1d(in_f) self.b2 = nn.BatchNorm1d(512) self.r = nn.ReLU() def forward(self, x): x = self.f(x) x = self.b1(x) x = self.d(x) x = self.l(x) x = self.r(x) x = self.b2(x) x = self.d(x) out = self.o(x) return out class FCN(torch.nn.Module): def __init__(self, base, in_f): super(FCN, self ).__init__() self.base = base self.h1 = Head(in_f, 1) def forward(self, x): x = self.base(x) return self.h1(x )
Deepfake Detection Challenge
8,053,853
cols_outliers_test = cols_outliers[:] cols_outliers_test.remove('SalePrice') test[(test['OverallQual'] >= 9)&(test['GrLivArea'] > 3000)] [cols_outliers_test]<drop_column>
checkpoint = torch.load('.. /input/deepfake-xception-trained-model/model.pth', map_location=gpu) model = FCN(model, 2048 ).to(gpu) model.load_state_dict(checkpoint) _ = model.eval() del checkpoint
Deepfake Detection Challenge
8,053,853
train.drop([523, 1298], axis = 0, inplace = True )<filter>
%%time predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
8,053,853
train[(train['OverallQual'] == 4)&(train['SalePrice'] > 250000)] [cols]<create_dataframe>
submission_df_xception = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df_xception.to_csv("submission_xception.csv", index=False )
Deepfake Detection Challenge
8,053,853
pd.DataFrame(train[(train['OverallQual'] == 4)][cols].mean() ).T<filter>
submission_df = pd.DataFrame({"filename": test_videos} )
Deepfake Detection Challenge
8,053,853
train[(train['OverallQual'] == 8)&(train['SalePrice'] > 500000)] [cols]<create_dataframe>
r1 = 0.46441 r2 = 0.52189 total = r1 + r2 r11 = r1/total r22 = r2/total
Deepfake Detection Challenge
8,053,853
pd.DataFrame(train[(train['OverallQual'] == 8)][cols].mean() ).T<prepare_output>
submission_df["label"] = r22*submission_df_resnext["label"] + r11*submission_df_xception["label"]
Deepfake Detection Challenge
8,053,853
data_sets = [train, test] data_sets_null = [] for data_set in data_sets: n_houses = data_set.shape[0] data_set = data_set.isnull().sum().sort_values(ascending = False) data_set = pd.DataFrame(data_set[(data_set != 0)], columns = ['NullSum']) data_set['NullPercent'] =(data_set['NullSum']/n_houses)*100 data_sets_null.append(data_set) train_null, test_null = data_sets_null<concatenate>
submission_df.to_csv("submission.csv", index=False )
Deepfake Detection Challenge
8,003,261
train_null_tidy = train_null.add_prefix('Train_'); test_null_tidy = test_null.add_prefix('Test_'); total_null_tidy = pd.concat([train_null_tidy, test_null_tidy], axis=1 ).fillna(0) total_null_tidy<train_model>
%matplotlib inline
Deepfake Detection Challenge
8,003,261
print("Train features with Na = " + str(( train.isnull().sum() != 0 ).sum())) print("Test features with Na = " + str(( test.isnull().sum() != 0 ).sum()))<data_type_conversions>
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,003,261
def handle_missing(data_sets): for data_set in data_sets: data_set['MSSubClass'] = data_set ['MSSubClass'].apply(str) data_set['YrSold'] = data_set['YrSold'].astype(str) data_set['MoSold'] = data_set['MoSold'].astype(str) for col in('PoolQC', 'MiscFeature', 'Alley', 'Fence', 'FireplaceQu', 'MasVnrType', 'Utilities'): data_set[col] = data_set[col].fillna('None') data_set['MasVnrArea'] = data_set['MasVnrArea'].fillna(0) for col in('Exterior1st', 'Exterior2nd', 'SaleType'): data_set[col] = data_set[col].fillna(data_set[col].mode() [0]) data_set['MSZoning'] = data_set.groupby('MSSubClass')['MSZoning'].transform(lambda x: x.fillna(x.mode() [0])) data_set['LotFrontage'] = data_set.groupby("Neighborhood")['LotFrontage'].transform(lambda x: x.fillna(x.median())) data_set['Electrical'] = data_set['Electrical'].fillna("SBrkr") data_set['Functional'] = data_set['Functional'].fillna('Typ') data_set['KitchenQual'] = data_set['KitchenQual'].fillna('TA') for col in ['GarageType', 'GarageFinish', 'GarageQual', 'GarageCond']: data_set[col] = data_set[col].fillna('None') for col in('GarageYrBlt', 'GarageArea', 'GarageCars'): data_set[col] = data_set[col].fillna(0) for col in('BsmtQual', 'BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2'): data_set[col] = data_set[col].fillna('None') for col in('BsmtFullBath', 'BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF', 'BsmtHalfBath'): data_set[col] = data_set[col].fillna(0 )<train_model>
print("PyTorch version:", torch.__version__) print("CUDA version:", torch.version.cuda) print("cuDNN version:", torch.backends.cudnn.version() )
Deepfake Detection Challenge
8,003,261
print("Train features with Na = " + str(( train.isnull().sum() != 0 ).sum())) print("Test features with Na = " + str(( test.isnull().sum() != 0 ).sum()))<feature_engineering>
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu
Deepfake Detection Challenge
8,003,261
train['SalePrice_norm'] = np.log1p(train['SalePrice'] )<prepare_x_and_y>
facedet = BlazeFace().to(gpu) facedet.load_weights("/kaggle/input/helper/blazeface-pytorch/blazeface.pth") facedet.load_anchors("/kaggle/input/helper/blazeface-pytorch/anchors.npy") _ = facedet.train(False )
Deepfake Detection Challenge
8,003,261
train_Y = train['SalePrice_norm'] train.drop(['SalePrice', 'SalePrice_norm'], axis = 1, inplace = True) all_data = pd.concat([train, test], axis=0, ignore_index = True) <sort_values>
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,003,261
numeric_dtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64'] numeric = [] for i in all_data.columns: if all_data[i].dtype in numeric_dtypes: numeric.append(i) skew_features = all_data[numeric].apply(lambda x: skew(x)).sort_values(ascending=False) high_skew = skew_features[abs(skew_features)> 0.5] skew_index = high_skew.index print("There are {} numerical features with Skew > 0.5 :".format(high_skew.shape[0])) skewness = pd.DataFrame({'Skew' :high_skew}) high_skew<compute_test_metric>
input_size = 224
Deepfake Detection Challenge
8,003,261
for i in skew_index: all_data[i] = boxcox1p(all_data[i], boxcox_normmax(all_data[i] + 1))<feature_engineering>
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )
Deepfake Detection Challenge
8,003,261
all_data['TotalSF'] = all_data['TotalBsmtSF'] + all_data['1stFlrSF'] + all_data['2ndFlrSF']<create_dataframe>
class MyResNeXt(models.resnet.ResNet): def __init__(self, training=True): super(MyResNeXt, self ).__init__(block=models.resnet.Bottleneck, layers=[3, 4, 23, 3], groups=32, width_per_group=8) self.fc = nn.Linear(2048, 1)
Deepfake Detection Challenge
8,003,261
new_data = all_data.copy()<categorify>
checkpoint = torch.load("/kaggle/input/models-update/checkpoint_t.pth", map_location=gpu) model = MyResNeXt().to(gpu) model.load_state_dict(checkpoint) _ = model.eval() del checkpoint
Deepfake Detection Challenge
8,003,261
ordinal_label=['LandSlope','YearBuilt','YearRemodAdd', 'CentralAir','GarageYrBlt','PavedDrive', 'YrSold'] for field in ordinal_label: le = LabelEncoder() new_data[field] = le.fit_transform(new_data[field].values )<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 = isotropically_resize_image(face, input_size) resized_face = make_square_image(resized_face) if n < batch_size: x[n] = resized_face n += 1 else: print("WARNING: have %d faces but batch size is %d" %(n, batch_size)) if n > 0: x = torch.tensor(x, device=gpu ).float() x = x.permute(( 0, 3, 1, 2)) for i in range(len(x)) : x[i] = normalize_transform(x[i] / 255.) with torch.no_grad() : y_pred = model(x) y_pred = torch.sigmoid(y_pred.squeeze()) return y_pred[:n].mean().item() except Exception as e: print("Prediction error on video %s: %s" %(video_path, str(e))) return 0.5
Deepfake Detection Challenge
8,003,261
ordinal_features = [ 'MSSubClass','ExterQual','LotShape','BsmtQual','BsmtCond', 'BsmtExposure','BsmtFinType1', 'BsmtFinType2','HeatingQC', 'Functional', 'FireplaceQu','KitchenQual', 'GarageFinish', 'GarageQual','GarageCond', 'PoolQC', 'Fence' ] orders=[ ['20','30','40','45','50','60','70','75','80','85', '90','120','150','160','180','190'], ['Po','Fa','TA','Gd','Ex'], ['Reg','IR1' ,'IR2','IR3'], ['None','Fa','TA','Gd','Ex'], ['None','Po','Fa','TA','Gd','Ex'], ['None','No','Mn','Av','Gd'], ['None','Unf','LwQ', 'Rec','BLQ','ALQ' , 'GLQ' ], ['None','Unf','LwQ', 'Rec','BLQ','ALQ' , 'GLQ' ], ['Po','Fa','TA','Gd','Ex'], ['Sev','Maj2','Maj1','Mod','Min2','Min1','Typ'], ['None','Po','Fa','TA','Gd','Ex'], ['Fa','TA','Gd','Ex'], ['None','Unf','RFn','Fin'], ['None','Po','Fa','TA','Gd','Ex'], ['None','Po','Fa','TA','Gd','Ex'], ['None','Fa','Gd','Ex'], ['None','MnWw','GdWo','MnPrv','GdPrv'] ] for field in ordinal_features: new_data[field] = new_data[field].astype(str) for i in range(len(orders)) : ord_en = OrdinalEncoder(categories = [orders[i]]) new_data[ordinal_features[i]] = pd.DataFrame(ord_en.fit_transform(new_data[[ordinal_features[i]]]))<normalization>
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(predictions )
Deepfake Detection Challenge
8,003,261
scale = StandardScaler() new_data.drop("Id", axis = 1, inplace = True) numerical_cols = new_data._get_numeric_data().columns new_data[numerical_cols]= scale.fit_transform(new_data[numerical_cols] )<define_variables>
speed_test = False
Deepfake Detection Challenge
8,003,261
categorical_cols = list(set(new_data.columns)- set(numerical_cols)) categorical_cols<categorify>
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,003,261
new_data=pd.get_dummies(new_data )<import_modules>
predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
8,003,261
<compute_train_metric><EOS>
submission_df = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df.to_csv("submission.csv", index=False )
Deepfake Detection Challenge
7,972,294
<SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<choose_model_class>
!pip install.. /input/pytorchcv/pytorchcv-0.0.55-py2.py3-none-any.whl --quiet
Deepfake Detection Challenge
7,972,294
cv_scores = [] cv_std = [] kf = KFold(n_splits = 10, shuffle = True, random_state = 1) baseline_models = ['Linear_Reg.','Bayesian_Ridge_Reg.','LGBM_Reg.','SVR', 'Dec_Tree_Reg.','Random_Forest_Reg.', 'XGB_Reg.', 'Grad_Boost_Reg.','Cat_Boost_Reg.','Stacked_Reg.'] lreg = LinearRegression() score_lreg = cv_rmse(lreg) cv_scores.append(score_lreg.mean()) cv_std.append(score_lreg.std()) brr = BayesianRidge(compute_score=True) score_brr = cv_rmse(brr) cv_scores.append(score_brr.mean()) cv_std.append(score_brr.std()) l_gbm = LGBMRegressor(objective='regression') score_l_gbm = cv_rmse(l_gbm) cv_scores.append(score_l_gbm.mean()) cv_std.append(score_l_gbm.std()) svr = SVR() score_svr = cv_rmse(svr) cv_scores.append(score_svr.mean()) cv_std.append(score_svr.std()) dtr = DecisionTreeRegressor() score_dtr = cv_rmse(dtr) cv_scores.append(score_dtr.mean()) cv_std.append(score_dtr.std()) rfr = RandomForestRegressor() score_rfr = cv_rmse(rfr) cv_scores.append(score_rfr.mean()) cv_std.append(score_rfr.std()) xgb = xgb.XGBRegressor() score_xgb = cv_rmse(xgb) cv_scores.append(score_xgb.mean()) cv_std.append(score_xgb.std()) gbr = GradientBoostingRegressor() score_gbr = cv_rmse(gbr) cv_scores.append(score_gbr.mean()) cv_std.append(score_gbr.std()) catb = CatBoostRegressor() score_catb = cv_rmse(catb) cv_scores.append(score_catb.mean()) cv_std.append(score_catb.std()) stack_gen = StackingRegressor(regressors=(CatBoostRegressor() , LinearRegression() , BayesianRidge() , GradientBoostingRegressor()), meta_regressor = CatBoostRegressor() , use_features_in_secondary = True) score_stack_gen = cv_rmse(stack_gen) cv_scores.append(score_stack_gen.mean()) cv_std.append(score_stack_gen.std()) final_cv_score = pd.DataFrame(baseline_models, columns = ['Regressors']) final_cv_score['RMSE_mean'] = cv_scores final_cv_score['RMSE_std'] = cv_std<feature_engineering>
%matplotlib inline warnings.filterwarnings("ignore" )
Deepfake Detection Challenge
7,972,294
feat_imp = gbr.get_feature_importance(prettified=True) feat_imp<define_search_space>
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,972,294
<train_on_grid>
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" )
Deepfake Detection Challenge
7,972,294
<predict_on_test>
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,972,294
stack_gen.fit(train_X, train_Y) test_pred = stack_gen.predict(test_X) submission = pd.DataFrame(test_id, columns = ['Id']) test_pred = np.expm1(test_pred) submission['SalePrice'] = test_pred submission.head()<save_to_csv>
frames_per_video = 20 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,972,294
submission.loc[1089, 'SalePrice'] = 125000 submission.to_csv("result.csv", index = False, header = True )<filter>
input_size = 150
Deepfake Detection Challenge
7,972,294
submission[submission['Id'] == 2550]<set_options>
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )
Deepfake Detection Challenge
7,972,294
%matplotlib inline warnings.filterwarnings('ignore' )<load_from_csv>
model = get_model("xception", pretrained=False) model = nn.Sequential(*list(model.children())[:-1]) model[0].final_block.pool = nn.Sequential(nn.AdaptiveAvgPool2d(1)) class Head(torch.nn.Module): def __init__(self, in_f, out_f): super(Head, self ).__init__() self.f = nn.Flatten() self.l = nn.Linear(in_f, 512) self.d = nn.Dropout(0.5) self.o = nn.Linear(512, out_f) self.b1 = nn.BatchNorm1d(in_f) self.b2 = nn.BatchNorm1d(512) self.r = nn.ReLU() def forward(self, x): x = self.f(x) x = self.b1(x) x = self.d(x) x = self.l(x) x = self.r(x) x = self.b2(x) x = self.d(x) out = self.o(x) return out class FCN(torch.nn.Module): def __init__(self, base, in_f): super(FCN, self ).__init__() self.base = base self.h1 = Head(in_f, 1) def forward(self, x): x = self.base(x) return self.h1(x) net = [] model = FCN(model, 2048) model = model.cuda() model.load_state_dict(torch.load('.. /input/deepfake-xception/modelv2.pth')) net.append(model )
Deepfake Detection Challenge
7,972,294
train = pd.read_csv('.. /input/forest-cover-type-prediction/train.csv') train.head()<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 = isotropically_resize_image(face, input_size) resized_face = make_square_image(resized_face) if n < batch_size: x[n] = resized_face n += 1 else: print("WARNING: have %d faces but batch size is %d" %(n, batch_size)) if n > 0: x = torch.tensor(x, device=gpu ).float() x = x.permute(( 0, 3, 1, 2)) for i in range(len(x)) : x[i] = normalize_transform(x[i] / 255.) with torch.no_grad() : y_pred = model(x) y_pred = torch.sigmoid(y_pred.squeeze()) return y_pred[:n].mean().item() except Exception as e: print("Prediction error on video %s: %s" %(video_path, str(e))) return 0.5
Deepfake Detection Challenge
7,972,294
test = pd.read_csv('.. /input/forest-cover-type-prediction/test.csv') test.head()<feature_engineering>
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(predictions )
Deepfake Detection Challenge
7,972,294
test['Euclidian_Distance_To_Hydrology'] =(test['Horizontal_Distance_To_Hydrology']**2 + test['Vertical_Distance_To_Hydrology']**2)**0.5 test['Mean_Elevation_Vertical_Distance_Hydrology'] =(test['Elevation'] + test['Vertical_Distance_To_Hydrology'])/2 test['Mean_Distance_Hydrology_Firepoints'] =(test['Horizontal_Distance_To_Hydrology'] + test['Horizontal_Distance_To_Fire_Points'])/2 test['Mean_Distance_Hydrology_Roadways'] =(test['Horizontal_Distance_To_Hydrology'] + test['Horizontal_Distance_To_Roadways'])/2 test['Mean_Distance_Firepoints_Roadways'] =(test['Horizontal_Distance_To_Fire_Points'] + test['Horizontal_Distance_To_Roadways'])/2 test<feature_engineering>
speed_test = False
Deepfake Detection Challenge
7,972,294
train['Euclidian_Distance_To_Hydrology'] =(train['Horizontal_Distance_To_Hydrology']**2 + train['Vertical_Distance_To_Hydrology']**2)**0.5 train['Mean_Elevation_Vertical_Distance_Hydrology'] =(train['Elevation'] + train['Vertical_Distance_To_Hydrology'])/2 train['Mean_Distance_Hydrology_Firepoints'] =(train['Horizontal_Distance_To_Hydrology'] + train['Horizontal_Distance_To_Fire_Points'])/2 train['Mean_Distance_Hydrology_Roadways'] =(train['Horizontal_Distance_To_Hydrology'] + train['Horizontal_Distance_To_Roadways'])/2 train['Mean_Distance_Firepoints_Roadways'] =(train['Horizontal_Distance_To_Fire_Points'] + train['Horizontal_Distance_To_Roadways'])/2 train<data_type_conversions>
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,972,294
<data_type_conversions>
%%time model.eval() predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
7,972,294
<prepare_x_and_y><EOS>
submission_df = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df.to_csv("submission.csv", index=False )
Deepfake Detection Challenge
7,799,054
<SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<train_model>
%matplotlib inline
Deepfake Detection Challenge
7,799,054
scaler = StandardScaler() scaler.fit(X_num) X_num = scaler.transform(X_num) print(f'Categorical Shape: {X_cat.shape}') print(f'Numerical Shape: {X_num.shape}') <concatenate>
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,799,054
X = np.hstack(( X_num, X_cat)) print(X.shape )<define_variables>
print("PyTorch version:", torch.__version__) print("CUDA version:", torch.version.cuda) print("cuDNN version:", torch.backends.cudnn.version() )
Deepfake Detection Challenge
7,799,054
features = [ 'Elevation','Horizontal_Distance_To_Roadways', 'Horizontal_Distance_To_Hydrology', 'Vertical_Distance_To_Hydrology','Aspect','Slope','Euclidian_Distance_To_Hydrology', 'Mean_Elevation_Vertical_Distance_Hydrology','Mean_Distance_Hydrology_Firepoints', 'Mean_Distance_Hydrology_Roadways','Mean_Distance_Firepoints_Roadways' ]<save_to_csv>
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu
Deepfake Detection Challenge
7,799,054
y = train["Cover_Type"] X = pd.get_dummies(train[features]) X_test = pd.get_dummies(test[features]) model = ExtraTreesClassifier(n_estimators=1000, random_state=42, max_features='log2') model.fit(X,y) predictions = model.predict(X_test) output = pd.DataFrame({'Id': test.Id, 'Cover_Type': predictions}) output.to_csv('forest_cover_submission.csv', index=False) print("Your submission was successfully saved!" )<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,799,054
train_data =pd.read_csv('/kaggle/input/forest-cover-type-prediction/train.csv') train_data.head() <load_from_csv>
frames_per_video = frame_h * frame_l 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,799,054
test_data = pd.read_csv('/kaggle/input/forest-cover-type-prediction/test.csv') test_data.head()<count_values>
input_size = 224
Deepfake Detection Challenge
7,799,054
train_data['Cover_Type'].value_counts()<prepare_x_and_y>
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )
Deepfake Detection Challenge
7,799,054
X = train_data.drop(labels =['Id','Cover_Type'],axis=1) Y = train_data['Cover_Type'] Y<import_modules>
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,799,054
from sklearn.model_selection import train_test_split<import_modules>
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,799,054
from sklearn.model_selection import train_test_split<split>
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 = isotropically_resize_image(face, input_size) resized_face = make_square_image(resized_face) if n < batch_size: x[n] = resized_face n += 1 else: print("WARNING: have %d faces but batch size is %d" %(n, batch_size)) if n > 0: x = torch.tensor(x, device=gpu ).float() x = x.permute(( 0, 3, 1, 2)) for i in range(len(x)) : x[i] = normalize_transform(x[i] / 255.) with torch.no_grad() : y_pred = model(x) y_pred = torch.sigmoid(y_pred.squeeze()) return y_pred[:n].mean().item() except Exception as e: print("Prediction error on video %s: %s" %(video_path, str(e))) return 0.5
Deepfake Detection Challenge
7,799,054
x_train,x_valid,y_train,y_valid = train_test_split(X,Y,random_state = 21 )<import_modules>
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(predictions )
Deepfake Detection Challenge
7,799,054
from sklearn.ensemble import RandomForestClassifier<train_model>
speed_test = False
Deepfake Detection Challenge
7,799,054
rfc = RandomForestClassifier(n_estimators = 80) rfc.fit(x_train,y_train )<compute_test_metric>
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,799,054
rfc.score(x_valid,y_valid )<predict_on_test>
predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
7,799,054
<prepare_output><EOS>
submission_df = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df.to_csv("submission.csv", index=False )
Deepfake Detection Challenge
7,690,202
<SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<prepare_output>
%matplotlib inline
Deepfake Detection Challenge
7,690,202
Submission['Id'] = test_data['Id'] Submission.set_index('Id',inplace = True )<save_to_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,690,202
Submission.to_csv('Submission.csv' )<load_from_csv>
print("PyTorch version:", torch.__version__) print("CUDA version:", torch.version.cuda) print("cuDNN version:", torch.backends.cudnn.version() )
Deepfake Detection Challenge
7,690,202
train_data=pd.read_csv('/kaggle/input/forest-cover-type-prediction/train.csv') train_data<load_from_csv>
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu
Deepfake Detection Challenge
7,690,202
test_data=pd.read_csv('/kaggle/input/forest-cover-type-prediction/test.csv') test_data.head()<count_values>
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,690,202
train_data['Cover_Type'].value_counts() <prepare_x_and_y>
frames_per_video = 17 video_reader = VideoReader() video_read_fn = lambda x: video_reader.read_frames(x, num_frames=frames_per_video) face_extractor = FaceExtractor(video_read_fn, facedet )
Deepfake Detection Challenge
7,690,202
X=train_data.drop(labels=['Id','Cover_Type'],axis=1) y=train_data['Cover_Type'] X_train,X_value,y_train,y_value=train_test_split(X,y,random_state=40) print(X_train.shape,y_train.shape) print(X_value.shape,y_value.shape) <train_model>
input_size = 224
Deepfake Detection Challenge
7,690,202
RFC=RandomForestClassifier(n_estimators=70) RFC.fit(X_train,y_train) <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
7,690,202
RFC.score(X_value,y_value) <predict_on_test>
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,690,202
predict=RFC.predict(test_data.drop(labels=['Id'],axis=1)) Submission=pd.DataFrame(data=predict,columns=['Cover_Type']) Submission.head()<prepare_output>
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,690,202
Submission['Id']=test_data['Id'] Submission.set_index('Id',inplace=True) Submission.head() <save_to_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 = isotropically_resize_image(face, input_size) resized_face = make_square_image(resized_face) if n < batch_size: x[n] = resized_face n += 1 else: print("WARNING: have %d faces but batch size is %d" %(n, batch_size)) if n > 0: x = torch.tensor(x, device=gpu ).float() x = x.permute(( 0, 3, 1, 2)) for i in range(len(x)) : x[i] = normalize_transform(x[i] / 255.) with torch.no_grad() : y_pred = model(x) y_pred = torch.sigmoid(y_pred.squeeze()) return y_pred[:n].mean().item() except Exception as e: print("Prediction error on video %s: %s" %(video_path, str(e))) return 0.5
Deepfake Detection Challenge
7,690,202
Submission.to_csv('Submission.csv') <import_modules>
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(predictions )
Deepfake Detection Challenge
7,690,202
import tensorflow as tf import numpy as np import pandas as pd <load_from_csv>
speed_test = False
Deepfake Detection Challenge
7,690,202
training = pd.read_csv('.. /input/digit-recognizer/train.csv' )<prepare_x_and_y>
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,690,202
x_train, y_train = training.iloc[:, 1:], training.iloc[:, 0:1]<feature_engineering>
predictions = predict_on_video_set(test_videos, num_workers=4 )
Deepfake Detection Challenge
7,690,202
<choose_model_class><EOS>
submission_df = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df.to_csv("submission.csv", index=False )
Deepfake Detection Challenge