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['BUREAU_CREDIT_DEBT_RATIO']=bureau['AMT_CREDIT_SUM_DEBT']/bureau['AMT_CREDIT_SUM'] bureau['BUREAU_CREDIT_DEBT_DIFF'] = bureau['AMT_CREDIT_SUM_DEBT'] - bureau['AMT_CREDIT_SUM'] bureau['BUREAU_IS_DPD'] = bureau['CREDIT_DAY_OVERDUE'].apply(lambda x: 1 if x > 0 else 0) bureau['BUREAU_IS_DPD_OVER120'] = bureau['CREDIT_DAY_OVERDUE'].apply(lambda x: 1 if x >120 else 0) return bureau<drop_column>
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': ['max', 'mean', 'sum'], 'AMT_CREDIT_SUM_DEBT': ['max', 'mean', 'sum'], 'AMT_CREDIT_SUM_OVERDUE': ['max', 'mean', 'sum'], 'AMT_ANNUITY': ['max', 'mean', 'sum'], 'BUREAU_ENDDATE_FACT_DIFF':['min', 'max', 'mean'], 'BUREAU_CREDIT_FACT_DIFF':['min', 'max', 'mean'], 'BUREAU_CREDIT_ENDDATE_DIFF':['min', 'max', 'mean'], 'BUREAU_CREDIT_DEBT_RATIO':['min', 'max', 'mean'], 'BUREAU_CREDIT_DEBT_DIFF':['min', 'max', 'mean'], 'BUREAU_IS_DPD':['mean', 'sum'], 'BUREAU_IS_DPD_OVER120':['mean', 'sum'] } bureau_grp = bureau.groupby('SK_ID_CURR') bureau_day_amt_agg = bureau_grp.agg(bureau_agg_dict) bureau_day_amt_agg.columns = ['BUREAU_'+('_' ).join(column ).upper() for column in bureau_day_amt_agg.columns.ravel() ] bureau_day_amt_agg = bureau_day_amt_agg.reset_index() print('bureau_day_amt_agg shape:', bureau_day_amt_agg.shape) return bureau_day_amt_agg<groupby>
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', 'mean'], 'DAYS_ENDDATE_FACT':['min', 'max', 'mean'], 'AMT_CREDIT_MAX_OVERDUE': ['max', 'mean'], 'AMT_CREDIT_SUM': ['max', 'mean', 'sum'], 'AMT_CREDIT_SUM_DEBT': ['max', 'mean', 'sum'], 'AMT_CREDIT_SUM_OVERDUE': ['max', 'mean', 'sum'], 'AMT_ANNUITY': ['max', 'mean', 'sum'], 'BUREAU_ENDDATE_FACT_DIFF':['min', 'max', 'mean'], 'BUREAU_CREDIT_FACT_DIFF':['min', 'max', 'mean'], 'BUREAU_CREDIT_ENDDATE_DIFF':['min', 'max', 'mean'], 'BUREAU_CREDIT_DEBT_RATIO':['min', 'max', 'mean'], 'BUREAU_CREDIT_DEBT_DIFF':['min', 'max', 'mean'], 'BUREAU_IS_DPD':['mean', 'sum'], 'BUREAU_IS_DPD_OVER120':['mean', 'sum'] } bureau_active_agg = bureau_active_grp.agg(bureau_agg_dict) bureau_active_agg.columns = ['BUREAU_ACT_'+('_' ).join(column ).upper() for column in bureau_active_agg.columns.ravel() ] bureau_active_agg = bureau_active_agg.reset_index() print('bureau_active_agg shape:', bureau_active_agg.shape) return bureau_active_agg<merge>
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'].apply(lambda x: 1 if x =='5' else 0) bureau_bal_grp = bureau_bal.groupby('SK_ID_CURR') bureau_bal_agg_dict = { 'SK_ID_CURR':['count'], 'MONTHS_BALANCE':['min', 'max', 'mean'], 'BUREAU_BAL_IS_DPD':['mean', 'sum'], 'BUREAU_BAL_IS_DPD_OVER120':['mean', 'sum'] } bureau_bal_agg = bureau_bal_grp.agg(bureau_bal_agg_dict) bureau_bal_agg.columns = [ 'BUREAU_BAL_'+('_' ).join(column ).upper() for column in bureau_bal_agg.columns.ravel() ] bureau_bal_agg = bureau_bal_agg.reset_index() print('bureau_bal_agg shape:', bureau_bal_agg.shape) return bureau_bal_agg<merge>
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='left') bureau_agg = bureau_agg.merge(bureau_bal_agg, on='SK_ID_CURR', how='left') print('bureau_agg shape:', bureau_agg.shape) return bureau_agg<merge>
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("Insincere question") display(df[df['target'] == 1].head() )<feature_engineering>
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['question_text'].progress_map(lambda x: sum(c.isdigit() for c in x)) stats['num_stopwords'] = stats['question_text'].progress_map(lambda x: len([c for c in str(x ).lower().split() if c in STOPWORDS])) return stats <define_variables>
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 not have',"could've": 'could have',"couldn't": 'could not',"couldn't've": 'could not have',"daren't": 'dare not',"daresn't": 'dare not',"dasn't": 'dare not',"didn't": 'did not','didn’t': 'did not',"don't": 'do not','don’t': 'do not',"doesn't": 'does not',"e'er": 'ever',"everyone's": 'everyone is',"finna": 'fixing to',"gimme": 'give me',"gon't": 'go not',"gonna": 'going to',"gotta": 'got to',"hadn't": 'had not',"hadn't've": 'had not have',"hasn't": 'has not',"haven't": 'have not',"he've": 'he have',"he's": 'he is',"he'll": 'he will',"he'll've": 'he will have',"he'd": 'he would',"he'd've": 'he would have',"here's": 'here is',"how're": 'how are',"how'd": 'how did',"how'd'y": 'how do you',"how's": 'how is',"how'll": 'how will',"isn't": 'is not',"it's": 'it is',"'tis": 'it is',"'twas": 'it was',"it'll": 'it will',"it'll've": 'it will have',"it'd": 'it would',"it'd've": 'it would have',"kinda": 'kind of',"let's": 'let us',"luv": 'love',"ma'am": 'madam',"may've": 'may have',"mayn't": 'may not',"might've": 'might have',"mightn't": 'might not',"mightn't've": 'might not have',"must've": 'must have',"mustn't": 'must not',"mustn't've": 'must not have',"needn't": 'need not',"needn't've": 'need not have',"ne'er": 'never',"o'": 'of',"o'clock": 'of the clock',"ol'": 'old',"oughtn't": 'ought not',"oughtn't've": 'ought not have',"o'er": 'over',"shan't": 'shall not',"sha'n't": 'shall not',"shalln't": 'shall not',"shan't've": 'shall not have',"she's": 'she is',"she'll": 'she will',"she'd": 'she would',"she'd've": 'she would have',"should've": 'should have',"shouldn't": 'should not',"shouldn't've": 'should not have',"so've": 'so have',"so's": 'so is',"somebody's": 'somebody is',"someone's": 'someone is',"something's": 'something is',"sux": 'sucks',"that're": 'that are',"that's": 'that is',"that'll": 'that will',"that'd": 'that would',"that'd've": 'that would have',"em": 'them',"there're": 'there are',"there's": 'there is',"there'll": 'there will',"there'd": 'there would',"there'd've": 'there would have',"these're": 'these are',"they're": 'they are',"they've": 'they have',"they'll": 'they will',"they'll've": 'they will have',"they'd": 'they would',"they'd've": 'they would have',"this's": 'this is',"those're": 'those are',"to've": 'to have',"wanna": 'want to',"wasn't": 'was not',"we're": 'we are',"we've": 'we have',"we'll": 'we will',"we'll've": 'we will have',"we'd": 'we would',"we'd've": 'we would have',"weren't": 'were not',"what're": 'what are',"what'd": 'what did',"what've": 'what have',"what's": 'what is',"what'll": 'what will',"what'll've": 'what will have',"when've": 'when have',"when's": 'when is',"where're": 'where are',"where'd": 'where did',"where've": 'where have',"where's": 'where is',"which's": 'which is',"who're": 'who are',"who've": 'who have',"who's": 'who is',"who'll": 'who will',"who'll've": 'who will have',"who'd": 'who would',"who'd've": 'who would have',"why're": 'why are',"why'd": 'why did',"why've": 'why have',"why's": 'why is',"will've": 'will have',"won't": 'will not',"won't've": 'will not have',"would've": 'would have',"wouldn't": 'would not',"wouldn't've": 'would not have',"y'all": 'you all',"y'all're": 'you all are',"y'all've": 'you all have',"y'all'd": 'you all would',"y'all'd've": 'you all would have',"you're": 'you are',"you've": 'you have',"you'll've": 'you shall have',"you'll": 'you will',"you'd": 'you would',"you'd've": 'you would have','jan.': 'january','feb.': 'february','mar.': 'march','apr.': 'april','jun.': 'june','jul.': 'july','aug.': 'august','sep.': 'september','oct.': 'october','nov.': 'november','dec.': 'december','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','amn’t': 'am not','ain’t': 'are not','aren’t': 'are not','’cause': 'because','can’t': 'can not','can’t’ve': 'can not have','could’ve': 'could have','couldn’t': 'could not','couldn’t’ve': 'could not have','daren’t': 'dare not','daresn’t': 'dare not','dasn’t': 'dare not','doesn’t': 'does not','e’er': 'ever','everyone’s': 'everyone is','gon’t': 'go not','hadn’t': 'had not','hadn’t’ve': 'had not have','hasn’t': 'has not','haven’t': 'have not','he’ve': 'he have','he’s': 'he is','he’ll': 'he will','he’ll’ve': 'he will have','he’d': 'he would','he’d’ve': 'he would have','here’s': 'here is','how’re': 'how are','how’d': 'how did','how’d’y': 'how do you','how’s': 'how is','how’ll': 'how will','isn’t': 'is not','it’s': 'it is','’tis': 'it is','’twas': 'it was','it’ll': 'it will','it’ll’ve': 'it will have','it’d': 'it would','it’d’ve': 'it would have','let’s': 'let us','ma’am': 'madam','may’ve': 'may have','mayn’t': 'may not','might’ve': 'might have','mightn’t': 'might not','mightn’t’ve': 'might not have','must’ve': 'must have','mustn’t': 'must not','mustn’t’ve': 'must not have','needn’t': 'need not','needn’t’ve': 'need not have','ne’er': 'never','o’': 'of','o’clock': 'of the clock','ol’': 'old','oughtn’t': 'ought not','oughtn’t’ve': 'ought not have','o’er': 'over','shan’t': 'shall not','sha’n’t': 'shall not','shalln’t': 'shall not','shan’t’ve': 'shall not have','she’s': 'she is','she’ll': 'she will','she’d': 'she would','she’d’ve': 'she would have','should’ve': 'should have','shouldn’t': 'should not','shouldn’t’ve': 'should not have','so’ve': 'so have','so’s': 'so is','somebody’s': 'somebody is','someone’s': 'someone is','something’s': 'something is','that’re': 'that are','that’s': 'that is','that’ll': 'that will','that’d': 'that would','that’d’ve': 'that would have','there’re': 'there are','there’s': 'there is','there’ll': 'there will','there’d': 'there would','there’d’ve': 'there would have','these’re': 'these are','they’re': 'they are','they’ve': 'they have','they’ll': 'they will','they’ll’ve': 'they will have','they’d': 'they would','they’d’ve': 'they would have','this’s': 'this is','those’re': 'those are','to’ve': 'to have','wasn’t': 'was not','we’re': 'we are','we’ve': 'we have','we’ll': 'we will','we’ll’ve': 'we will have','we’d': 'we would','we’d’ve': 'we would have','weren’t': 'were not','what’re': 'what are','what’d': 'what did','what’ve': 'what have','what’s': 'what is','what’ll': 'what will','what’ll’ve': 'what will have','when’ve': 'when have','when’s': 'when is','where’re': 'where are','where’d': 'where did','where’ve': 'where have','where’s': 'where is','which’s': 'which is','who’re': 'who are','who’ve': 'who have','who’s': 'who is','who’ll': 'who will','who’ll’ve': 'who will have','who’d': 'who would','who’d’ve': 'who would have','why’re': 'why are','why’d': 'why did','why’ve': 'why have','why’s': 'why is','will’ve': 'will have','won’t': 'will not','won’t’ve': 'will not have','would’ve': 'would have','wouldn’t': 'would not','wouldn’t’ve': 'would not have','y’all': 'you all','y’all’re': 'you all are','y’all’ve': 'you all have','y’all’d': 'you all would','y’all’d’ve': 'you all would have','you’re': 'you are','you’ve': 'you have','you’ll’ve': 'you shall have','you’ll': 'you will','you’d': 'you would','you’d’ve': 'you would have'} missing_spell = {'colour': 'color', 'centre': 'center', 'favourite': 'favorite', 'travelling': 'traveling', 'counselling': 'counseling', 'theatre': 'theater', 'cancelled': 'canceled', 'labour': 'labor', 'organisation': 'organization', 'wwii': 'world war 2', 'citicise': 'criticize', 'youtu ': 'youtube ', 'Qoura': 'Quora', 'sallary': 'salary', 'Whta': 'What', 'narcisist': 'narcissist', 'howdo': 'how do', 'whatare': 'what are', 'howcan': 'how can', 'howmuch': 'how much', 'howmany': 'how many', 'whydo': 'why do', 'doI': 'do I', 'theBest': 'the best', 'howdoes': 'how does', 'mastrubation': 'masturbation', 'mastrubate': 'masturbate', "mastrubating": 'masturbating', 'pennis': 'penis', 'Etherium': 'bitcoin', 'narcissit': 'narcissist', 'bigdata': 'big data', '2k17': '2017', '2k18': '2018', 'qouta': 'quota', 'exboyfriend': 'ex boyfriend', 'airhostess': 'air hostess', "whst": 'what', 'watsapp': 'whatsapp', 'demonitisation': 'demonetization', 'demonitization': 'demonetization', 'demonetisation': 'demonetization','electroneum':'bitcoin','nanodegree':'degree','hotstar':'star','dream11':'dream','ftre':'fire','tensorflow':'framework','unocoin':'bitcoin','lnmiit':'limit','unacademy':'academy','altcoin':'bitcoin','altcoins':'bitcoin','litecoin':'bitcoin','coinbase':'bitcoin','cryptocurency':'cryptocurrency','simpliv':'simple','quoras':'quora','schizoids':'psychopath','remainers':'remainder','twinflame':'soulmate','quorans':'quora','brexit':'demonetized','iiest':'institute','dceu':'comics','pessat':'exam','uceed':'college','bhakts':'devotee','boruto':'anime','cryptocoin':'bitcoin','blockchains':'blockchain','fiancee':'fiance','redmi':'smartphone','oneplus':'smartphone','qoura':'quora','deepmind':'framework','ryzen':'cpu','whattsapp':'whatsapp','undertale':'adventure','zenfone':'smartphone','cryptocurencies':'cryptocurrencies','koinex':'bitcoin','zebpay':'bitcoin','binance':'bitcoin','whtsapp':'whatsapp','reactjs':'framework','bittrex':'bitcoin','bitconnect':'bitcoin','bitfinex':'bitcoin','yourquote':'your quote','whyis':'why is','jiophone':'smartphone','dogecoin':'bitcoin','onecoin':'bitcoin','poloniex':'bitcoin','7700k':'cpu','angular2':'framework','segwit2x':'bitcoin','hashflare':'bitcoin','940mx':'gpu','openai':'framework','hashflare':'bitcoin','1050ti':'gpu','nearbuy':'near buy','freebitco':'bitcoin','antminer':'bitcoin','filecoin':'bitcoin','whatapp':'whatsapp','empowr':'empower','1080ti':'gpu','crytocurrency':'cryptocurrency','8700k':'cpu','whatsaap':'whatsapp','g4560':'cpu','payymoney':'pay money','fuckboys':'fuck boys','intenship':'internship','zcash':'bitcoin','demonatisation':'demonetization','narcicist':'narcissist','mastuburation':'masturbation','trignometric':'trigonometric','cryptocurreny':'cryptocurrency','howdid':'how did','crytocurrencies':'cryptocurrencies','phycopath':'psychopath','bytecoin':'bitcoin','possesiveness':'possessiveness','scollege':'college','humanties':'humanities','altacoin':'bitcoin','demonitised':'demonetized','brasília':'brazilia','accolite':'accolyte','econimics':'economics','varrier':'warrier','quroa':'quora','statergy':'strategy','langague':'language','splatoon':'game','7600k':'cpu','gate2018':'gate 2018','in2018':'in 2018','narcassist':'narcissist','jiocoin':'bitcoin','hnlu':'hulu','7300hq':'cpu','weatern':'western','interledger':'blockchain','deplation':'deflation', 'cryptocurrencies':'cryptocurrency', 'bitcoin':'blockchain cryptocurrency'} def clean_tag(x): if '[math]' in x: x = re.sub('\[math\].*?math\]', 'math equation', x) if 'http' in x or 'www' in x: x = re.sub('(?:(?:https?|ftp):\/\/)?[\w/\-?=%.]+\.[\w/\-?=%.]+', 'url', x) return x def contraction_fix(word): try: a=contractions[word] except KeyError: a=word return a def misspell_fix(word): try: a=missing_spell[word] except KeyError: a=word return a def clean_text(text): text = clean_tag(text) text = " ".join([contraction_fix(w)for w in text.split() ]) text = " ".join([misspell_fix(w)for w in text.split() ]) text = re.sub(r'[^a-zA-Z0-9]', ' ', text) return text def apply_clean_text(question_text): tmp = pd.DataFrame() tmp['question_text'] = question_text; tmp['clean'] = tmp.question_text.progress_map(clean_text) with pd_ctx: display(tmp) return tmp['clean'] sample['clean'] = apply_clean_text(sample.question_text )<string_transform>
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())[:20]<string_transform>
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 padded_sequences = create_sequence(tokenizer, sample['clean']) print("Kích thước mảng:",padded_sequences.shape) print("Length of 20 first word_sequences:") print(list(map(lambda x: len(x),padded_sequences[:20]))) print(" 10 first word_sequences:") for sequence in padded_sequences[:10]: print(sequence) <prepare_x_and_y>
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_SENTENCE_LENGTH, weights=[embedding_matrix], trainable=False )(x_input) else: embedding = Embedding(features, EMBEDDING_DIM, input_length=MAX_SENTENCE_LENGTH )(x_input) x = SpatialDropout1D(0.2 )(embedding) lstm = Bidirectional(LSTM(256, return_sequences=True))(x) gru = Bidirectional(GRU(128, return_sequences=True))(lstm) x = Concatenate()([lstm, gru]) x = GlobalAveragePooling1D()(x) x_output = Dense(1, activation='sigmoid', bias_initializer=output_bias )(x) model = Model(inputs=x_input, outputs=x_output) opt = Adam(lr=learning_rate) model.compile(loss='binary_crossentropy', optimizer= opt, metrics=[f1_m]) return model def f1_m(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) recall = true_positives /(possible_positives + K.epsilon()) precision = true_positives /(predicted_positives + K.epsilon()) return 2*(( precision*recall)/(precision+recall+K.epsilon()))<compute_test_metric>
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_strategy() print('Use CPU' )<choose_model_class>
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_categorical('colsample_bytree', [0.1, 0.2, 0.3,0.5,0.7,0.9]), 'subsample': trial.suggest_categorical('subsample', [0.1, 0.2,0.3,0.4,0.5,0.8,1.0]), 'learning_rate': trial.suggest_categorical('learning_rate', [0.0008, 0.01, 0.015, 0.02,0.03, 0.05,0.08,0.1]), 'n_estimators': 4000, 'max_depth': trial.suggest_categorical('max_depth', [5,7,9,11,13,15,17,20,23,25]), 'random_state': 48, 'min_child_weight': trial.suggest_int('min_child_weight', 1, 400), } model = xgb.XGBRegressor(**param) model.fit(train_x,train_y,eval_set=[(test_x,test_y)],early_stopping_rounds=100,verbose=False) preds = model.predict(test_x) rmse = mean_squared_error(test_y, preds,squared=False) return rmse
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=[early_stopping,reduce_lr] def train_model_and_predict(X_train, y_train, X_val, y_val, X_test, embedding_vec=None): print("Create vocab...") tokenizer = create_tokenizer(X_train) print("Create sequences...") X_train_seq = create_sequence(tokenizer, X_train) X_val_seq = create_sequence(tokenizer, X_val) X_test_seq = create_sequence(tokenizer, X_test) embedding_matrix = None if not(embedding_vec is None): embedding_matrix = load_embedding(embedding_vec, tokenizer.word_index) model = createModel_bidirectional_LSTM_GRU(len(tokenizer.word_index)+1, embedding_matrix) model.fit(X_train_seq, y_train, batch_size=batch_size, epochs=n_epochs, validation_data=(X_val_seq, y_val), class_weight=class_weight, callbacks=my_callbacks) val_pred = model.predict(X_val_seq, verbose=1, batch_size=256) threshold, f1_score = best_threshold(y_val, val_pred) test_pred = model.predict(X_test_seq, verbose=1, batch_size=256) return threshold, f1_score, val_pred, test_pred<predict_on_test>
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_lines_count(file_name) )if len(o)> 100 )<choose_model_class>
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.float32)- 1 unknown_words = [] for key, i in tqdm(word2index.items()): word = key if word in word2vec: embedding_weights[i] = word2vec[word] continue word = key.capitalize() if word in word2vec: embedding_weights[i] = word2vec[word] continue word = key.upper() if word in word2vec: embedding_weights[i] = word2vec[word] continue word = key.lower() if word in word2vec: embedding_weights[i] = word2vec[word] continue word = ps.stem(key) if word in word2vec: embedding_weights[i] = word2vec[word] continue word = lc.stem(key) if word in word2vec: embedding_weights[i] = word2vec[word] continue word = sb.stem(key) if word in word2vec: embedding_weights[i] = word2vec[word] continue unknown_words.append(key) embedding_weights[i] = unknown_vector print('Top 10 Null word embeddings: ') print(unknown_words[:10]) print(' Null word embeddings: %d' % len(unknown_words)) print("There are {:.2f}% word out of embedding file".format(100*len(unknown_words)/vocab_size)) return embedding_weights<load_pretrained>
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_global ).astype(int)) )<save_to_csv>
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["prediction"]=y_test_pre submit.to_csv("submission.csv",index=False )<import_modules>
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_labels = train[:, 0].astype(np.uint8) test_images = test.reshape(( test.shape[0], 28, 28, 1)) / 255.0<choose_model_class>
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, activation='relu'), Dropout(0.3), Dense(10, activation='softmax') ] )<choose_model_class>
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': trial.suggest_categorical('feature_framcion', [0.1, 0.2, 0.3,0.5,0.7,0.9]), 'bagging_fraction': trial.suggest_categorical('bagging_framcion', [0.1, 0.2,0.3,0.4,0.5,0.8,1.0]), 'learning_rate': trial.suggest_categorical('learning_rate', [0.0008, 0.01, 0.015, 0.02,0.03, 0.05,0.08,0.1]), 'n_estimators': 4000, 'num_leaves': trial.suggest_categorical('num_leaves', [31,50,150,200,250,300,350]), 'max_depth': trial.suggest_categorical('max_depth', [5,7,9,11,13,15,17,20,23,25]), 'min_data_in_leaf': trial.suggest_categorical('min_data_in_leaf', [10,20,30]), 'min_child_weight': trial.suggest_categorical('min_child_weight', [0.001,0.005, 0.01, 0.05, 0.1,0.5]), 'random_state': 48 } model = lgb.LGBMRegressor(**param) model.fit(train_x,train_y,eval_set=[(test_x,test_y)],early_stopping_rounds=100,verbose=False) preds = model.predict(test_x) rmse = mean_squared_error(test_y, preds,squared=False) return rmse
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, RandomBrightnessContrast, Flip, OneOf, Compose, Normalize, Cutout, CoarseDropout, ShiftScaleRotate, CenterCrop, Resize ) HorizontalFlip, VerticalFlip, IAAPerspective, ShiftScaleRotate, CLAHE, RandomRotate90, Transpose, ShiftScaleRotate, Blur, OpticalDistortion, GridDistortion, HueSaturationValue, IAAAdditiveGaussianNoise, GaussNoise, MotionBlur, MedianBlur, IAAPiecewiseAffine, RandomResizedCrop, IAASharpen, IAAEmboss, RandomBrightnessContrast, Flip, OneOf, Compose, Normalize, Cutout, CoarseDropout, ShiftScaleRotate, CenterCrop, Resize ) def get_train_transforms() : return Compose([ RandomResizedCrop(CFG['img_size'], CFG['img_size']), Transpose(p=0.5), HorizontalFlip(p=0.5), VerticalFlip(p=0.5), ShiftScaleRotate(p=0.5), HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=0.5), RandomBrightnessContrast(brightness_limit=(-0.1,0.1), contrast_limit=(-0.1, 0.1), p=0.5), Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0), CoarseDropout(p=0.5), Cutout(p=0.5), ToTensorV2(p=1.0), ], p=1.) def get_valid_transforms() : return Compose([ CenterCrop(CFG['img_size'], CFG['img_size'], p=1.) , Resize(CFG['img_size'], CFG['img_size']), Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0), ToTensorV2(p=1.0), ], p=1.) def get_inference_transforms() : return Compose([ RandomResizedCrop(CFG['img_size'], CFG['img_size']), Transpose(p=0.5), HorizontalFlip(p=0.5), VerticalFlip(p=0.5), HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit=0.2, val_shift_limit=0.2, p=0.5), RandomBrightnessContrast(brightness_limit=(-0.1,0.1), contrast_limit=(-0.1, 0.1), p=0.5), Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225], max_pixel_value=255.0, p=1.0), ToTensorV2(p=1.0), ], p=1.)<choose_model_class>
!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.model(x) return x<split>
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(drop=True) valid_ds = CassavaDataset(valid_, '.. /input/cassava-leaf-disease-classification/train_images/', transforms=get_inference_transforms() , output_label=False) test = pd.DataFrame() test['image_id'] = list(os.listdir('.. /input/cassava-leaf-disease-classification/test_images/')) test_ds = CassavaDataset(test, '.. /input/cassava-leaf-disease-classification/test_images/', transforms=get_inference_transforms() , output_label=False) val_loader = torch.utils.data.DataLoader( valid_ds, batch_size=CFG['valid_bs'], num_workers=CFG['num_workers'], shuffle=False, pin_memory=False, ) tst_loader = torch.utils.data.DataLoader( test_ds, batch_size=CFG['valid_bs'], num_workers=CFG['num_workers'], shuffle=False, pin_memory=False, ) device = torch.device(CFG['device']) model = CassvaImgClassifier(CFG['model_arch'], train.label.nunique() ).to(device) val_preds = [] tst_preds = [] for i, epoch in enumerate(CFG['used_epochs']): model.load_state_dict(torch.load('.. /input/pytorch-efficientnet-baseline-train-amp-aug/{}_fold_{}_{}'.format(CFG['model_arch'], fold, epoch))) with torch.no_grad() : for _ in range(CFG['tta']): val_preds += [CFG['weights'][i]/sum(CFG['weights'])/CFG['tta']*inference_one_epoch(model, val_loader, device)] tst_preds += [CFG['weights'][i]/sum(CFG['weights'])/CFG['tta']*inference_one_epoch(model, tst_loader, device)] val_preds = np.mean(val_preds, axis=0) tst_preds = np.mean(tst_preds, axis=0) print('fold {} validation loss = {:.5f}'.format(fold, log_loss(valid_.label.values, val_preds))) print('fold {} validation accuracy = {:.5f}'.format(fold,(valid_.label.values==np.argmax(val_preds, axis=1)).mean())) del model torch.cuda.empty_cache()<feature_engineering>
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_tensor_by_name('detection_scores:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0' )
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={image_tensor: imgs}) finals=[] for x in range(boxes.shape[0]): scores=scores_[x] max_=np.where(scores==scores.max())[0][0] box=boxes[x][max_] ymin, xmin, ymax, xmax = box (left, right, top, bottom)=(xmin * im_width, xmax * im_width, ymin * im_height, ymax * im_height) left, right, top, bottom = int(left), int(right), int(top), int(bottom) image=imgs[x] finals.append(cv2.cvtColor(cv2.resize(image[max([0,top-40]):bottom+80,max([0,left-40]):right+80],(240,240)) ,cv2.COLOR_BGR2RGB)) return finals def detect_video(video, start_frame): frame_count=10 capture = cv2.VideoCapture(video) v_len = int(capture.get(cv2.CAP_PROP_FRAME_COUNT)) frame_idxs = np.linspace(start_frame,v_len,frame_count, endpoint=False, dtype=np.int) imgs=[] i=0 for frame_idx in range(int(v_len)) : ret = capture.grab() if not ret: print("Error grabbing frame %d from movie %s" %(frame_idx, video)) if frame_idx >= frame_idxs[i]: if frame_idx-frame_idxs[i]>20: return None ret, frame = capture.retrieve() if not ret or frame is None: print("Error retrieving frame %d from movie %s" %(frame_idx, video)) else: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) imgs.append(frame) i += 1 if i >= len(frame_idxs): break imgs=get_img(imgs) if len(imgs)<10: return None return np.hstack(imgs)
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 err: print(err )
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 as err: print(err )
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 = nn.Dropout(dropout_rate) self.dense2 = nn.Linear(hidden_size+len(all_feat_cols), hidden_size) self.batch_norm2 = nn.BatchNorm1d(hidden_size) self.dropout2 = nn.Dropout(dropout_rate) self.dense3 = nn.Linear(hidden_size+hidden_size, hidden_size) self.batch_norm3 = nn.BatchNorm1d(hidden_size) self.dropout3 = nn.Dropout(dropout_rate) self.dense4 = nn.Linear(hidden_size+hidden_size, hidden_size) self.batch_norm4 = nn.BatchNorm1d(hidden_size) self.dropout4 = nn.Dropout(dropout_rate) self.dense5 = nn.Linear(hidden_size+hidden_size, len(target_cols)) self.Relu = nn.ReLU(inplace=True) self.PReLU = nn.PReLU() self.LeakyReLU = nn.LeakyReLU(negative_slope=0.01, inplace=True) self.RReLU = nn.RReLU() def forward(self, x): x = self.batch_norm0(x) x = self.dropout0(x) x1 = self.dense1(x) x1 = self.batch_norm1(x1) x1 = self.LeakyReLU(x1) x1 = self.dropout1(x1) x = torch.cat([x, x1], 1) x2 = self.dense2(x) x2 = self.batch_norm2(x2) x2 = self.LeakyReLU(x2) x2 = self.dropout2(x2) x = torch.cat([x1, x2], 1) x3 = self.dense3(x) x3 = self.batch_norm3(x3) x3 = self.LeakyReLU(x3) x3 = self.dropout3(x3) x = torch.cat([x2, x3], 1) x4 = self.dense4(x) x4 = self.batch_norm4(x4) x4 = self.LeakyReLU(x4) x4 = self.dropout4(x4) x = torch.cat([x3, x4], 1) x = self.dense5(x) return x<set_options>
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+['./videos_2/']*4 for xxxxx in range(8): start = time.time() model.load_weights(weights[xxxxx]) def get_birghtness(img): return img/img.max() def process_img(img,flip=[False]*10): imgs=[] for x in range(10): if flip[x]: imgs.append(get_birghtness(cv2.flip(img[:,x*240:(x+1)*240,:],1))) else: imgs.append(get_birghtness(img[:,x*240:(x+1)*240,:])) return np.array(imgs) sample_submission = pd.read_csv(".. /input/deepfake-detection-challenge/sample_submission.csv") test_files=glob.glob(video[xxxxx]+'*.jpg') submission=pd.DataFrame() submission['filename']=os.listdir(( '.. /input/deepfake-detection-challenge/test_videos/')) submission['label']=0.5 filenames=[] batch=[] batch1=[] batch2=[] batch3=[] preds=[] for x in test_files: img=process_img(cv2.cvtColor(cv2.imread(x),cv2.COLOR_BGR2RGB)) if img is None: continue batch.append(img) batch1.append(process_img(cv2.cvtColor(cv2.imread(x),cv2.COLOR_BGR2RGB),[True]*10)) batch2.append(process_img(cv2.cvtColor(cv2.imread(x),cv2.COLOR_BGR2RGB),[True,False]*5)) batch3.append(process_img(cv2.cvtColor(cv2.imread(x),cv2.COLOR_BGR2RGB),[False,True]*5)) filenames.append(x.replace(video[xxxxx],'' ).replace('.jpg','.mp4')) if len(batch)==16: preds+=(((0.25*model.predict(np.array(batch)))) +(( 0.25*model.predict(np.array(batch1)))) +(( 0.25*model.predict(np.array(batch2)))) +(( 0.25*model.predict(np.array(batch3)))) ).tolist() batch=[] batch1=[] batch2=[] batch3=[] if len(batch)!=0: preds+=(((0.25*model.predict(np.array(batch)))) +(( 0.25*model.predict(np.array(batch1)))) +(( 0.25*model.predict(np.array(batch2)))) +(( 0.25*model.predict(np.array(batch3)))) ).tolist() print(time.time() -start) new_preds=[] for x in preds: new_preds.append(x[0]) print(sum(new_preds)/len(new_preds)) for x,y in zip(new_preds,filenames): submission.loc[submission['filename']==y,'label']=min([max([0.05,x]),0.95]) submission.to_csv(sub_file[xxxxx], index=False )
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_modules>
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' ).transpose().to_dict() df5 = pd.read_csv('submission_5.csv' ).set_index('filename' ).transpose().to_dict() df6 = pd.read_csv('submission_6.csv' ).set_index('filename' ).transpose().to_dict() df7 = pd.read_csv('submission_7.csv' ).set_index('filename' ).transpose().to_dict() df8 = pd.read_csv('submission_8.csv' ).set_index('filename' ).transpose().to_dict() filename = [] label = [] for i in df1.keys() : filename.append(i) a = [] if df1[i]['label']!=0.5: a.append(df1[i]['label']) if df2[i]['label']!=0.5: a.append(df2[i]['label']) if df3[i]['label']!=0.5: a.append(df3[i]['label']) if df4[i]['label']!=0.5: a.append(df4[i]['label']) if df5[i]['label']!=0.5: a.append(df5[i]['label']) if df6[i]['label']!=0.5: a.append(df6[i]['label']) if df7[i]['label']!=0.5: a.append(df7[i]['label']) if df8[i]['label']!=0.5: a.append(df8[i]['label']) if len(a)==0: label.append(0.5) else: label.append(min([max([0.05,sum(a)/len(a)]),0.95])) df = pd.DataFrame() df['filename'] = filename df['label'] = label print(np.array(df['label'] ).mean()) df.to_csv('submission.csv', index=False )
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 = 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): with open(load_path, 'rb')as f: message_dict = pickle.load(f) return message_dict feat_cols = [f'feature_{i}' for i in range(130)] target_cols = ['action', 'action_1', 'action_2', 'action_3', 'action_4'] f_mean = np.load(f'{CACHE_PATH}/f_mean_online.npy') all_feat_cols = [col for col in feat_cols] all_feat_cols.extend(['cross_41_42_43', 'cross_1_2']) 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.2) dropout_rate = 0.2 hidden_size = 256 self.dense1 = nn.Linear(len(all_feat_cols), hidden_size) self.batch_norm1 = nn.BatchNorm1d(hidden_size) self.dropout1 = nn.Dropout(dropout_rate) self.dense2 = nn.Linear(hidden_size+len(all_feat_cols), hidden_size) self.batch_norm2 = nn.BatchNorm1d(hidden_size) self.dropout2 = nn.Dropout(dropout_rate) self.dense3 = nn.Linear(hidden_size+hidden_size, hidden_size) self.batch_norm3 = nn.BatchNorm1d(hidden_size) self.dropout3 = nn.Dropout(dropout_rate) self.dense4 = nn.Linear(hidden_size+hidden_size, hidden_size) self.batch_norm4 = nn.BatchNorm1d(hidden_size) self.dropout4 = nn.Dropout(dropout_rate) self.dense5 = nn.Linear(hidden_size+hidden_size, len(target_cols)) self.Relu = nn.ReLU(inplace=True) self.PReLU = nn.PReLU() self.LeakyReLU = nn.LeakyReLU(negative_slope=0.01, inplace=True) self.RReLU = nn.RReLU() def forward(self, x): x = self.batch_norm0(x) x = self.dropout0(x) x1 = self.dense1(x) x1 = self.batch_norm1(x1) x1 = self.LeakyReLU(x1) x1 = self.dropout1(x1) x = torch.cat([x, x1], 1) x2 = self.dense2(x) x2 = self.batch_norm2(x2) x2 = self.LeakyReLU(x2) x2 = self.dropout2(x2) x = torch.cat([x1, x2], 1) x3 = self.dense3(x) x3 = self.batch_norm3(x3) x3 = self.LeakyReLU(x3) x3 = self.dropout3(x3) x = torch.cat([x2, x3], 1) x4 = self.dense4(x) x4 = self.batch_norm4(x4) x4 = self.LeakyReLU(x4) x4 = self.dropout4(x4) x = torch.cat([x3, x4], 1) x = self.dense5(x) return x if True: device = torch.device("cuda:0") model_list = [] tmp = np.zeros(len(feat_cols)) for _fold in [1, 3, 4]: 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)) model.eval() model_list.append(model) models_other = [] model = torch.load(Model_Root + 'FOLD_1_10.pth') models_other.append(model) model = torch.load('.. /input/kaggle-model-130-features-epoch-200/' + 'FOLD_1_10.pth') models_other.append(model )<choose_model_class>
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)) : x = tf.keras.layers.Dense(hidden_units[i] )(x) x = tf.keras.layers.BatchNormalization()(x) x = tf.keras.layers.Activation(tf.keras.activations.swish )(x) x = tf.keras.layers.Dropout(dropout_rates[i + 1] )(x) x = tf.keras.layers.Dense(num_labels )(x) out = tf.keras.layers.Activation("sigmoid" )(x) model = tf.keras.models.Model(inputs=inp, outputs=out) model.compile( optimizer=tfa.optimizers.RectifiedAdam(learning_rate=learning_rate), loss=tf.keras.losses.BinaryCrossentropy(label_smoothing=label_smoothing), metrics=tf.keras.metrics.AUC(name="AUC"), ) return model epochs = 200 batch_size = 4096 hidden_units = [160, 160, 160] dropout_rates = [0.2, 0.2, 0.2, 0.2] label_smoothing = 1e-2 learning_rate = 1e-3 tf.keras.backend.clear_session() tf.random.set_seed(SEED) clf = create_mlp( len(feat_cols), 5, hidden_units, dropout_rates, label_smoothing, learning_rate ) clf.load_weights('.. /input/jane-street-with-keras-nn-overfit/model.h5') tf_models = [clf]<statistical_test>
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 = x_tt[:, 1] /(x_tt[:, 2] + 1e-5) feature_inp = np.concatenate(( x_tt, np.array(cross_41_42_43 ).reshape(x_tt.shape[0], 1), np.array(cross_1_2 ).reshape(x_tt.shape[0], 1), ), axis=1) torch_pred = np.zeros(( 1, len(target_cols))) for model in model_list: torch_pred += model(torch.tensor(feature_inp, dtype=torch.float ).to(device)).sigmoid().detach().cpu().numpy() / len(model_list) torch_pred = np.median(torch_pred) pred_other_torch = np.zeros(( 1, len(target_cols))) for model in models_other: pred_other_torch += np.mean(model(torch.tensor(x_tt, dtype=torch.float ).to(device)).sigmoid().detach().cpu().numpy() , axis=1)/ len(models_other) tf_pred = np.median(np.mean([model(x_tt, training = False ).numpy() for model in tf_models],axis=0)) pred = torch_pred * 0.35 + np.median(pred_other_torch)* 0.25 + tf_pred * 0.40 pred_df.action = np.where(pred > 0.495, 1, 0 ).astype(int) else: pred_df.action = 0 env.predict(pred_df )<load_pretrained>
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): with open(load_path, 'rb')as f: message_dict = pickle.load(f) return message_dict feat_cols = [f'feature_{i}' for i in range(130)] target_cols = ['action', 'action_1', 'action_2', 'action_3', 'action_4'] f_mean = np.load(f'{CACHE_PATH}/f_mean_online.npy') all_feat_cols = [col for col in feat_cols] all_feat_cols.extend(['cross_41_42_43', 'cross_1_2']) 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.2) dropout_rate = 0.2 hidden_size = 256 self.dense1 = nn.Linear(len(all_feat_cols), hidden_size) self.batch_norm1 = nn.BatchNorm1d(hidden_size) self.dropout1 = nn.Dropout(dropout_rate) self.dense2 = nn.Linear(hidden_size+len(all_feat_cols), hidden_size) self.batch_norm2 = nn.BatchNorm1d(hidden_size) self.dropout2 = nn.Dropout(dropout_rate) self.dense3 = nn.Linear(hidden_size+hidden_size, hidden_size) self.batch_norm3 = nn.BatchNorm1d(hidden_size) self.dropout3 = nn.Dropout(dropout_rate) self.dense4 = nn.Linear(hidden_size+hidden_size, hidden_size) self.batch_norm4 = nn.BatchNorm1d(hidden_size) self.dropout4 = nn.Dropout(dropout_rate) self.dense5 = nn.Linear(hidden_size+hidden_size, len(target_cols)) self.Relu = nn.ReLU(inplace=True) self.PReLU = nn.PReLU() self.LeakyReLU = nn.LeakyReLU(negative_slope=0.01, inplace=True) self.RReLU = nn.RReLU() def forward(self, x): x = self.batch_norm0(x) x = self.dropout0(x) x1 = self.dense1(x) x1 = self.batch_norm1(x1) x1 = self.LeakyReLU(x1) x1 = self.dropout1(x1) x = torch.cat([x, x1], 1) x2 = self.dense2(x) x2 = self.batch_norm2(x2) x2 = self.LeakyReLU(x2) x2 = self.dropout2(x2) x = torch.cat([x1, x2], 1) x3 = self.dense3(x) x3 = self.batch_norm3(x3) x3 = self.LeakyReLU(x3) x3 = self.dropout3(x3) x = torch.cat([x2, x3], 1) x4 = self.dense4(x) x4 = self.batch_norm4(x4) x4 = self.LeakyReLU(x4) x4 = self.dropout4(x4) x = torch.cat([x3, x4], 1) x = self.dense5(x) return x if True: device = torch.device("cuda:0") 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)) model.eval() model_list.append(model )<choose_model_class>
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)) : x = tf.keras.layers.Dense(hidden_units[i] )(x) x = tf.keras.layers.BatchNormalization()(x) x = tf.keras.layers.Activation(tf.keras.activations.swish )(x) x = tf.keras.layers.Dropout(dropout_rates[i + 1] )(x) x = tf.keras.layers.Dense(num_labels )(x) out = tf.keras.layers.Activation("sigmoid" )(x) model = tf.keras.models.Model(inputs=inp, outputs=out) model.compile( optimizer=tfa.optimizers.RectifiedAdam(learning_rate=learning_rate), loss=tf.keras.losses.BinaryCrossentropy(label_smoothing=label_smoothing), metrics=tf.keras.metrics.AUC(name="AUC"), ) return model epochs = 200 batch_size = 4096 hidden_units = [160, 160, 160] dropout_rates = [0.2, 0.2, 0.2, 0.2] label_smoothing = 1e-2 learning_rate = 1e-3 tf.keras.backend.clear_session() tf.random.set_seed(SEED) clf = create_mlp( len(feat_cols), 5, hidden_units, dropout_rates, label_smoothing, learning_rate ) clf.load_weights('.. /input/jane-street-with-keras-nn-overfit/model.h5') tf_models = [clf]<statistical_test>
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 = x_tt[:, 1] /(x_tt[:, 2] + 1e-5) feature_inp = np.concatenate(( x_tt, np.array(cross_41_42_43 ).reshape(x_tt.shape[0], 1), np.array(cross_1_2 ).reshape(x_tt.shape[0], 1), ), axis=1) torch_pred = np.zeros(( 1, len(target_cols))) for model in model_list: torch_pred += model(torch.tensor(feature_inp, dtype=torch.float ).to(device)).sigmoid().detach().cpu().numpy() / NFOLDS torch_pred = np.median(torch_pred) tf_pred = np.median(np.mean([model(x_tt, training = False ).numpy() for model in tf_models],axis=0)) pred = torch_pred * 0.5 + tf_pred * 0.5 pred_df.action = np.where(pred >= 0.4914, 1, 0 ).astype(int) else: pred_df.action = 0 env.predict(pred_df )<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,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, f) def load_pickle(load_path): with open(load_path, 'rb')as f: message_dict = pickle.load(f) return message_dict feat_cols = [f'feature_{i}' for i in range(130)] target_cols = ['action', 'action_1', 'action_2', 'action_3', 'action_4'] f_mean = np.load(f'{CACHE_PATH}/f_mean_online.npy') all_feat_cols = [col for col in feat_cols] all_feat_cols.extend(['cross_41_42_43', 'cross_1_2']) 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.2) dropout_rate = 0.2 hidden_size = 256 self.dense1 = nn.Linear(len(all_feat_cols), hidden_size) self.batch_norm1 = nn.BatchNorm1d(hidden_size) self.dropout1 = nn.Dropout(dropout_rate) self.dense2 = nn.Linear(hidden_size+len(all_feat_cols), hidden_size) self.batch_norm2 = nn.BatchNorm1d(hidden_size) self.dropout2 = nn.Dropout(dropout_rate) self.dense3 = nn.Linear(hidden_size+hidden_size, hidden_size) self.batch_norm3 = nn.BatchNorm1d(hidden_size) self.dropout3 = nn.Dropout(dropout_rate) self.dense4 = nn.Linear(hidden_size+hidden_size, hidden_size) self.batch_norm4 = nn.BatchNorm1d(hidden_size) self.dropout4 = nn.Dropout(dropout_rate) self.dense5 = nn.Linear(hidden_size+hidden_size, len(target_cols)) self.Relu = nn.ReLU(inplace=True) self.PReLU = nn.PReLU() self.LeakyReLU = nn.LeakyReLU(negative_slope=0.01, inplace=True) self.RReLU = nn.RReLU() def forward(self, x): x = self.batch_norm0(x) x = self.dropout0(x) x1 = self.dense1(x) x1 = self.batch_norm1(x1) x1 = self.LeakyReLU(x1) x1 = self.dropout1(x1) x = torch.cat([x, x1], 1) x2 = self.dense2(x) x2 = self.batch_norm2(x2) x2 = self.LeakyReLU(x2) x2 = self.dropout2(x2) x = torch.cat([x1, x2], 1) x3 = self.dense3(x) x3 = self.batch_norm3(x3) x3 = self.LeakyReLU(x3) x3 = self.dropout3(x3) x = torch.cat([x2, x3], 1) x4 = self.dense4(x) x4 = self.batch_norm4(x4) x4 = self.LeakyReLU(x4) x4 = self.dropout4(x4) x = torch.cat([x3, x4], 1) x = self.dense5(x) return x if True: device = torch.device("cuda:0") 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)) model.eval() model_list.append(model) <choose_model_class>
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)) : x = tf.keras.layers.Dense(hidden_units[i] )(x) x = tf.keras.layers.BatchNormalization()(x) x = tf.keras.layers.Activation(tf.keras.activations.swish )(x) x = tf.keras.layers.Dropout(dropout_rates[i + 1] )(x) x = tf.keras.layers.Dense(num_labels )(x) out = tf.keras.layers.Activation("sigmoid" )(x) model = tf.keras.models.Model(inputs=inp, outputs=out) model.compile( optimizer=tfa.optimizers.RectifiedAdam(learning_rate=learning_rate), loss=tf.keras.losses.BinaryCrossentropy(label_smoothing=label_smoothing), metrics=tf.keras.metrics.AUC(name="AUC"), ) return model epochs = 200 batch_size = 4096 hidden_units = [160, 160, 160] dropout_rates = [0.2, 0.2, 0.2, 0.2] label_smoothing = 1e-2 learning_rate = 1e-3 tf.keras.backend.clear_session() tf.random.set_seed(SEED) clf = create_mlp( len(feat_cols), 5, hidden_units, dropout_rates, label_smoothing, learning_rate ) clf.load_weights('.. /input/jane-street-with-keras-nn-overfit/model.h5') tf_models = [clf]<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
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 = 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 np.percentile(y_pred[:n].to('cpu'), 52, interpolation="nearest") except Exception as e: print("Prediction error on video %s: %s" %(video_path, str(e))) return 0.481
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.iloc[0]<load_pretrained>
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,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'].values)> 0 ).astype(int) df_train, df_test = train_test_split(df_raw, test_size=0.2, shuffle=True, random_state=150) features = [c for c in df_train.columns if "feature" in c] all_feat_cols = [col for col in features] del df_raw, df_train neutral_values = median df_test.fillna(neutral_values,inplace=True) X_test = df_test.loc[:, df_test.columns.str.contains('feature')] X_test_extended = df_test.loc[:, df_test.columns.str.contains('feature')] X_test_extended['cross_41_42_43'] = X_test_extended['feature_41'] + X_test_extended['feature_42'] + X_test_extended['feature_43'] X_test_extended['cross_1_2'] = X_test_extended['feature_1'] /(X_test_extended['feature_2'] + 1e-5) all_feat_cols.extend(['cross_41_42_43', 'cross_1_2']) y_action_test = df_test['action'].to_numpy() del df_test <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
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(feature_data), len(model_list))) for model in model_list: multiple_preds += model(torch.tensor(feature_data, dtype=torch.float ).to(device)).sigmoid().detach().cpu().numpy() / NFOLDS torch_pred = np.median(multiple_preds, axis=1) torch_preds.append(torch_pred) resnet_preds = np.concatenate(torch_preds) mlp_preds = np.median(tf_models[0](X_test.values, training = False ).numpy() , axis=1) five_preds = [] for i in range(5): pred_prob = xgb_clfs[i].predict_proba(X_test)[:,1] five_preds.append(pred_prob) five_preds = np.array(five_preds ).T xgboost_preds = np.median(five_preds, axis=1) th = 0.5 preds = np.mean(np.vstack([resnet_preds, mlp_preds, xgboost_preds] ).T, axis=1) actions_predicted = np.where(preds >= th, 1, 0 ).astype(int) print(preds.shape) print(actions_predicted.shape) print(metrics.accuracy_score(y_action_test, actions_predicted))<statistical_test>
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_tt[:, 43] cross_1_2 = x_tt[:, 1] /(x_tt[:, 2] + 1e-5) feature_inp = np.concatenate(( x_tt, np.array(cross_41_42_43 ).reshape(x_tt.shape[0], 1), np.array(cross_1_2 ).reshape(x_tt.shape[0], 1), ), axis=1) torch_pred = np.zeros(( 1, len(target_cols))) for model in model_list: torch_pred += model(torch.tensor(feature_inp, dtype=torch.float ).to(device)).sigmoid().detach().cpu().numpy() / NFOLDS torch_pred = np.median(torch_pred) tf_pred = np.median(np.mean([model(x_tt, training = False ).numpy() for model in tf_models],axis=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)* median.values five_preds = [] for i in range(5): pred_prob = xgb_clfs[i].predict_proba(x_tt)[:,1] five_preds.append(pred_prob) five_preds = np.array(five_preds ).T xgb_pred = np.median(five_preds, axis=1) pred =(torch_pred + tf_pred + xgb_pred)/ 3.0 pred_df.action = np.where(pred >= th, 1, 0 ).astype(int) else: pred_df.action = 0 env.predict(pred_df )<load_from_csv>
!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(units )(x1) x1 = tf.keras.layers.BatchNormalization()(x1) x1 = tf.keras.layers.Activation(tf.keras.activations.swish )(x1) x1 = tf.keras.layers.Dropout(0.25 )(x1) x2 = tf.keras.layers.BatchNormalization()(input) x2 = tf.keras.layers.Dropout(0.25 )(x2) for units in HIDDEN_LAYER_2: x2 = tf.keras.layers.Dense(units )(x2) x2 = tf.keras.layers.BatchNormalization()(x2) x2 = tf.keras.layers.Activation(tf.keras.activations.swish )(x2) x2 = tf.keras.layers.Dropout(0.25 )(x2) x3 = tf.keras.layers.BatchNormalization()(input) x3 = tf.keras.layers.Dropout(0.25 )(x3) for units in HIDDEN_LAYER_3: x3 = tf.keras.layers.Dense(units )(x3) x3 = tf.keras.layers.BatchNormalization()(x3) x3 = tf.keras.layers.Activation(tf.keras.activations.swish )(x3) x3 = tf.keras.layers.Dropout(0.25 )(x3) x = tf.keras.layers.concatenate([x1, x2, x3]) output = tf.keras.layers.Dense(TARGET_NUM )(x) model = tf.keras.models.Model(inputs=input, outputs=output) model.compile( optimizer = tf.optimizers.Adam(learning_rate=1e-3), metrics = tf.keras.metrics.MeanSquaredError(name='mean_squared_error'), loss = "MSE", ) display(plot_model(model)) print('Done!' )<train_model>
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,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 = 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 np.percentile(y_pred[:n].to('cpu'), 52, interpolation="nearest") except Exception as e: print("Prediction error on video %s: %s" %(video_path, str(e))) return 0.481
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(predictions )
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.values pred = model(X_test, training = False ).numpy() pred = np.mean(pred) pred_df.action = np.where(pred > THRESHOLD, 1, 0 ).astype(int) else: pred_df.action = 0 env.predict(pred_df) <import_modules>
%%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-market-prediction/example_sample_submission.csv') <train_model>
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.version.cuda) print("cuDNN version:", torch.backends.cudnn.version()) gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" )
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(hidden_units[i] )(x) x = tf.keras.layers.BatchNormalization()(x) x = tf.keras.layers.Activation(tf.keras.activations.swish )(x) x = tf.keras.layers.Dropout(dropout_rates[i + 1] )(x) x = tf.keras.layers.Dense(num_labels )(x) out = tf.keras.layers.Activation("sigmoid" )(x) model = tf.keras.models.Model(inputs=inp, outputs=out) model.compile( optimizer=tfa.optimizers.RectifiedAdam(learning_rate=learning_rate), loss=tf.keras.losses.BinaryCrossentropy(label_smoothing=label_smoothing), metrics=tf.keras.metrics.AUC(name="AUC"), ) return model<choose_model_class>
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_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) input_size = 224 mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std) def isotropically_resize_image(img, size, resample=cv2.INTER_AREA): h, w = img.shape[:2] if w > h: h = h * size // w w = size else: w = w * size // h h = size resized = cv2.resize(img,(w, h), interpolation=resample) return resized def make_square_image(img): h, w = img.shape[:2] size = max(h, w) t = 0 b = size - h l = 0 r = size - w return cv2.copyMakeBorder(img, t, b, l, r, cv2.BORDER_CONSTANT, value=0) 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) 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 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 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) speed_test = False 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))) predictions_resnext = predict_on_video_set(test_videos, num_workers=4) submission_df_resnext = pd.DataFrame({"filename": test_videos, "label": predictions_resnext}) submission_df_resnext.to_csv("submission_resnext.csv", index=False )
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.ReduceLROnPlateau( monitor = 'AUC', factor = 0.75, patience = 3, verbose = 0, min_delta = 1e-3, mode = 'max',min_lr=1e-8) early_stopping=keras.callbacks.EarlyStopping(patience=15,min_delta=1e-2,monitor='loss',restore_best_weights=True) model2.fit(X_train, y_train, epochs=epochs, batch_size=batch_size,callbacks=[reduce_lr,early_stopping]) gc.collect()<choose_model_class>
!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( monitor = 'AUC', factor = 0.50, patience = 3, verbose = 0, min_delta = 1e-3, mode = 'max',min_lr=1e-8) early_stopping=keras.callbacks.EarlyStopping(patience=15,min_delta=1e-3,monitor='loss',restore_best_weights=True) model3.fit(X_train, y_train, epochs=epochs, batch_size=batch_size,callbacks=[reduce_lr,early_stopping]) gc.collect()<predict_on_test>
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 = False ).numpy() for model in models],axis=0) pred=f(pred) pred_df.action = np.where(pred >= th, 1, 0 ).astype(int) else: pred_df.action = 0 env.predict(pred_df )<set_options>
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/input/blazeface-pytorch/anchors.npy") _ = facedet.train(False) 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) input_size = 150 mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )
Deepfake Detection Challenge