kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
10,857,169
def preprocess(df): df["hour"] = df["timestamp"].dt.hour df["weekend"] = df["timestamp"].dt.weekday df["month"] = df["timestamp"].dt.month df["dayofweek"] = df["timestamp"].dt.dayofweek <categorify>
optimizer = AdamW(model.parameters() , lr=1e-5, eps=1e-8) epochs = 4 scheduler = get_linear_schedule_with_warmup( optimizer, num_warmup_steps=0, num_training_steps=len(dataloader_train)*epochs )
Natural Language Processing with Disaster Tweets
10,857,169
preprocess(train_df )<sort_values>
def f1_score_func(preds, labels): preds_flat = np.argmax(preds, axis =1 ).flatten() labels_flat = labels.flatten() return f1_score(labels_flat, preds_flat, average='weighted') def accuracy_per_class(preds, labels): preds_flat = np.argmax(preds, axis =1 ).flatten() labels_flat = labels.flatten() for label in np.unique(...
Natural Language Processing with Disaster Tweets
10,857,169
if use_ucf and use_sort: train_df = train_df.sort_values('month') train_df = train_df.reset_index()<categorify>
seed_val = 10 random.seed(seed_val) np.random.seed(seed_val) torch.manual_seed(seed_val) torch.cuda.manual_seed_all(seed_val) device = 'cuda' if torch.cuda.is_available() else 'cpu' model.to(device) print(device)
Natural Language Processing with Disaster Tweets
10,857,169
df_group = train_df.groupby('building_id')['meter_reading_log1p'] building_median = df_group.median().astype(np.float16) train_df['building_median'] = train_df['building_id'].map(building_median) del df_group<count_missing_values>
def evaluate(dataloader_val): model.eval() loss_val_total = 0 predictions, true_vals = [], [] for batch in dataloader_val: batch = tuple(b.to(device)for b in batch) inputs = {'input_ids': batch[0], 'attention_mask': batch[1], 'labels': batch[2], } with torch.no_grad() : outputs = model(**inputs) loss = outputs[0] log...
Natural Language Processing with Disaster Tweets
10,857,169
weather_train_df.isna().sum()<groupby>
for epoch in tqdm(range(1, epochs+1)) : model.train() training_loss=0 progress_bar = tqdm(dataloader_train, desc='Epoch {:1d}'.format(epoch), leave=False, disable=False ) for batch in progress_bar: model.zero_grad() batch = tuple(b.to(device)for b in batch) inputs = { 'input_ids': batch[0], 'attention_mask':batch[1]...
Natural Language Processing with Disaster Tweets
10,857,169
weather_train_df.groupby('site_id' ).apply(lambda group: group.isna().sum() )<groupby>
_, predictions, true_vals = evaluate(dataloader_val )
Natural Language Processing with Disaster Tweets
10,857,169
weather_train_df = weather_train_df.groupby('site_id' ).apply(lambda group: group.interpolate(limit_direction='both'))<groupby>
accuracy_per_class(predictions, true_vals )
Natural Language Processing with Disaster Tweets
10,857,169
weather_train_df.groupby('site_id' ).apply(lambda group: group.isna().sum() )<data_type_conversions>
model.eval() predictions=[] for batch in dataloader_test: batch = tuple(b.to(device)for b in batch) inputs = {'input_ids': batch[0], 'attention_mask': batch[1] } with torch.no_grad() : outputs = model(**inputs) logits = outputs[0] logits = logits.detach().cpu().numpy() predictions.append(np.argmax(logits,axis=1))
Natural Language Processing with Disaster Tweets
10,857,169
def add_lag_feature(weather_df, window=3): group_df = weather_df.groupby('site_id') cols = ['air_temperature', 'cloud_coverage', 'dew_temperature', 'precip_depth_1_hr', 'sea_level_pressure', 'wind_direction', 'wind_speed'] rolled = group_df[cols].rolling(window=window, min_periods=0) lag_mean = rolled.mean().reset_in...
prediction = list(chain.from_iterable(predictions))
Natural Language Processing with Disaster Tweets
10,857,169
set_localtime(weather_train_df )<categorify>
sub= pd.read_csv('.. /input/nlp-getting-started/sample_submission.csv') sub.head()
Natural Language Processing with Disaster Tweets
10,857,169
primary_use_list = building_meta_df['primary_use'].unique() primary_use_dict = {key: value for value, key in enumerate(primary_use_list)} print('primary_use_dict: ', primary_use_dict) building_meta_df['primary_use'] = building_meta_df['primary_use'].map(primary_use_dict) gc.collect()<feature_engineering>
sub['target']=prediction
Natural Language Processing with Disaster Tweets
10,857,169
train_df = reduce_mem_usage(train_df, use_float16=True) building_meta_df = reduce_mem_usage(building_meta_df, use_float16=True) weather_train_df = reduce_mem_usage(weather_train_df, use_float16=True )<define_variables>
sub.to_csv('submission.csv', index=False )
Natural Language Processing with Disaster Tweets
10,857,169
<prepare_x_and_y><EOS>
sub.to_csv('submission.csv', index=False )
Natural Language Processing with Disaster Tweets
10,758,120
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<train_model>
Bidirectional, Lambda, Conv1D, MaxPooling1D, GRU,GlobalMaxPooling1D,GlobalAveragePooling1D, concatenate
Natural Language Processing with Disaster Tweets
10,758,120
def fit_lgbm(train, val, devices=(-1,), seed=None, cat_features=None, num_rounds=1500, lr=0.1, bf=0.1): X_train, y_train = train X_valid, y_valid = val metric = 'l2' params = {'num_leaves': 31, 'objective': 'regression', 'learning_rate': lr, "boosting": "gbdt", "bagging_freq": 5, "bagging_fraction": bf, "feature_frac...
class CyclicLR(Callback): def __init__(self, base_lr=0.001, max_lr=0.006, step_size=2000., mode='triangular', gamma=1., scale_fn=None, scale_mode='cycle'): super(CyclicLR, self ).__init__() self.base_lr = base_lr self.max_lr = max_lr self.step_size = step_size self.mode = mode self.gamma = gamma if scale_fn == None: if...
Natural Language Processing with Disaster Tweets
10,758,120
seed = 666 shuffle = False kf = KFold(n_splits=folds, shuffle=shuffle, random_state=seed) oof_total = 0<split>
data = pd.read_csv(".. /input/nlp-getting-started/train.csv" )
Natural Language Processing with Disaster Tweets
10,758,120
target_meter = 0 X_train, y_train = create_X_y(train_df, target_meter=target_meter) y_valid_pred_total = np.zeros(X_train.shape[0]) gc.collect() print('target_meter', target_meter, X_train.shape) cat_features = [X_train.columns.get_loc(cat_col)for cat_col in category_cols] print('cat_features', cat_features) models...
MAX_SEQUENCE_LENGTH = 60 MAX_NB_WORDS = 30000 EMBEDDING_DIM = 300 tokenizer = Tokenizer(num_words=MAX_NB_WORDS) tokenizer.fit_on_texts(data['text'].values) sequences = tokenizer.texts_to_sequences(data['text'].values) word_index = tokenizer.word_index print('Found %s unique tokens.' % len(word_index)) pad_text = pad...
Natural Language Processing with Disaster Tweets
10,758,120
target_meter = 1 X_train, y_train = create_X_y(train_df, target_meter=target_meter) y_valid_pred_total = np.zeros(X_train.shape[0]) gc.collect() print('target_meter', target_meter, X_train.shape) cat_features = [X_train.columns.get_loc(cat_col)for cat_col in category_cols] print('cat_features', cat_features) models...
embeddings_index = {} f = open('.. /input/glove840b300dtxt/glove.840B.300d.txt','r',encoding='utf-8') for line in f: values = line.split(' ') word = values[0] coefs = np.asarray([float(val)for val in values[1:]]) embeddings_index[word] = coefs f.close() print(' Found %s word vectors.' % len(embeddings_index)) embedd...
Natural Language Processing with Disaster Tweets
10,758,120
target_meter = 2 X_train, y_train = create_X_y(train_df, target_meter=target_meter) y_valid_pred_total = np.zeros(X_train.shape[0]) gc.collect() print('target_meter', target_meter, X_train.shape) cat_features = [X_train.columns.get_loc(cat_col)for cat_col in category_cols] print('cat_features', cat_features) models...
X_train,X_test, y_train, y_test = train_test_split(pad_text,data['target'].values, test_size=0.33,shuffle=True,random_state=124, stratify=data['target'] )
Natural Language Processing with Disaster Tweets
10,758,120
target_meter = 3 X_train, y_train = create_X_y(train_df, target_meter=target_meter) y_valid_pred_total = np.zeros(X_train.shape[0]) gc.collect() print('target_meter', target_meter, X_train.shape) cat_features = [X_train.columns.get_loc(cat_col)for cat_col in category_cols] print('cat_features', cat_features) models...
input_text = Input(shape=(60,),dtype='int64') embedding_layer = Embedding(embedding_matrix.shape[0], embedding_matrix.shape[1], weights=[embedding_matrix], trainable=False, mask_zero=True )(input_text) text_embed = SpatialDropout1D(0.4 )(embedding_layer) hidden_states = Bidirectional(LSTM(units=300, return_sequences...
Natural Language Processing with Disaster Tweets
10,758,120
print('oof score meter0 =', np.sqrt(oof0)) print('oof score meter1 =', np.sqrt(oof1)) print('oof score meter2 =', np.sqrt(oof2)) print('oof score meter3 =', np.sqrt(oof3)) print('oof score total =', np.sqrt(oof_total / len(train_df)) )<drop_column>
val_preds = BiLSTM.predict(X_test) val_preds = np.round(val_preds ).astype(int) print(classification_report(y_test,val_preds,target_names = ['Not Relevant', 'Relevant']))
Natural Language Processing with Disaster Tweets
10,758,120
del train_df, weather_train_df, building_meta_df gc.collect()<feature_engineering>
input_text = Input(shape=(60,),dtype='int64') embedding_layer = Embedding(embedding_matrix.shape[0], embedding_matrix.shape[1], weights=[embedding_matrix], trainable=False, mask_zero=True )(input_text) text_embed = SpatialDropout1D(0.4 )(embedding_layer) conv_layer = Conv1D(300, kernel_size=3, padding="valid", activ...
Natural Language Processing with Disaster Tweets
10,758,120
print('loading...') test_df = pd.read_feather(root/'test.feather') weather_test_df = pd.read_feather(root/'weather_test.feather') building_meta_df = pd.read_feather(root/'building_metadata.feather') set_localtime(weather_test_df) print('preprocessing building...') test_df['date'] = test_df['timestamp'].dt.date pr...
val_preds = CNNRNN.predict(X_test) val_preds = np.round(val_preds ).astype(int) print(classification_report(y_test,val_preds,target_names = ['Not Relevant', 'Relevant']))
Natural Language Processing with Disaster Tweets
10,758,120
sample_submission = pd.read_feather(os.path.join(root, 'sample_submission.feather')) reduce_mem_usage(sample_submission )<merge>
input_text = Input(shape=(60,),dtype='int64') embedding_layer = Embedding(embedding_matrix.shape[0], embedding_matrix.shape[1], weights=[embedding_matrix], trainable=False, mask_zero=True )(input_text) text_embed = SpatialDropout1D(0.4 )(embedding_layer) gru_layer = Bidirectional(GRU(300, return_sequences=True))(tex...
Natural Language Processing with Disaster Tweets
10,758,120
def create_X(test_df, target_meter): target_test_df = test_df[test_df['meter'] == target_meter] target_test_df = target_test_df.merge(building_meta_df, on='building_id', how='left') target_test_df = target_test_df.merge(weather_test_df, on=['site_id', 'timestamp'], how='left') X_test = target_test_df[feature_cols + c...
val_preds = RNNCNN.predict(X_test) val_preds = np.round(val_preds ).astype(int) print(classification_report(y_test,val_preds,target_names = ['Not Relevant', 'Relevant']))
Natural Language Processing with Disaster Tweets
10,758,120
def pred(X_test, models, batch_size=1000000): iterations =(X_test.shape[0] + batch_size -1)// batch_size print('iterations', iterations) y_test_pred_total = np.zeros(X_test.shape[0]) for i, model in enumerate(models): print(f'predicting {i}-th model') for k in tqdm(range(iterations)) : y_pred_test = model.predict(X_...
train,_, y_train, _ = train_test_split(data['text'].values,data['target'].values, test_size=0.2,shuffle=True,random_state=124, stratify=data['target'] )
Natural Language Processing with Disaster Tweets
10,758,120
sample_submission.loc[test_df['meter'] == 0, 'meter_reading'] = np.expm1(y_test0) sample_submission.loc[test_df['meter'] == 1, 'meter_reading'] = np.expm1(y_test1) sample_submission.loc[test_df['meter'] == 2, 'meter_reading'] = np.expm1(y_test2) sample_submission.loc[test_df['meter'] == 3, 'meter_reading'] = np.expm...
MAX_SEQUENCE_LENGTH = 60 MAX_NB_WORDS = 30000 EMBEDDING_DIM = 300 sequences = tokenizer.texts_to_sequences(train) word_index = tokenizer.word_index print('Found %s unique tokens.' % len(word_index)) pad_text = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH )
Natural Language Processing with Disaster Tweets
10,758,120
if not debug: sample_submission.to_csv('submission.csv', index=False, float_format='%.4f' )<feature_engineering>
bilstm=BiLSTM.predict(pad_text) cr = CNNRNN.predict(pad_text) rc = RNNCNN.predict(pad_text )
Natural Language Processing with Disaster Tweets
10,758,120
leak_score0 = 0 leak_df = pd.read_pickle(ucf_root/'site0.pkl') leak_df['meter_reading'] = leak_df.meter_reading_scraped leak_df.drop(['meter_reading_original','meter_reading_scraped'], axis=1, inplace=True) leak_df.fillna(0, inplace=True) leak_df = leak_df[leak_df.timestamp.dt.year > 2016] leak_df.loc[leak_df.meter_...
prediction = pd.DataFrame({"BiLSTM":bilstm.flatten() ,"CR":cr.flatten() ,"RC":rc.flatten() ,"target":y_train} )
Natural Language Processing with Disaster Tweets
10,758,120
leak_score1 = 0 leak_df = pd.read_pickle(ucl_root/'site1.pkl') leak_df['meter_reading'] = leak_df.meter_reading_scraped leak_df.drop(['meter_reading_scraped'], axis=1, inplace=True) leak_df.fillna(0, inplace=True) leak_df = leak_df[leak_df.timestamp.dt.year > 2016] leak_df.loc[leak_df.meter_reading < 0, 'meter_readi...
clf = Sequential([ Dense(3,activation = 'relu'), Dense(1,activation= 'sigmoid') ]) clf.compile(loss = 'binary_crossentropy',optimizer = Adam(3e-5),metrics = ['acc'] )
Natural Language Processing with Disaster Tweets
10,758,120
if not debug: sample_submission.to_csv('submission_ucf_replaced.csv', index=False, float_format='%.4f' )<compute_test_metric>
history =clf.fit(prediction.loc[:,['BiLSTM','CR','RC']].values,prediction.iloc[:,-1],validation_split= 0.1,batch_size = 5,epochs = 32 )
Natural Language Processing with Disaster Tweets
10,758,120
print('UCF score = ', np.sqrt(leak_score0)) print('UCL score = ', np.sqrt(leak_score1))<define_variables>
test = pd.read_csv(".. /input/nlp-getting-started/test.csv" )
Natural Language Processing with Disaster Tweets
10,758,120
sub_path = ".. /input/ashrae-ensembling-1" all_files = os.listdir(sub_path) all_files<feature_engineering>
MAX_SEQUENCE_LENGTH = 60 MAX_NB_WORDS = 30000 EMBEDDING_DIM = 300 sequences = tokenizer.texts_to_sequences(test.text.values) pad_text = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH )
Natural Language Processing with Disaster Tweets
10,758,120
concat_sub['m_max'] = concat_sub.iloc[:, 1:].max(axis=1) concat_sub['m_min'] = concat_sub.iloc[:, 1:].min(axis=1) concat_sub['m_median'] = concat_sub.iloc[:, 1:].median(axis=1 )<define_variables>
bilstm_test = BiLSTM.predict(pad_text ).flatten() cr_test = CNNRNN.predict(pad_text ).flatten() rc_test = RNNCNN.predict(pad_text ).flatten()
Natural Language Processing with Disaster Tweets
10,758,120
cutoff_lo = 0.8 cutoff_hi = 0.2<feature_engineering>
test_predictions = clf.predict(np.stack([bilstm_test,cr_test,rc_test],axis=-1)).flatten() test_predictions = np.round(test_predictions ).astype(int )
Natural Language Processing with Disaster Tweets
10,758,120
rank = np.tril(concat_sub.iloc[:,1:ncol].corr().values,-1) m_gmean = 0 n = 8 while rank.max() >0: mx = np.unravel_index(rank.argmax() , rank.shape) m_gmean += n*(np.log(concat_sub.iloc[:, mx[0]+1])+ np.log(concat_sub.iloc[:, mx[1]+1])) /2 rank[mx] = 0 n += 1<feature_engineering>
submission = pd.read_csv(".. /input/nlp-getting-started/sample_submission.csv") submission['target'] = test_predictions
Natural Language Processing with Disaster Tweets
10,758,120
concat_sub['m_mean'] = np.exp(m_gmean/(n-1)**2 )<save_to_csv>
submission.to_csv("/kaggle/working/submission.csv",index = False )
Natural Language Processing with Disaster Tweets
10,784,248
concat_sub['meter_reading'] = concat_sub['m_mean'] concat_sub[['row_id', 'meter_reading']].to_csv('stack_mean.csv', index=False, float_format='%.6f' )<save_to_csv>
!pip install -q tensorflow-text
Natural Language Processing with Disaster Tweets
10,784,248
concat_sub['meter_reading'] = concat_sub['m_median'] concat_sub[['row_id', 'meter_reading']].to_csv('stack_median.csv', index=False, float_format='%.6f' )<save_to_csv>
import numpy as np import pandas as pd import numpy as np import tensorflow as tf from tqdm import tqdm from sklearn.model_selection import train_test_split import time import numpy as np import tensorflow_hub as hub import tensorflow_text
Natural Language Processing with Disaster Tweets
10,784,248
concat_sub['meter_reading'] = np.where(np.all(concat_sub.iloc[:,1:7] > cutoff_lo, axis=1), 1, np.where(np.all(concat_sub.iloc[:,1:7] < cutoff_hi, axis=1), 0, concat_sub['m_median'])) concat_sub[['row_id', 'meter_reading']].to_csv('stack_pushout_median.csv', index=False, float_format='%.6f' )<feature_engineering>
use = hub.load("https://tfhub.dev/google/universal-sentence-encoder-large/5" )
Natural Language Processing with Disaster Tweets
10,784,248
concat_sub['meter_reading'] = np.where(np.all(concat_sub.iloc[:,1:7] > cutoff_lo, axis=1), concat_sub['m_max'], np.where(np.all(concat_sub.iloc[:,1:7] < cutoff_hi, axis=1), concat_sub['m_min'], concat_sub['m_mean'])) concat_sub[['row_id', 'meter_reading']].to_csv('stack_minmax_mean.csv', index=False, float_format='%.6f...
train_df = pd.read_csv("/kaggle/input/nlp-getting-started/train.csv") test_df = pd.read_csv("/kaggle/input/nlp-getting-started/test.csv" )
Natural Language Processing with Disaster Tweets
10,784,248
concat_sub['meter_reading'] = np.where(np.all(concat_sub.iloc[:,1:7] > cutoff_lo, axis=1), concat_sub['m_max'], np.where(np.all(concat_sub.iloc[:,1:7] < cutoff_hi, axis=1), concat_sub['m_min'], concat_sub['m_median'])) concat_sub[['row_id', 'meter_reading']].to_csv('stack_minmax_median.csv', index=False, float_format='...
def embedd(dataset): data = [] for i in tqdm(dataset): embeddings = use(i) embeddings = tf.reshape(embeddings, [-1] ).numpy() data.append(embeddings) return data
Natural Language Processing with Disaster Tweets
10,784,248
concat_sub['meter_reading'] = concat_sub['mol0'].rank(method ='min')+ concat_sub['mol1'].rank(method ='min')+ concat_sub['mol2'].rank(method ='min') concat_sub['meter_reading'] =(concat_sub['meter_reading']-concat_sub['meter_reading'].min())/(concat_sub['meter_reading'].max() - concat_sub['meter_reading'].min()) conc...
x_training = np.reshape(train_df.text.values,(len(train_df.text.values),1)) x_topredict = np.reshape(test_df.text.values,(len(test_df.text.values),1)) print("Embedding training data...") x_training = embedd(x_training) print("Embedding data for prediction...") x_topredict = embedd(x_topredict )
Natural Language Processing with Disaster Tweets
10,784,248
register_matplotlib_converters() sub = None for dirname, _, filenames in os.walk('/kaggle/input/subs20191106/'): for filename in filenames: filename = os.path.join(dirname, filename) print(filename) if sub is None: sub = pd.read_csv(filename) else: sub.meter_reading += pd.read_csv(filename, usecols=['meter_reading']...
x_training = np.array(x_training) y_train = train_df.target.values x_topredict = np.array(x_topredict )
Natural Language Processing with Disaster Tweets
10,784,248
path = '.. /input/clean-weather-data-eda' building = pd.read_csv(f'{path}/building_metadata.csv.gz', dtype={'building_id':np.uint16, 'site_id':np.uint8} )<load_from_csv>
X_train, X_test, y_train, y_test = train_test_split(x_training, y_train,test_size = 0.25, random_state=7 )
Natural Language Processing with Disaster Tweets
10,784,248
train = pd.read_csv(f'{path}/train.csv.gz', dtype={'building_id':np.uint16, 'meter':np.uint8}, parse_dates=['timestamp']) train = train.merge(building, on='building_id', how='left') train.head()<load_from_csv>
clf = linear_model.RidgeClassifier() clf.fit(X_train, y_train )
Natural Language Processing with Disaster Tweets
10,784,248
test = pd.read_csv(f'{path}/test.csv.gz', dtype={'building_id':np.uint16, 'meter':np.uint8}, parse_dates=['timestamp']) test['meter_reading'] = sub.meter_reading test = test.merge(building, on='building_id', how='left') test.head()<load_from_csv>
y_pred = clf.predict(X_test) cm = confusion_matrix(y_test, y_pred) print(cm) print("The accuracy of the model in the tested data is: ",accuracy_score(y_test, y_pred)) print("The f1 score of the model in the tested data is: ",f1_score(y_test, y_pred))
Natural Language Processing with Disaster Tweets
10,784,248
weather_trn = pd.read_csv(f'{path}/weather_train.csv.gz', parse_dates=['timestamp'], dtype={'site_id':np.uint8, 'air_temperature':np.float16}, usecols=['site_id', 'timestamp', 'air_temperature']) weather_tst = pd.read_csv(f'{path}/weather_test.csv.gz', parse_dates=['timestamp'], dtype={'site_id':np.uint8, 'air_tempera...
log_clf = LogisticRegression() rnd_clf = RandomForestClassifier() svm_clf = SVC() log_clf.fit(X_train, y_train) rnd_clf.fit(X_train, y_train) svm_clf.fit(X_train, y_train )
Natural Language Processing with Disaster Tweets
10,784,248
sub.to_csv(f'submission.csv', index=False, float_format='%g' )<define_variables>
y_pred = rnd_clf.predict(X_test) y_pred =(y_pred > 0.5) cm = confusion_matrix(y_test, y_pred) print(cm) print("The accuracy of the model Random Forest in the tested data is: ",accuracy_score(y_test, y_pred)) print("The f1 score of the model Random Forest in the tested data is: ",f1_score(y_test, y_pred))
Natural Language Processing with Disaster Tweets
10,784,248
print(os.listdir("./")) TRAIN_PREFIX = '.. /input/the-nature-conservancy-fisheries-monitoring/train' VALIDATION_PREFIX = './data/fish/test_stg1' ORIGINAL_IMG_HEIGHT = 750 ORIGINAL_IMG_WIDTH = 1200 IMG_HEIGHT = 468 IMG_WIDTH = 752 ANCHOR_WIDTH = 100 ANCHOR_HEIGHT = 100 label_encoder = dict() str_labels = [] FEATURE_SHAP...
sample_submission = pd.read_csv("/kaggle/input/nlp-getting-started/sample_submission.csv") y_pred = svm_clf.predict(x_topredict) y_pred =(y_pred > 0.5 ).astype(int) sample_submission["target"] = y_pred sample_submission.to_csv("submission_SVC_universal_sentence_encoder.csv", index=False )
Natural Language Processing with Disaster Tweets
11,447,202
%matplotlib inline <define_variables>
print("TF version: ", tf.__version__) print("Hub version: ", hub.__version__ )
Natural Language Processing with Disaster Tweets
11,447,202
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 )<set_options>
pd.set_option('display.max_colwidth', None)
Natural Language Processing with Disaster Tweets
11,447,202
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu<load_pretrained>
train = pd.read_csv('.. /input/nlp-getting-started/train.csv') test = pd.read_csv('.. /input/nlp-getting-started/test.csv') ids = test.id print('Total length of the dataset: ', len(train)+len(test)) print('shape of training set: ', train.shape) print('shape of testing set: ', test.shape )
Natural Language Processing with Disaster Tweets
11,447,202
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 )<load_pretrained>
df_concat = pd.concat([train, test], axis = 0 ).reset_index(drop = True) nulls = pd.DataFrame(np.c_[df_concat.isnull().sum() ,(df_concat.isnull().sum() / len(df_concat)) *100], columns = [' index = df_concat.columns) nulls
Natural Language Processing with Disaster Tweets
11,447,202
frames_per_video = 150 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 )<define_variables>
for df in [train, test, df_concat]: df.keyword.fillna('no_keyword', inplace = True) df.location.fillna('no_location', inplace = True )
Natural Language Processing with Disaster Tweets
11,447,202
input_size =224<normalization>
df_concat.groupby(['location'] ).count().text.sort_values(ascending = False )
Natural Language Processing with Disaster Tweets
11,447,202
mean = [0.43216, 0.394666, 0.37645] std = [0.22803, 0.22145, 0.216989] normalize_transform = Normalize(mean,std )<choose_model_class>
for df in [train, test, df_concat]: df.drop(columns = ['location', 'keyword', 'id'], inplace = True )
Natural Language Processing with Disaster Tweets
11,447,202
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 )<load_pretrained>
nlp = spacy.load("en") sp = spacy.load('en_core_web_sm') nltk.download('stopwords') nltk.download('punkt') spacy_st = nlp.Defaults.stop_words nltk_st = stopwords.words('english') def clean(tweet, http = True, punc = True, lem = True, stop_w = True): if http is True: tweet = re.sub("https?:\/\/t.co\/[A-Za-z0-9]*", ...
Natural Language Processing with Disaster Tweets
11,447,202
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<predict_on_test>
df_concat['cleaned_text'] = df_concat.text.apply(lambda x: clean(x, lem = False, stop_w = 'nltk', http = True, punc = True))
Natural Language Processing with Disaster Tweets
11,447,202
def predict_on_video(video_path, batch_size): try: faces = face_extractor.process_video(video_path) face_extractor.keep_only_best_face(faces) if len(faces)> 0: x = np.zeros(( batch_size, input_size, input_size, 3), dtype=np.uint8) n = 0 for frame_data in faces: for face in frame_data["faces"]: resized_face = isotrop...
cleaned_train = df_concat[:train.shape[0]] cleaned_test = df_concat[train.shape[0]:]
Natural Language Processing with Disaster Tweets
11,447,202
def predict_on_video_set(videos, num_workers): def process_file(i): filename = videos[i] y_pred = predict_on_video(os.path.join(test_dir, filename), batch_size=frames_per_video) return y_pred with ThreadPoolExecutor(max_workers=num_workers)as ex: predictions = ex.map(process_file, range(len(videos))) return list(pred...
%%HTML <a id = "Word_Embeddings"></a> <center> <iframe width="700" height="315" src="https://www.youtube.com/embed/t5wdTK-QtLA" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" style="position: relative;top: 0;left: 0;" allowfullscreen ng-show="showvideo"></iframe> </cente...
Natural Language Processing with Disaster Tweets
11,447,202
speed_test = False<predict_on_test>
!wget --quiet https://raw.githubusercontent.com/tensorflow/models/master/official/nlp/bert/tokenization.py FullTokenizer = tokenization.FullTokenizer
Natural Language Processing with Disaster Tweets
11,447,202
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)) )<predict_on_test>
ans = input("Which Bert should I use? a.Base uncased b.Large uncased c.Basic cased d.Large cased ") if ans is 'a': BERT_MODEL_HUB = 'https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/2' disc = 'Base_uncased' elif ans is 'b': BERT_MODEL_HUB = 'https://tfhub.dev/tensorflow/bert_en_uncased_L-24_H-1024_A-16/2' ...
Natural Language Processing with Disaster Tweets
11,447,202
predictions = predict_on_video_set(test_videos, num_workers=4 )<save_to_csv>
sentence = 'Terrorist will crush the Tower' print('Tokenized version of {} is : {} '.format(sentence, tokenizer.tokenize(sentence)) )
Natural Language Processing with Disaster Tweets
11,447,202
submission_df = pd.DataFrame({"filename": test_videos, "label": predictions}) submission_df.to_csv("submission.csv", index=False )<install_modules>
def tokenize_tweets(text_): return tokenizer.convert_tokens_to_ids(['[CLS]'] + tokenizer.tokenize(text_)+ ['[SEP]']) df_concat['tokenized_tweets'] = df_concat.cleaned_text.apply(lambda x: tokenize_tweets(x)) cleaned_train.head(2 )
Natural Language Processing with Disaster Tweets
11,447,202
!pip install.. /input/kaggle-efficientnet-repo/efficientnet-1.0.0-py3-none-any.whl<import_modules>
max_len = len(max(df_concat.tokenized_tweets, key = len)) print('The maximum length of each sequence besed on tokenized tweets is:', max_len) df_concat['padded_tweets'] = df_concat.tokenized_tweets.apply(lambda x: x + [0] *(max_len - len(x))) df_concat.head(2 )
Natural Language Processing with Disaster Tweets
11,447,202
import pandas as pd import tensorflow as tf import cv2 import glob from tqdm.notebook import tqdm import numpy as np import os from keras.layers import * from keras import Model import matplotlib.pyplot as plt import time from keras.applications.xception import Xception import efficientnet.keras as efn<import_modules>
class TweetClassifier: def __init__(self, tokenizer, bert_layer, max_len, lr = 0.0001, epochs = 15, batch_size = 32, activation = 'sigmoid', optimizer = 'SGD', beta_1=0.9, beta_2=0.999, epsilon=1e-07, metrics = 'accuracy', loss = 'binary_crossentropy'): self.lr = lr self.epochs = epochs self.max_len = max_len self.batc...
Natural Language Processing with Disaster Tweets
11,447,202
import torch import torch.nn as nn import torch.nn.functional as F<import_modules>
classifier = TweetClassifier(tokenizer = tokenizer, bert_layer = bert_layer, max_len = max_len, lr = 0.0001, epochs = 3, activation = 'sigmoid', batch_size = 32,optimizer = 'SGD', beta_1=0.9, beta_2=0.999, epsilon=1e-07 )
Natural Language Processing with Disaster Tweets
11,447,202
print("PyTorch version:", torch.__version__) print("CUDA version:", torch.version.cuda) print("cuDNN version:", torch.backends.cudnn.version() )<set_options>
classifier.train(cleaned_train )
Natural Language Processing with Disaster Tweets
11,447,202
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu<define_variables>
!git clone https://github.com/mitramir55/Kaggle_NLP_competition.git perfection = pd.read_csv('Kaggle_NLP_competition/perfect_submission.csv' )
Natural Language Processing with Disaster Tweets
11,447,202
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 )<load_pretrained>
y_pred = np.round(classifier.predict(cleaned_test)) print('The score of prediction: ', sklearn.metrics.f1_score(perfection.target, y_pred, average = 'micro'))
Natural Language Processing with Disaster Tweets
11,447,202
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 )<define_variables>
sample_sub = pd.read_csv('.. /input/nlp-getting-started/sample_submission.csv') ids = sample_sub.id final_submission = pd.DataFrame(np.c_[ids, y_pred.astype('int')], columns = ['id', 'target']) final_submission.to_csv('final_submission.csv', index = False) final_submission.head()
Natural Language Processing with Disaster Tweets
11,852,549
input_size = 224<normalization>
import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from wordcloud import WordCloud
Natural Language Processing with Disaster Tweets
11,852,549
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )<load_pretrained>
df =pd.read_csv('/kaggle/input/nlp-getting-started/train.csv' , encoding='ISO-8859-1') df.head()
Natural Language Processing with Disaster Tweets
11,852,549
frames_per_video = 10 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) <choose_model_class>
df_tweets = df[['text','target']]
Natural Language Processing with Disaster Tweets
11,852,549
class HisResNeXt(models.resnet.ResNet): def __init__(self, training=True): super(HisResNeXt, self ).__init__(block=models.resnet.Bottleneck, layers=[3, 4, 6, 3], groups=32, width_per_group=4) self.fc = nn.Linear(2048, 1 )<load_pretrained>
df_tweets.drop_duplicates(subset=['text'],keep='first',inplace=True) df_tweets.info()
Natural Language Processing with Disaster Tweets
11,852,549
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='' )...
train_df,eval_df = train_test_split(df_tweets,test_size = 0.01 )
Natural Language Processing with Disaster Tweets
11,852,549
checkpoint = torch.load("/kaggle/input/deepfakes-inference-demo/resnext.pth", map_location=gpu) model = HisResNeXt().to(gpu) model.load_state_dict(checkpoint) _ = model.eval() del checkpoint <predict_on_test>
!pip install simpletransformers==0.32.3
Natural Language Processing with Disaster Tweets
11,852,549
def predict_on_video(video_path, batch_size): try: faces = face_extractor.process_video(video_path) face_extractor.keep_only_best_face(faces) if len(faces)> 0: x = np.zeros(( batch_size, input_size, input_size, 3), dtype=np.uint8) n = 0 for frame_data in faces: for face in frame_data["faces"]: resized_face = isotrop...
model = ClassificationModel('bert', 'bert-base-cased', num_labels=2, args={'reprocess_input_data': True, 'overwrite_output_dir': True},use_cuda=False)
Natural Language Processing with Disaster Tweets
11,852,549
cm = detection_graph.as_default() cm.__enter__()<prepare_x_and_y>
train_df2 = pd.DataFrame({ 'text': train_df['text'].replace(r' ', ' ', regex=True), 'label': train_df['target'] }) eval_df2 = pd.DataFrame({ 'text': eval_df['text'].replace(r' ', ' ', regex=True), 'label': eval_df['target'] } )
Natural Language Processing with Disaster Tweets
11,852,549
config = tf.compat.v1.ConfigProto() config.gpu_options.allow_growth = True sess=tf.compat.v1.Session(graph=detection_graph, config=config) image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') boxes_tensor = detection_graph.get_tensor_by_name('detection_boxes:0') scores_tensor = detection_graph.get_ten...
model.train_model(train_df2 )
Natural Language Processing with Disaster Tweets
11,852,549
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=...
result, model_outputs, wrong_predictions = model.eval_model(eval_df2 )
Natural Language Processing with Disaster Tweets
11,852,549
res_predictions =[]<predict_on_test>
lst = [] for arr in model_outputs: lst.append(np.argmax(arr))
Natural Language Processing with Disaster Tweets
11,852,549
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) y_pred = predict_on_video(x, batch_size=frames_per_video) res_predictions.append(y_pred) if a is None: co...
true = eval_df2['label'].tolist() predicted = lst
Natural Language Processing with Disaster Tweets
11,852,549
bottleneck_EfficientNetB1 = efn.EfficientNetB1(weights=None,include_top=False,pooling='avg') inp=Input(( 10,240,240,3)) x=TimeDistributed(bottleneck_EfficientNetB1 )(inp) x = LSTM(128 )(x) x = Dense(64, activation='elu' )(x) x = Dense(1,activation='sigmoid' )(x) model_EfficientNetB1=Model(inp,x) bottleneck_Xcepti...
mat = sklearn.metrics.confusion_matrix(true , predicted) mat
Natural Language Processing with Disaster Tweets
11,852,549
model_EfficientNetB1.load_weights('.. /input/efficientnetb1dfdc/EfficientNetB1-e_2_b_4_f_30-10.h5') model_Xception.load_weights('.. /input/xceptiondfdc/Xception-e_2_b_4_f_30-10.h5' )<statistical_test>
print(sklearn.metrics.classification_report(true,predicted,target_names=['fake','real']))
Natural Language Processing with Disaster Tweets
11,852,549
def get_birghtness(img): return img/img.max() def process_img(img,flip=False): imgs=[] for x in range(10): if flip: 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 )<load_from_csv>
test_df =pd.read_csv('/kaggle/input/nlp-getting-started/test.csv' , encoding='ISO-8859-1') test_df.head()
Natural Language Processing with Disaster Tweets
11,852,549
sample_submission = pd.read_csv(".. /input/deepfake-detection-challenge/sample_submission.csv") test_files=glob.glob('./videos/*.jpg') submission=pd.DataFrame() submission['filename']=os.listdir(( '.. /input/deepfake-detection-challenge/test_videos/')) submission['label']=0.5 filenames=[] batch=[] batch1=[] preds=[]<...
final_prediction = model.predict(list(test_df.text))
Natural Language Processing with Disaster Tweets
11,852,549
new_preds=[] for x,y in zip(preds,res_predictions): new_preds.append(x[0]+(0.2*y)) print(sum(new_preds)/len(new_preds))<feature_engineering>
print('Loading in Submission File...') submit_df = pd.read_csv("/kaggle/input/nlp-getting-started/sample_submission.csv") submit_df['target'] = final_prediction[0] submit_df.to_csv('bert_submit.csv', index=False )
Natural Language Processing with Disaster Tweets
11,852,549
for x,y in zip(new_preds,filenames): submission.loc[submission['filename']==y,'label']=x<save_to_csv>
print("Finished" )
Natural Language Processing with Disaster Tweets
11,792,393
submission.to_csv('submission.csv', index=False) !rm -r videos<set_options>
if torch.cuda.is_available() : device = torch.device("cuda") print('We will use the GPU:', torch.cuda.get_device_name(0)) else: print('No GPU available, using the CPU instead.') device = torch.device("cpu" )
Natural Language Processing with Disaster Tweets
11,792,393
%matplotlib inline <define_variables>
df_train=pd.read_csv("/kaggle/input/nlp-getting-started/train.csv") df_test=pd.read_csv("/kaggle/input/nlp-getting-started/test.csv" )
Natural Language Processing with Disaster Tweets
11,792,393
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 )<import_modules>
def preprocess(text): text=text.lower() text = re.sub(r'https?:\/\/.*[\r ]*', '', text) text = re.sub(r'http?:\/\/.*[\r ]*', '', text) text=text.replace(r'&amp;?',r'and') text=text.replace(r'&lt;',r'<') text=text.replace(r'&gt;',r'>') text = re.sub(r"(?:\@)\w+", '', text) text=text.encode("ascii",errors="ignore" ...
Natural Language Processing with Disaster Tweets
11,792,393
print("PyTorch version:", torch.__version__) print("CUDA version:", torch.version.cuda) print("cuDNN version:", torch.backends.cudnn.version() )<set_options>
df_train["target"].value_counts()
Natural Language Processing with Disaster Tweets
11,792,393
gpu = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") gpu<load_pretrained>
texts = df_train.text.values labels = df_train.target.values
Natural Language Processing with Disaster Tweets
11,792,393
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 )<load_pretrained>
tokenizer = ElectraTokenizer.from_pretrained('google/electra-base-discriminator') model = ElectraForSequenceClassification.from_pretrained('google/electra-base-discriminator',num_labels=2) model.cuda()
Natural Language Processing with Disaster Tweets
11,792,393
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 )<define_variables>
indices=tokenizer.batch_encode_plus(texts,max_length=64,add_special_tokens=True, return_attention_mask=True,pad_to_max_length=True,truncation=True) input_ids=indices["input_ids"] attention_masks=indices["attention_mask"]
Natural Language Processing with Disaster Tweets
11,792,393
input_size = 224<normalization>
train_inputs, validation_inputs, train_labels, validation_labels = train_test_split(input_ids, labels, random_state=42, test_size=0.2) train_masks, validation_masks, _, _ = train_test_split(attention_masks, labels, random_state=42, test_size=0.2 )
Natural Language Processing with Disaster Tweets
11,792,393
mean = [0.485, 0.456, 0.406] std = [0.229, 0.224, 0.225] normalize_transform = Normalize(mean, std )<choose_model_class>
train_inputs = torch.tensor(train_inputs) validation_inputs = torch.tensor(validation_inputs) train_labels = torch.tensor(train_labels, dtype=torch.long) validation_labels = torch.tensor(validation_labels, dtype=torch.long) train_masks = torch.tensor(train_masks, dtype=torch.long) validation_masks = torch.tensor(v...
Natural Language Processing with Disaster Tweets
11,792,393
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 )<load_pretrained>
batch_size = 32 train_data = TensorDataset(train_inputs, train_masks, train_labels) train_sampler = RandomSampler(train_data) train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=batch_size) validation_data = TensorDataset(validation_inputs, validation_masks, validation_labels) validation_sam...
Natural Language Processing with Disaster Tweets