kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
14,194,052 | def get_bureau_processed(bureau):
bureau['BUREAU_ENDDATE_FACT_DIFF'] = bureau['DAYS_CREDIT_ENDDATE'] - bureau['DAYS_ENDDATE_FACT']
bureau['BUREAU_CREDIT_FACT_DIFF'] = bureau['DAYS_CREDIT'] - bureau['DAYS_ENDDATE_FACT']
bureau['BUREAU_CREDIT_ENDDATE_DIFF'] = bureau['DAYS_CREDIT'] - bureau['DAYS_CREDIT_ENDDATE']
bureau['... | corr_feature = ['cont6','cont7','cont8','cont9','cont10','cont11','cont12','cont13']
corr_in = train[corr_feature] | Tabular Playground Series - Jan 2021 |
14,194,052 | def get_bureau_day_amt_agg(bureau):
bureau_agg_dict = {
'SK_ID_BUREAU':['count'],
'DAYS_CREDIT':['min', 'max', 'mean'],
'CREDIT_DAY_OVERDUE':['min', 'max', 'mean'],
'DAYS_CREDIT_ENDDATE':['min', 'max', 'mean'],
'DAYS_ENDDATE_FACT':['min', 'max', 'mean'],
'AMT_CREDIT_MAX_OVERDUE': ['max', 'mean'],
'AMT_CREDIT_SUM': ['ma... | train = train.drop(284103 ) | Tabular Playground Series - Jan 2021 |
14,194,052 | def get_bureau_active_agg(bureau):
cond_active = bureau['CREDIT_ACTIVE'] == 'Active'
bureau_active_grp = bureau[cond_active].groupby(['SK_ID_CURR'])
bureau_agg_dict = {
'SK_ID_BUREAU':['count'],
'DAYS_CREDIT':['min', 'max', 'mean'],
'CREDIT_DAY_OVERDUE':['min', 'max', 'mean'],
'DAYS_CREDIT_ENDDATE':['min', 'max', 'mea... | target = train.pop('target')
X_train, X_test, y_train, y_test = train_test_split(train, target, train_size=0.60 ) | Tabular Playground Series - Jan 2021 |
14,194,052 | def get_bureau_bal_agg(bureau, bureau_bal):
bureau_bal = bureau_bal.merge(bureau[['SK_ID_CURR', 'SK_ID_BUREAU']], on='SK_ID_BUREAU', how='left')
bureau_bal['BUREAU_BAL_IS_DPD'] = bureau_bal['STATUS'].apply(lambda x: 1 if x in['1','2','3','4','5'] else 0)
bureau_bal['BUREAU_BAL_IS_DPD_OVER120'] = bureau_bal['STATUS'].... | model = XGBRegressor(n_estimators=500, learning_rate=0.05, n_jobs=4)
model.fit(X_train, y_train,
early_stopping_rounds=5,
eval_set=[(X_test, y_test)],
verbose=False ) | Tabular Playground Series - Jan 2021 |
14,194,052 | def get_bureau_agg(bureau, bureau_bal):
bureau = get_bureau_processed(bureau)
bureau_day_amt_agg = get_bureau_day_amt_agg(bureau)
bureau_active_agg = get_bureau_active_agg(bureau)
bureau_bal_agg = get_bureau_bal_agg(bureau, bureau_bal)
bureau_agg = bureau_day_amt_agg.merge(bureau_active_agg, on='SK_ID_CURR', how='l... | y_pred = model.predict(X_test)
score = mean_squared_error(y_test, y_pred, squared=False)
print(score ) | Tabular Playground Series - Jan 2021 |
14,194,052 | <categorify><EOS> | submission['target'] = model.predict(test)
submission.to_csv('xgb_regressor.csv' ) | Tabular Playground Series - Jan 2021 |
14,309,939 | <SOS> metric: RMSE Kaggle data source: tabular-playground-series-jan-2021<categorify> | warnings.filterwarnings("ignore" ) | Tabular Playground Series - Jan 2021 |
14,309,939 | apps_all = get_apps_all_encoded(apps_all)
apps_all_train, apps_all_test = get_apps_all_train_test(apps_all )<load_pretrained> | train = pd.read_csv('.. /input/tabular-playground-series-jan-2021/train.csv')
test = pd.read_csv('.. /input/tabular-playground-series-jan-2021/test.csv')
sub = pd.read_csv('.. /input/tabular-playground-series-jan-2021/sample_submission.csv' ) | Tabular Playground Series - Jan 2021 |
14,309,939 | clf = train_apps_all(apps_all_train )<save_to_csv> | features = ['cont1', 'cont2', 'cont3', 'cont4', 'cont5', 'cont6', 'cont7',
'cont8', 'cont9', 'cont10', 'cont11', 'cont12', 'cont13', 'cont14'] | Tabular Playground Series - Jan 2021 |
14,309,939 | preds = clf.predict_proba(apps_all_test.drop(['SK_ID_CURR'], axis=1)) [:, 1 ]
apps_all_test['TARGET'] = preds
apps_all_test[['SK_ID_CURR', 'TARGET']].to_csv('bureau_baseline_04.csv', index=False )<set_options> | X = train_01[features]
y = train_01['target'] | Tabular Playground Series - Jan 2021 |
14,309,939 | tqdm().pandas()
pd_ctx = pd.option_context('display.max_colwidth', 100)
pd.set_option('display.float_format', lambda x: '%.3f' % x )<load_from_csv> | params_xgb = {'lambda': 1,
'alpha': 0,
'colsample_bytree': 1,
'subsample': 1,
'learning_rate': 0.05,
'max_depth': 6,
'min_child_weight': 3,
'random_state': 48} | Tabular Playground Series - Jan 2021 |
14,309,939 | TRAIN_FILE = '/kaggle/input/quora-insincere-questions-classification/train.csv'
TEST_FILE = '/kaggle/input/quora-insincere-questions-classification/test.csv'
df = pd.read_csv(TRAIN_FILE)
df.info()
test_df = pd.read_csv(TEST_FILE)
with pd_ctx:
print("Sincere question")
display(df[df['target'] == 0].head())
print("In... | model_xgb = xgb.XGBRegressor(**params_xgb ) | Tabular Playground Series - Jan 2021 |
14,309,939 | def statistic(df):
stats = pd.DataFrame() ;
stats['question_text'] = df['question_text']
stats['sp_char_words'] = stats['question_text'].str.findall(r'[^a-zA-Z0-9 ]' ).str.len()
stats['num_capital'] = stats['question_text'].progress_map(lambda x: len([c for c in str(x)if c.isupper() ]))
stats['num_numerics'] = stats['q... | param_range = np.linspace(0, 1, 10)
param_range | Tabular Playground Series - Jan 2021 |
14,309,939 | contractions= {"i'm": 'i am',"i'm'a": 'i am about to',"i'm'o": 'i am going to',"i've": 'i have',"i'll": 'i will',"i'll've": 'i will have',"i'd": 'i would',"i'd've": 'i would have',"Whatcha": 'What are you',"amn't": 'am not',"ain't": 'are not',"aren't": 'are not',"'cause": 'because',"can't": 'can not',"can't've": 'can n... | param_name = "alpha" | Tabular Playground Series - Jan 2021 |
14,309,939 | OOV_TOKEN = '<OOV>'
def create_tokenizer(docs):
tokenizer = Tokenizer(oov_token=OOV_TOKEN)
tokenizer.fit_on_texts(list(docs))
print("Size of vocabulary: ", len(tokenizer.word_index))
return tokenizer
tokenizer = create_tokenizer(sample['clean'])
print("20 từ đầu tiên trong từ điển:")
list(tokenizer.word_index.items(... | param_name = "lambda" | Tabular Playground Series - Jan 2021 |
14,309,939 | word_sequences = tokenizer.texts_to_sequences(sample['clean'])
print("Length of 20 first word_sequences:")
print(list(map(lambda x: len(x),word_sequences[:20])))
print("
20 first word_sequences:")
for sequence in word_sequences[:20]:
print(sequence )<categorify> | param_range = np.linspace(0.1, 1, 10)
param_range | Tabular Playground Series - Jan 2021 |
14,309,939 | MAX_SENTENCE_LENGTH = 60
PADDING_TYPE = 'post'
TRUNCATE_TYPE = 'post'
def create_sequence(tokenizer, docs):
word_sequeces = tokenizer.texts_to_sequences(docs)
padded_word_sequences = pad_sequences(word_sequeces, maxlen=MAX_SENTENCE_LENGTH, padding=PADDING_TYPE, truncating=TRUNCATE_TYPE)
return padded_word_sequences
p... | param_name = 'colsample_bytree' | Tabular Playground Series - Jan 2021 |
14,309,939 | trainY = train.target
print("Clean train question")
trainX_text = apply_clean_text(train.question_text)
print("Clean test question")
testX_text = apply_clean_text(test_df.question_text )<split> | param_name = 'subsample' | Tabular Playground Series - Jan 2021 |
14,309,939 | X_train, X_val, y_train, y_val = train_test_split(trainX_text, trainY, test_size=0.2, random_state=123 )<choose_model_class> | param_name = 'n_estimators' | Tabular Playground Series - Jan 2021 |
14,309,939 | EMBEDDING_DIM = 300
learning_rate = 0.001
def createModel_bidirectional_LSTM_GRU(features,embedding_matrix = None):
output_bias = Constant(np.log([len(data_pos)/len(data_neg)]))
x_input = Input(shape=(MAX_SENTENCE_LENGTH))
if not(embedding_matrix is None):
embedding = Embedding(features, EMBEDDING_DIM, input_length=MAX... | param_range = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000] | Tabular Playground Series - Jan 2021 |
14,309,939 | def best_threshold(y_train,train_preds):
tmp = [0,0,0]
delta = 0
for tmp[0] in tqdm(np.arange(0.1, 0.9, 0.01)) :
tmp[1] = metrics.f1_score(y_train, np.array(train_preds)>tmp[0])
if tmp[1] > tmp[2]:
delta = tmp[0]
tmp[2] = tmp[1]
return delta, tmp[2]<choose_model_class> | X = train[features]
y = train['target'] | Tabular Playground Series - Jan 2021 |
14,309,939 | strategy = None
try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect()
strategy = tf.distribute.TPUStrategy(tpu)
print('Use TPU')
except ValueError:
if len(tf.config.list_physical_devices('GPU')) > 0:
strategy = tf.distribute.MirroredStrategy()
print('Use GPU')
else:
strategy = tf.distribute.get_stra... | def objective(trial,data=X,target=y):
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, 1),
'alpha': trial.suggest_loguniform('alpha', 1e-3, 1),
'colsample_bytree': trial.suggest_categ... | Tabular Playground Series - Jan 2021 |
14,309,939 | class_weight = {
0: 1,
1: 3,
}
batch_size = 1024
n_epochs = 30
early_stopping=tf.keras.callbacks.EarlyStopping(
monitor="val_loss",
patience=3,
mode="min",
restore_best_weights=True
)
reduce_lr=tf.keras.callbacks.ReduceLROnPlateau(
monitor="val_loss",
factor=0.2,
patience=2,
verbose=1,
mode="auto"
)
my_callbacks=... | study = optuna.create_study(direction='minimize')
study.optimize(objective, n_trials=50)
print('Number of finished trials:', len(study.trials))
print('Best trial:', study.best_trial.params ) | Tabular Playground Series - Jan 2021 |
14,309,939 | with strategy.scope() :
threshold, f1_score, val_pred, test_pred = train_model_and_predict(X_train, y_train, X_val, y_val, testX_text)
print(metrics.classification_report(y_val,(val_pred>threshold ).astype(int)) )<feature_engineering> | study.best_trial.params | Tabular Playground Series - Jan 2021 |
14,309,939 | def get_coefs(word, *arr):
return word, np.asarray(arr, dtype='float32')
def get_lines_count(file_name):
return sum(1 for _ in open(file_name, encoding="utf8", errors='ignore'))
def load_vec(file_name):
return dict(
get_coefs(*o.split(" "))
for o in tqdm(open(
file_name, encoding="utf8", errors='ignore'),
total=get_... | Best_params_xgb = {'lambda': 0.0014311714230223992,
'alpha': 0.008850567457271379,
'colsample_bytree': 0.3,
'subsample': 1.0,
'learning_rate': 0.01,
'max_depth': 20,
'min_child_weight': 245,
'n_estimators': 4000,
'random_state': 48,
'tree_method':'gpu_hist'} | Tabular Playground Series - Jan 2021 |
14,309,939 | EMBEDDING_DIM = 300
ps = PorterStemmer()
lc = LancasterStemmer()
sb = SnowballStemmer('english')
def load_embedding(word2vec, word2index):
oov_count = 0
vocab_count = 0
vocab_size = len(word2index)
embedding_weights = np.zeros(( vocab_size+1, EMBEDDING_DIM))
unknown_vector = np.zeros(( EMBEDDING_DIM,), dtype=np.float... | train_x, test_x, train_y, test_y = train_test_split(X, y, test_size=0.15,random_state=42)
model_xgb = xgb.XGBRegressor(**Best_params_xgb)
model_xgb.fit(train_x,train_y,eval_set=[(test_x,test_y)],early_stopping_rounds=100,verbose=False ) | Tabular Playground Series - Jan 2021 |
14,309,939 | GLOVE_FILE = 'glove.840B.300d/glove.840B.300d.txt'
!unzip -n /kaggle/input/quora-insincere-questions-classification/embeddings.zip {GLOVE_FILE} -d.
print('loading glove_vec')
glove_vec = load_vec(GLOVE_FILE )<predict_on_test> | preds = model_xgb.predict(test_x)
rmse = mean_squared_error(test_y, preds,squared=False)
rmse | Tabular Playground Series - Jan 2021 |
14,309,939 | with strategy.scope() :
glove_threshold, glove_f1_score, glove_val_pred, glove_test_pred = train_model_and_predict(X_train, y_train, X_val, y_val, testX_text, glove_vec)
print(metrics.classification_report(y_val,(glove_val_pred>glove_threshold ).astype(int)) )<set_options> | test_X = test[features] | Tabular Playground Series - Jan 2021 |
14,309,939 | del glove_vec
gc.collect()<load_pretrained> | preds = model_xgb.predict(test_X ) | Tabular Playground Series - Jan 2021 |
14,309,939 | PARA_FILE = 'paragram_300_sl999/paragram_300_sl999.txt'
!unzip -n /kaggle/input/quora-insincere-questions-classification/embeddings.zip {PARA_FILE} -d.
print('loading para_vec')
para_vec = load_vec(PARA_FILE )<predict_on_test> | sub['target']=preds
sub.to_csv('submission.csv', index=False ) | Tabular Playground Series - Jan 2021 |
14,309,939 | with strategy.scope() :
para_threshold, para_f1_score, para_val_pred, para_test_pred = train_model_and_predict(X_train, y_train, X_val, y_val, testX_text, para_vec)
print(metrics.classification_report(y_val,(para_val_pred>para_threshold ).astype(int)) )<set_options> | X = train_01[features]
y = train_01['target'] | Tabular Playground Series - Jan 2021 |
14,309,939 | del para_vec
gc.collect()<load_pretrained> | params_lgb = {'num_leaves': 31,
'min_data_in_leaf': 20,
'min_child_weight': 0.001,
'max_depth': -1,
'learning_rate': 0.005,
'bagging_fraction': 1,
'feature_fraction': 1,
'lambda_l1': 0,
'lambda_l2': 0,
'random_state': 48} | Tabular Playground Series - Jan 2021 |
14,309,939 | WIKI_FILE = 'wiki-news-300d-1M/wiki-news-300d-1M.vec'
!unzip -n /kaggle/input/quora-insincere-questions-classification/embeddings.zip {WIKI_FILE} -d.
print('loading wiki_vec')
wiki_vec = load_vec(WIKI_FILE )<predict_on_test> | model_lgb = lgb.LGBMRegressor(**params_lgb ) | Tabular Playground Series - Jan 2021 |
14,309,939 | with strategy.scope() :
wiki_threshold, wiki_f1_score, wiki_val_pred, wiki_test_pred = train_model_and_predict(X_train, y_train, X_val, y_val, testX_text, wiki_vec)
print(metrics.classification_report(y_val,(wiki_val_pred>wiki_threshold ).astype(int)) )<set_options> | param_range = np.linspace(0, 1, 10)
param_range | Tabular Playground Series - Jan 2021 |
14,309,939 | del wiki_vec
gc.collect()<compute_test_metric> | param_name = 'lambda_l1' | Tabular Playground Series - Jan 2021 |
14,309,939 | val_prod = np.zeros(( len(X_val),), dtype=np.float32)
val_prod += 1/3 * np.squeeze(glove_val_pred)
val_prod += 1/3 * np.squeeze(para_val_pred)
val_prod += 1/3 *np.squeeze(wiki_val_pred)
threshold_global, f1_global = best_threshold(y_val, val_prod)
print(metrics.classification_report(y_val,(val_prod>threshold_globa... | param_name = 'lambda_l2' | Tabular Playground Series - Jan 2021 |
14,309,939 | pred_prob = np.zeros(( len(testX_text),), dtype=np.float32)
pred_prob += 1/3 * np.squeeze(glove_test_pred)
pred_prob += 1/3 * np.squeeze(para_test_pred)
pred_prob += 1/3 * np.squeeze(wiki_test_pred)
y_test_pre=(( pred_prob>threshold_global ).astype(int))
submit = pd.DataFrame()
submit["qid"]=test_df.qid
submit["pre... | param_name = 'feature_fraction' | Tabular Playground Series - Jan 2021 |
14,309,939 | import numpy as np
import pandas as pd
import os
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
import pandas as pd
import matplotlib.pyplot as plt<load_from_csv> | param_name = 'bagging_fraction' | Tabular Playground Series - Jan 2021 |
14,309,939 | train = np.loadtxt(open('/kaggle/input/digit-recognizer/train.csv', 'r'), delimiter=',', skiprows=1, dtype='float32')
test = np.loadtxt(open('/kaggle/input/digit-recognizer/test.csv', 'r'), delimiter=',', skiprows=1, dtype='float32')
train_images = train[:, 1:].reshape(( train.shape[0], 28, 28, 1)) / 255.0
train_labe... | param_name = 'n_estimators'
| Tabular Playground Series - Jan 2021 |
14,309,939 | augmentation_layer = tf.keras.Sequential([
tf.keras.layers.experimental.preprocessing.RandomRotation(0.1, input_shape=(28, 28, 1)) ,
tf.keras.layers.experimental.preprocessing.RandomZoom(( 0.2, 0.2)) ,
] )<categorify> | param_range = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000] | Tabular Playground Series - Jan 2021 |
14,309,939 | for i in range(5):
new_img = augmentation_layer(train_images[np.random.randint(train_images.shape[0])] ).numpy()
plt.imshow(new_img.reshape(( 28, 28)))
plt.show()<choose_model_class> | X = train[features]
y = train['target'] | Tabular Playground Series - Jan 2021 |
14,309,939 | model = Sequential([
tf.keras.layers.Input(( 28, 28, 1)) ,
augmentation_layer,
Conv2D(32, 3, activation='relu', padding="same"),
MaxPooling2D(2),
Conv2D(64, 3, activation='relu', padding="same"),
MaxPooling2D(2),
Conv2D(64, 3, activation='relu', padding="same"),
MaxPooling2D(2),
Flatten() ,
Dropout(0.3),
Dense(128, act... | def objective_lgb(trial,data=X,target=y):
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_l2': trial.suggest_loguniform('lambda_l2', 1e-3, 1),
'lambda_l1': trial.suggest_loguniform('lambda_l1', 1e-3, 1),
'feature_framcion': t... | Tabular Playground Series - Jan 2021 |
14,309,939 | model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)<train_model> | study = optuna.create_study(direction='minimize')
study.optimize(objective_lgb, n_trials=50)
print('Number of finished trials:', len(study.trials))
print('Best trial:', study.best_trial.params ) | Tabular Playground Series - Jan 2021 |
14,309,939 | history = model.fit(train_images, train_labels, epochs=100 )<choose_model_class> | study.best_trial.params | Tabular Playground Series - Jan 2021 |
14,309,939 | predition_model = tf.keras.Sequential()
for layer in model.layers:
if layer != augmentation_layer:
predition_model.add(layer)
predition_model.compile(loss="sparse_categorical_crossentropy", optimizer="adam" )<predict_on_test> | Best_params_lgb = {'lambda_l2': 0.013616569506899653,
'lambda_l1': 0.006495842188985166,
'feature_framcion': 0.3,
'bagging_framcion': 0.3,
'learning_rate': 0.015,
'num_leaves': 200,
'max_depth': 25,
'min_data_in_leaf': 30,
'min_child_weight': 0.001,
'n_estimators': 3000,
'random_state': 48,
'tree_method':'gpu_hist'} | Tabular Playground Series - Jan 2021 |
14,309,939 | test_labels = np.argmax(predition_model.predict(test_images), axis=-1)
print(test_labels.shape )<save_to_csv> | train_x, test_x, train_y, test_y = train_test_split(X, y, test_size=0.15,random_state=42)
model_lgb = lgb.LGBMRegressor(**Best_params_lgb)
model_lgb.fit(train_x,train_y,eval_set=[(test_x,test_y)],
early_stopping_rounds=100,verbose=False ) | Tabular Playground Series - Jan 2021 |
14,309,939 | image_ids = np.arange(1, test_labels.shape[0]+1)
result = np.concatenate(( image_ids.reshape(image_ids.shape[0], 1), test_labels.reshape(test_labels.shape[0], 1)) , axis=1)
df = pd.DataFrame(result, columns=["ImageId", "Label"], dtype='int')
df.to_csv("submission.csv", index=False )<set_options> | preds = model_lgb.predict(test_x)
rmse = mean_squared_error(test_y, preds,squared=False)
rmse | Tabular Playground Series - Jan 2021 |
14,309,939 | <load_from_csv><EOS> | test_X = test[features]
preds = model_lgb.predict(test_X)
sub['target']=preds
sub.to_csv('submission_lgb.csv', index=False ) | Tabular Playground Series - Jan 2021 |
8,682,100 | HorizontalFlip, VerticalFlip, IAAPerspective, ShiftScaleRotate, CLAHE, RandomRotate90,
Transpose, ShiftScaleRotate, Blur, OpticalDistortion, GridDistortion, HueSaturationValue,
IAAAdditiveGaussianNoise, GaussNoise, MotionBlur, MedianBlur, IAAPiecewiseAffine, RandomResizedCrop,
IAASharpen, IAAEmboss, RandomBrightnessCon... | !pip install.. /input/efficientnet/efficientnet-1.0.0-py3-none-any.whl | Deepfake Detection Challenge |
8,682,100 | class CassvaImgClassifier(nn.Module):
def __init__(self, model_arch, n_class, pretrained=False):
super().__init__()
self.model = timm.create_model(model_arch, pretrained=pretrained)
n_features = self.model.classifier.in_features
self.model.classifier = nn.Linear(n_features, n_class)
def forward(self, x):
x = self.mod... | import pandas as pd
import tensorflow as tf
import cv2
import glob
from tqdm.notebook import tqdm
import numpy as np
import os
import efficientnet.keras as efn
from keras.layers import *
from keras import Model
import matplotlib.pyplot as plt
import time | Deepfake Detection Challenge |
8,682,100 | if __name__ == '__main__':
seed_everything(CFG['seed'])
folds = StratifiedKFold(n_splits=CFG['fold_num'] ).split(np.arange(train.shape[0]), train.label.values)
for fold,(trn_idx, val_idx)in enumerate(folds):
if fold > 0:
break
print('Inference fold {} started'.format(fold))
valid_ = train.loc[val_idx,:].reset_index(d... | 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,682,100 | test['label'] = np.argmax(tst_preds, axis=1)
test.head()<save_to_csv> | cm = detection_graph.as_default()
cm.__enter__() | Deepfake Detection Challenge |
8,682,100 | test.to_csv('submission.csv', index=False )<set_options> | config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
sess=tf.compat.v1.Session(graph=detection_graph, config=config)
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
boxes_tensor = detection_graph.get_tensor_by_name('detection_boxes:0')
scores_tensor = detection_graph.get_ten... | Deepfake Detection Challenge |
8,682,100 | pd.set_option('display.max_columns', 100)
pd.set_option('display.max_rows', 100)
<load_pretrained> | def get_img(images):
global boxes,scores,num_detections
im_heights,im_widths=[],[]
imgs=[]
for image in images:
(im_height,im_width)=image.shape[:-1]
imgs.append(image)
im_heights.append(im_height)
im_widths.append(im_widths)
imgs=np.array(imgs)
(boxes, scores_)= sess.run(
[boxes_tensor, scores_tensor],
feed_dict=... | Deepfake Detection Challenge |
8,682,100 | CACHE_PATH = '.. /input/mlp012003weights'
def save_pickle(dic, save_path):
with open(save_path, 'wb')as f:
pickle.dump(dic, f)
def load_pickle(load_path):
with open(load_path, 'rb')as f:
message_dict = pickle.load(f)
return message_dict
f_mean = np.load(f'{CACHE_PATH}/f_mean_online.npy' )<define_variables> | os.mkdir('./videos/')
for x in tqdm(glob.glob('.. /input/deepfake-detection-challenge/test_videos/*.mp4')) :
try:
filename=x.replace('.. /input/deepfake-detection-challenge/test_videos/','' ).replace('.mp4','.jpg')
a=detect_video(x,0)
if a is None:
continue
cv2.imwrite('./videos/'+filename,a)
except Exception as er... | Deepfake Detection Challenge |
8,682,100 | feat_cols = [f'feature_{i}' for i in range(130)]
all_feat_cols = [col for col in feat_cols]
all_feat_cols.extend(['cross_41_42_43', 'cross_1_2'])
target_cols = ['action', 'action_1', 'action_2', 'action_3', 'action_4']<import_modules> | os.mkdir('./videos_2/')
for x in tqdm(glob.glob('.. /input/deepfake-detection-challenge/test_videos/*.mp4')) :
try:
filename=x.replace('.. /input/deepfake-detection-challenge/test_videos/','' ).replace('.mp4','.jpg')
a=detect_video(x,95)
if a is None:
continue
cv2.imwrite('./videos_2/'+filename,a)
except Exception ... | Deepfake Detection Challenge |
8,682,100 | import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torch.nn import CrossEntropyLoss, MSELoss
from torch.nn.modules.loss import _WeightedLoss
import torch.nn.functional as F<choose_model_class> | bottleneck = efn.EfficientNetB1(weights=None,include_top=False,pooling='avg')
inp=Input(( 10,240,240,3))
x=TimeDistributed(bottleneck )(inp)
x = LSTM(128 )(x)
x = Dense(64, activation='elu' )(x)
x = Dense(1,activation='sigmoid' )(x ) | Deepfake Detection Challenge |
8,682,100 | class Model(nn.Module):
def __init__(self):
super(Model, self ).__init__()
self.batch_norm0 = nn.BatchNorm1d(len(all_feat_cols))
self.dropout0 = nn.Dropout(0.9)
dropout_rate = 0.9
hidden_size = 256
self.dense1 = nn.Linear(len(all_feat_cols), hidden_size)
self.batch_norm1 = nn.BatchNorm1d(hidden_size)
self.dropout1 =... | model=Model(inp,x)
weights = ['.. /input/deepfake-20/saved-model-01-0.06.hdf5', '.. /input/deepfake-20/saved-model-02-0.05.hdf5', '.. /input/model-epoch-3/saved-model-03-0.06.hdf5','.. /input/model-02/saved-model-01-0.06.hdf5']*2
sub_file = ['submission_'+str(i)+'.csv' for i in range(1,9)]
video = ['./videos/']*4+['./... | Deepfake Detection Challenge |
8,682,100 | if torch.cuda.is_available() :
print('using device: cuda')
device = torch.device("cuda:0")
else:
print('using device: cpu')
device = torch.device('cpu' )<load_pretrained> | !rm -r videos
!rm -r videos_2 | Deepfake Detection Challenge |
8,682,100 | NFOLDS = 5
model_list = []
tmp = np.zeros(len(feat_cols))
for _fold in range(NFOLDS):
torch.cuda.empty_cache()
model = Model()
model.to(device)
model_weights = f"{CACHE_PATH}/online_model{_fold}.pth"
model.load_state_dict(torch.load(model_weights, map_location=device))
model.eval()
model_list.append(model )<import_mod... | df1 = pd.read_csv('submission_1.csv' ).set_index('filename' ).transpose().to_dict()
df2 = pd.read_csv('submission_2.csv' ).set_index('filename' ).transpose().to_dict()
df3 = pd.read_csv('submission_3.csv' ).set_index('filename' ).transpose().to_dict()
df4 = pd.read_csv('submission_4.csv' ).set_index('filename' ).transp... | Deepfake Detection Challenge |
8,682,100 | <choose_model_class><EOS> | !rm submission_1.csv
!rm submission_2.csv
!rm submission_3.csv
!rm submission_4.csv
!rm submission_5.csv
!rm submission_6.csv
!rm submission_7.csv
!rm submission_8.csv | Deepfake Detection Challenge |
8,125,767 | <SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<load_pretrained> | %matplotlib inline
warnings.filterwarnings("ignore" ) | Deepfake Detection Challenge |
8,125,767 | clf.save(f'model.h5')
clf.load_weights('.. /input/jane-street-with-keras-nn-overfit/model.h5')
<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"])
frame_h = 5
frame_l = 5
len(test_videos ) | Deepfake Detection Challenge |
8,125,767 | copyfile(src = ".. /input/mlp-model-130-features-200-epoch/Models.py", dst = ".. /working/Models.py")
pd.set_option('display.max_columns', 100)
pd.set_option('display.max_rows', 100)
DATA_PATH = '.. /input/jane-street-market-prediction/'
Model_Root = '.. /input/mlp-model-130-features-200-epoch/'
NFOLDS = 5
TRAIN = F... | print("PyTorch version:", torch.__version__)
print("CUDA version:", torch.version.cuda)
print("cuDNN version:", torch.backends.cudnn.version() ) | Deepfake Detection Challenge |
8,125,767 | SEED = 1111
np.random.seed(SEED)
def create_mlp(
num_columns, num_labels, hidden_units, dropout_rates, label_smoothing, learning_rate
):
inp = tf.keras.layers.Input(shape=(num_columns,))
x = tf.keras.layers.BatchNormalization()(inp)
x = tf.keras.layers.Dropout(dropout_rates[0] )(x)
for i in range(len(hidden_units)... | gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
gpu | Deepfake Detection Challenge |
8,125,767 | if True:
env = janestreet.make_env()
env_iter = env.iter_test()
for(test_df, pred_df)in tqdm(env_iter):
if test_df['weight'].item() > 0:
x_tt = test_df.loc[:, feat_cols].values
if np.isnan(x_tt.sum()):
x_tt = np.nan_to_num(x_tt)+ np.isnan(x_tt)* f_mean
cross_41_42_43 = x_tt[:, 41] + x_tt[:, 42] + x_tt[:, 43]
cross_1_2 ... | 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,125,767 | pd.set_option('display.max_columns', 100)
pd.set_option('display.max_rows', 100)
DATA_PATH = '.. /input/jane-street-market-prediction/'
NFOLDS = 5
TRAIN = False
CACHE_PATH = '.. /input/mlp012003weights'
def save_pickle(dic, save_path):
with open(save_path, 'wb')as f:
pickle.dump(dic, f)
def load_pickle(load_path):
w... | 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,125,767 | SEED = 1111
np.random.seed(SEED)
def create_mlp(
num_columns, num_labels, hidden_units, dropout_rates, label_smoothing, learning_rate
):
inp = tf.keras.layers.Input(shape=(num_columns,))
x = tf.keras.layers.BatchNormalization()(inp)
x = tf.keras.layers.Dropout(dropout_rates[0] )(x)
for i in range(len(hidden_units)... | input_size = 250 | Deepfake Detection Challenge |
8,125,767 | if True:
env = janestreet.make_env()
env_iter = env.iter_test()
for(test_df, pred_df)in tqdm(env_iter):
if test_df['weight'].item() > 0:
x_tt = test_df.loc[:, feat_cols].values
if np.isnan(x_tt.sum()):
x_tt = np.nan_to_num(x_tt)+ np.isnan(x_tt)* f_mean
cross_41_42_43 = x_tt[:, 41] + x_tt[:, 42] + x_tt[:, 43]
cross_1_2 ... | mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
normalize_transform = Normalize(mean, std ) | Deepfake Detection Challenge |
8,125,767 | pd.set_option('display.max_columns', 100)
pd.set_option('display.max_rows', 100)
DATA_PATH = '.. /input/jane-street-market-prediction/'
NFOLDS = 5
TRAIN = False
CACHE_PATH = '.. /input/mlp012003weights'
XGBOOST_PATH = '.. /input/xgboost'
def save_pickle(dic, save_path):
with open(save_path, 'wb')as f:
pickle.dump(dic... | 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,125,767 | SEED = 1111
np.random.seed(SEED)
def create_mlp(
num_columns, num_labels, hidden_units, dropout_rates, label_smoothing, learning_rate
):
inp = tf.keras.layers.Input(shape=(num_columns,))
x = tf.keras.layers.BatchNormalization()(inp)
x = tf.keras.layers.Dropout(dropout_rates[0] )(x)
for i in range(len(hidden_units)... | 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,125,767 | import joblib
from xgboost import XGBClassifier
import xgboost as xgb<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,125,767 | XGBOOST_PATH = '.. /input/xgboost'
median_df = pd.read_csv(XGBOOST_PATH+'/median_pd_130_features.csv', index_col=False, header=0);
median_df.columns = range(median_df.shape[1])
median_df = median_df.transpose()
median_df.columns = median_df.iloc[0]
median_df.drop(median_df.index[0], inplace=True)
median = median_df.i... | 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,125,767 | xgb_file_suffix = "-n-500-d-8-sub-0.9-lr-0.05.joblib"
xgb_clfs = []
for i in range(5):
xgb_clf = joblib.load(XGBOOST_PATH + "/xgb" + str(i)+ xgb_file_suffix)
xgb_clfs.append(xgb_clf )<load_from_csv> | speed_test = True | Deepfake Detection Challenge |
8,125,767 | LOCAL_TEST = True
if LOCAL_TEST:
datatable_frame = datatable.fread('.. /input/jane-street-market-prediction/train.csv')
df_raw = datatable_frame.to_pandas()
del datatable_frame
df_raw = df_raw.query('date > 85' ).reset_index(drop = True)
df_raw = df_raw[df_raw['weight'] != 0]
df_raw['action'] =(( df_raw['resp'].value... | 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,125,767 | if LOCAL_TEST:
class TestDataset(Dataset):
def __init__(self, df):
self.features = df[all_feat_cols].values
def __len__(self):
return len(self.features)
def __getitem__(self, idx):
return {
'features': torch.tensor(self.features[idx], dtype=torch.float)
}<load_pretrained> | predictions = predict_on_video_set(test_videos, num_workers=4 ) | Deepfake Detection Challenge |
8,125,767 | if LOCAL_TEST:
BATCH_SIZE = 8192
test_set = TestDataset(X_test_extended)
test_loader = DataLoader(test_set, batch_size=BATCH_SIZE, shuffle=False, num_workers=4)
for model in model_list:
model.eval()
torch_preds = []
for data in test_loader:
feature_data = data['features'].to(device)
multiple_preds = np.zeros(( len(f... | submission_df_resnext = pd.DataFrame({"filename": test_videos, "label": predictions})
submission_df_resnext.to_csv("submission_resnext.csv", index=False ) | Deepfake Detection Challenge |
8,125,767 | if not LOCAL_TEST:
env = janestreet.make_env()
env_iter = env.iter_test()
th = 0.5
for(test_df, pred_df)in tqdm(env_iter):
if test_df['weight'].item() > 0:
x_tt = test_df.loc[:, feat_cols].values
if np.isnan(x_tt.sum()):
x_tt = np.nan_to_num(x_tt)+ np.isnan(x_tt)* f_mean
cross_41_42_43 = x_tt[:, 41] + x_tt[:, 42] + x_t... | !pip install.. /input/deepfake-xception-trained-model/pytorchcv-0.0.55-py2.py3-none-any.whl --quiet | Deepfake Detection Challenge |
8,125,767 | train = pd.read_csv(".. /input/jane-street-market-prediction/train.csv" )<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 |
8,125,767 | train = train.query('date > 85' ).reset_index(drop = True )<groupby> | gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" ) | Deepfake Detection Challenge |
8,125,767 | features_mean = train.loc[:, features].mean()<data_type_conversions> | 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,125,767 | train.fillna(train.mean() , inplace=True )<prepare_x_and_y> | 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,125,767 | resp_cols = ['resp_1', 'resp_2', 'resp_3', 'resp_4', 'resp']
X_train = train.loc[:, features].values
y_train = np.stack([train[c] for c in resp_cols] ).T
print(X_train.shape, y_train.shape)
del train<choose_model_class> | input_size = 150 | Deepfake Detection Challenge |
8,125,767 |
<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,125,767 | HIDDEN_LAYER_1 = [256, 256]
HIDDEN_LAYER_2 = [160, 160, 160]
HIDDEN_LAYER_3 = [128, 128, 128, 128]
TARGET_NUM = 5
input = tf.keras.layers.Input(shape=(X_train.shape[1],))
x1 = tf.keras.layers.BatchNormalization()(input)
x1 = tf.keras.layers.Dropout(0.25 )(x1)
for units in HIDDEN_LAYER_1:
x1 = tf.keras.layers.Dense(un... | 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,125,767 | print('Train NN...')
history = model.fit(
x = X_train,
y = y_train,
epochs=200,
batch_size=4096,
)
models = []
models.append(model)
print('Done!' )<prepare_x_and_y> | 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,125,767 | del X_train, y_train<save_model> | 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,125,767 | model.save('./model', save_format="tf")
print('export saved model.')
<load_pretrained> | speed_test = True | Deepfake Detection Challenge |
8,125,767 | model = tf.keras.models.load_model('./model' )<statistical_test> | 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,125,767 | THRESHOLD = 0
env = janestreet.make_env()
iter_test = env.iter_test()
print('predicting...')
for(test_df, pred_df)in tqdm(env.iter_test()):
global pred
if test_df['weight'].item() > 0:
X_test = test_df.loc[:, features].values
if np.isnan(X_test.sum()):
X_test = np.nan_to_num(X_test)+ np.isnan(X_test)* features_mean.va... | %%time
model.eval()
predictions = predict_on_video_set(test_videos, num_workers=4 ) | Deepfake Detection Challenge |
8,125,767 | import janestreet
from tqdm.notebook import tqdm
import time
import numpy as np
import os ,gc
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import datatable as dt
import tensorflow as tf
from tensorflow import keras
import tensorflow_addons as tfa<set_options> | submission_df_xception = pd.DataFrame({"filename": test_videos, "label": predictions})
submission_df_xception.to_csv("submission_xception.csv", index=False ) | Deepfake Detection Challenge |
8,125,767 | def set_seed(seed=7):
np.random.seed(seed)
tf.random.set_seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
set_seed(seed=7)
plt.style.use('seaborn' )<load_from_csv> | submission_df = pd.DataFrame({"filename": test_videos} ) | Deepfake Detection Challenge |
8,125,767 | %time
train_df=dt.fread('.. /input/jane-street-market-prediction/train.csv' ).to_pandas().query('weight > 0 and date >85' ).reset_index(drop=True)
test_df=dt.fread('.. /input/jane-street-market-prediction/example_test.csv' ).to_pandas().reset_index(drop=True)
sample_submission=pd.read_csv('.. /input/jane-street-marke... | r1 = 0.38
r2 = 0.62
total = r1 + r2
r11 = r1/total
r22 = r2/total | Deepfake Detection Challenge |
8,125,767 | print('Training set shape {}
Test set shape {} '.format(train_df.shape,test_df.shape))<categorify> | submission_df["label"] = r22*submission_df_resnext["label"] + r11*submission_df_xception["label"] | Deepfake Detection Challenge |
8,125,767 | <prepare_x_and_y><EOS> | submission_df.to_csv("submission.csv", index=False ) | Deepfake Detection Challenge |
8,206,048 | <SOS> metric: LogLoss Kaggle data source: deepfake-detection-challenge<choose_model_class> | %matplotlib inline
warnings.filterwarnings("ignore")
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)
print("PyTorch version:", torch.__version__)
print("CUDA version:", torch.vers... | Deepfake Detection Challenge |
8,206,048 | def Build_model(num_columns, num_labels, hidden_units, dropout_rates, label_smoothing, learning_rate
):
inp = tf.keras.layers.Input(shape=(num_columns,))
x = tf.keras.layers.BatchNormalization()(inp)
x = tf.keras.layers.Dropout(dropout_rates[0] )(x)
for i in range(len(hidden_units)) :
x = tf.keras.layers.Dense(hidde... | sys.path.insert(0, "/kaggle/input/blazeface-pytorch")
sys.path.insert(0, "/kaggle/input/deepfakes-inference-demo")
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)
frames... | Deepfake Detection Challenge |
8,206,048 | epochs = 200
batch_size = 8192
hidden_units = [256,128,128,64]
dropout_rates = [0.2,0.25, 0.25, 0.2, 0.15]
label_smoothing = 1e-2
learning_rate = 1e-2
tf.keras.backend.clear_session()
model2 = Build_model(len(features), 5, hidden_units, dropout_rates, label_smoothing, learning_rate)
reduce_lr = keras.callbacks.ReduceL... | !pip install.. /input/deepfake-xception-trained-model/pytorchcv-0.0.55-py2.py3-none-any.whl --quiet | Deepfake Detection Challenge |
8,206,048 | epochs = 200
batch_size = 8192
hidden_units = [256,128,64]
dropout_rates = [0.2,0.25, 0.20, 0.2]
label_smoothing = 1e-2
learning_rate = 1e-1
tf.keras.backend.clear_session()
model3= Build_model(len(features), 5, hidden_units, dropout_rates, label_smoothing, learning_rate)
reduce_lr = keras.callbacks.ReduceLROnPlateau(... | 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,206,048 | models=[model2,model3]
th = 0.491
f = np.median
env = janestreet.make_env()
for(test_df, pred_df)in tqdm(env.iter_test()):
test_df=test_df.interpolate(limit_direction='forward',axis=0)
test_df=test_df.bfill()
if test_df['weight'].item() > 0:
x_tt = test_df.loc[:, features].values
pred = np.mean([model(x_tt, training =... | gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
sys.path.insert(0, "/kaggle/input/blazeface-pytorch")
sys.path.insert(0, "/kaggle/input/deepfakes-inference-demo")
facedet = BlazeFace().to(gpu)
facedet.load_weights("/kaggle/input/blazeface-pytorch/blazeface.pth")
facedet.load_anchors("/kaggle/i... | Deepfake Detection Challenge |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.