kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
8,536,043
<merge><EOS>
sub.to_csv('submission.csv',index=False )
Natural Language Processing with Disaster Tweets
14,311,680
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<categorify>
!wget --quiet https://raw.githubusercontent.com/tensorflow/models/master/official/nlp/bert/tokenization.py
Natural Language Processing with Disaster Tweets
14,311,680
folds = train.copy() Fold = MultilabelStratifiedKFold(n_splits=5, shuffle=True, random_state=42) for n,(train_index, val_index)in enumerate(Fold.split(folds, folds[target_cols])) : folds.loc[val_index, 'fold'] = int(n) folds['fold'] = folds['fold'].astype(int) print(folds.shape )<prepare_x_and_y>
import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd from nltk.corpus import stopwords import string import plotly.express as px from collections import defaultdict import operator import re from sklearn.model_selection import StratifiedKFold from sklearn.metrics import precision...
Natural Language Processing with Disaster Tweets
14,311,680
class TrainDataset(Dataset): def __init__(self, df, num_features, cat_features, labels): self.cont_values = df[num_features].values self.cate_values = df[cat_features].values self.labels = labels def __len__(self): return len(self.cont_values) def __getitem__(self, idx): cont_x = torch.FloatTensor(self.cont_values[idx...
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
14,311,680
cat_features = ['cp_time', 'cp_dose'] num_features = [c for c in train.columns if train.dtypes[c] != 'object'] num_features = [c for c in num_features if c not in cat_features] num_features = [c for c in num_features if c not in target_cols] target = train[target_cols].values def cate2num(df): df['cp_time'] = df['cp_ti...
missing_values = pd.DataFrame({c:[(train_df[c].isna().sum() /len(train_df)) *100,\ (test_df[c].isna().sum() /len(test_df)) *100] for c in \ ["keyword","location"]},index=["train","test"]) missing_values
Natural Language Processing with Disaster Tweets
14,311,680
class CFG: max_grad_norm=1000 gradient_accumulation_steps=1 hidden_size=512 dropout=0.4 lr=1e-3 weight_decay=1e-5 batch_size=128 epochs=50 num_features=num_features cat_features=cat_features target_cols=target_cols<choose_model_class>
train_df["keyword"].fillna("no_keywords",inplace = True) test_df["keyword"].fillna("no_keywords",inplace = True) train_df["location"].fillna("no_location",inplace=True) test_df["location"].fillna("no_location",inplace=True )
Natural Language Processing with Disaster Tweets
14,311,680
class TabularNN(nn.Module): def __init__(self, cfg): super().__init__() self.mlp = nn.Sequential( nn.Linear(len(cfg.num_features), cfg.hidden_size), nn.BatchNorm1d(cfg.hidden_size), nn.Dropout(cfg.dropout), nn.PReLU(cfg.hidden_size), nn.Linear(cfg.hidden_size, cfg.hidden_size), nn.BatchNorm1d(cfg.hidden_size), nn.Drop...
train_df["word_count"] = train_df["text"].map(lambda x: len(str(x ).split())) test_df["word_count"] = test_df["text"].map(lambda x: len(str(x ).split())) train_df["unique_word_count"] = train_df["text"].map(lambda x:len(set(str(x ).split()))) test_df["unique_word_count"] = test_df["text"].map(lambda x:len(set(str(x )....
Natural Language Processing with Disaster Tweets
14,311,680
def train_fn(train_loader, model, optimizer, epoch, scheduler, device): losses = AverageMeter() model.train() for step,(cont_x, cate_x, y)in enumerate(train_loader): cont_x, cate_x, y = cont_x.to(device), cate_x.to(device), y.to(device) batch_size = cont_x.size(0) pred = model(cont_x, cate_x) loss = nn.BCEWithLogits...
def gen_n_grams(text,n_grams=1): tokens = [token for token in str(text ).lower().split() if token not in stopwords.words("english")] ngrams = zip(*[tokens[i:] for i in range(n_grams)]) return [" ".join(gram)for gram in ngrams] def gen_df_ngrams(n_grams=1): mask = train_df["target"]==1 disaster_unigrams = defaultdi...
Natural Language Processing with Disaster Tweets
14,311,680
def run_single_nn(cfg, train, test, folds, num_features, cat_features, target, device, fold_num=0, seed=42): logger.info(f'Set seed {seed}') seed_everything(seed=seed) trn_idx = folds[folds['fold'] != fold_num].index val_idx = folds[folds['fold'] == fold_num].index train_folds = train.loc[trn_idx].reset_index(drop=Tr...
%%time glove_embeddings = np.load('.. /input/pickled-glove840b300d-for-10sec-loading/glove.840B.300d.pkl', allow_pickle=True) fasttext_embeddings = np.load('.. /input/pickled-crawl300d2m-for-kernel-competitions/crawl-300d-2M.pkl', allow_pickle=True )
Natural Language Processing with Disaster Tweets
14,311,680
oof = np.zeros(( len(train), len(CFG.target_cols))) predictions = np.zeros(( len(test), len(CFG.target_cols))) SEED = [0, 1, 2] for seed in SEED: _oof, _predictions = run_kfold_nn(CFG, train, test, folds, num_features, cat_features, target, device, n_fold=5, seed=seed) oof += _oof / len(SEED) predictions += _predic...
def build_vocab(X): tweets = X.apply(lambda x : x.split() ).values vocab = {} for tweet in tweets: for word in tweet: try: vocab[word] +=1 except KeyError: vocab[word] = 1 return vocab
Natural Language Processing with Disaster Tweets
14,311,680
train[target_cols] = oof train[['sig_id']+target_cols].to_csv('oof.csv', index=False) test[target_cols] = predictions test[['sig_id']+target_cols].to_csv('pred.csv', index=False )<compute_test_metric>
def check_embedding_coverage(X,embedding): vocab = build_vocab(X) covered = {} oov ={} n_covered = 0 n_oov = 0 for word in vocab : try: covered[word] = embedding[word] n_covered += vocab[word] except: oov[word] = vocab[word] n_oov += vocab[word] coverage = len(covered)/ len(vocab) text_coverage = n_covered /(n_cove...
Natural Language Processing with Disaster Tweets
14,311,680
result = train_targets_scored.drop(columns=target_cols)\ .merge(train[['sig_id']+target_cols], on='sig_id', how='left' ).fillna(0) y_true = train_targets_scored[target_cols].values y_pred = result[target_cols].values score = 0 for i in range(y_true.shape[1]): _score = log_loss(y_true[:,i], y_pred[:,i]) score += _sco...
train_glove_oov,train_glove_coverage,train_glove_text = check_embedding_coverage(train_df["text"],glove_embeddings) test_glove_oov,test_glove_coverage,test_glove_text = check_embedding_coverage(test_df["text"],glove_embeddings) print("Glove embedding cover {} of vocabulary and {} of text in the training dataset".form...
Natural Language Processing with Disaster Tweets
14,311,680
sub = submission.drop(columns=target_cols ).merge(test[['sig_id']+target_cols], on='sig_id', how='left' ).fillna(0) sub.to_csv('submission.csv', index=False) sub.head()<import_modules>
train_fastext_oov,train_fastext_coverage,train_fastext_text = check_embedding_coverage(train_df["text"],fasttext_embeddings) test_fastext_oov,test_fastext_coverage,test_fastext_text = check_embedding_coverage(test_df["text"],fasttext_embeddings) print("FastText embedding cover {} of vocabulary and {} of text in the t...
Natural Language Processing with Disaster Tweets
14,311,680
import numpy as np import pandas as pd import tensorflow as tf import tensorflow.keras.backend as K import tensorflow.keras.layers as L import tensorflow.keras.models as M from tensorflow.keras.callbacks import ReduceLROnPlateau import tensorflow_addons as tfa from sklearn.model_selection import KFold from sklearn.metr...
def clean(tweet): tweet = re.sub(r"\x89Û_", "", tweet) tweet = re.sub(r"\x89ÛÒ", "", tweet) tweet = re.sub(r"\x89ÛÓ", "", tweet) tweet = re.sub(r"\x89ÛÏWhen", "When", tweet) tweet = re.sub(r"\x89ÛÏ", "", tweet) tweet = re.sub(r"China\x89Ûªs", "China's", tweet) tweet = re.sub(r"let\x89Ûªs", "let's", tweet) tweet ...
Natural Language Processing with Disaster Tweets
14,311,680
train_features = pd.read_csv('.. /input/lish-moa/train_features.csv') train_targets = pd.read_csv('.. /input/lish-moa/train_targets_scored.csv') test_features = pd.read_csv('.. /input/lish-moa/test_features.csv') ss = pd.read_csv('.. /input/lish-moa/sample_submission.csv' )<categorify>
train_df["text_cleaned"] = train_df["text"].apply(lambda s:clean(s)) test_df["text_cleaned"] = test_df["text"].apply(lambda s:clean(s))
Natural Language Processing with Disaster Tweets
14,311,680
def preprocess(df): df.loc[:, 'cp_type'] = df.loc[:, 'cp_type'].map({'trt_cp': 0, 'ctl_vehicle': 1}) df.loc[:, 'cp_dose'] = df.loc[:, 'cp_dose'].map({'D1': 0, 'D2': 1}) del df['sig_id'] return df train = preprocess(train_features) test = preprocess(test_features) del train_targets['sig_id']<choose_model_class>
train_glove_oov,train_glove_coverage,train_glove_text = check_embedding_coverage(train_df["text_cleaned"],glove_embeddings) test_glove_oov,test_glove_coverage,test_glove_text = check_embedding_coverage(test_df["text_cleaned"],glove_embeddings) print("Glove embedding cover {} of vocabulary and {} of text in the traini...
Natural Language Processing with Disaster Tweets
14,311,680
def create_model(num_columns): model = tf.keras.Sequential([ tf.keras.layers.Input(num_columns), tf.keras.layers.BatchNormalization() , tfa.layers.WeightNormalization(tf.keras.layers.Dense(6144, activation="relu")) , tf.keras.layers.BatchNormalization() , tf.keras.layers.Dropout(0.4), tfa.layers.WeightNormalization(tf....
train_fastext_oov,train_fastext_coverage,train_fastext_text = check_embedding_coverage(train_df["text_cleaned"],fasttext_embeddings) test_fastext_oov,test_fastext_coverage,test_fastext_text = check_embedding_coverage(test_df["text_cleaned"],fasttext_embeddings) print("FastText embedding cover {} of vocabulary and {} ...
Natural Language Processing with Disaster Tweets
14,311,680
top_feats = [ 0, 1, 2, 3, 5, 6, 8, 9, 10, 11, 12, 14, 15, 16, 18, 19, 20, 21, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 44, 45, 46, 48, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 63, 64, 65, 66, 68, 69, 70, 71, 72, 73, 74, 75, 76, 78, 79, 80, 81, 82, 83, 84, 86, 87, 88, 89, 90, 92, 93...
del(train_fastext_oov) del(test_fastext_oov) del(train_glove_oov) del(test_glove_oov) del(glove_embeddings) del(fasttext_embeddings )
Natural Language Processing with Disaster Tweets
14,311,680
N_STARTS = 3 res = train_targets.copy() ss.loc[:, train_targets.columns] = 0 res.loc[:, train_targets.columns] = 0 for seed in range(N_STARTS): for n,(tr, te)in enumerate(KFold(n_splits=5, random_state=seed, shuffle=True ).split(train_targets)) : print(f'Fold {n+1}') model = create_model(len(top_feats)) reduce_lr_loss...
missalabeled_text = train_df.groupby("text" ).nunique().sort_values(by="target",ascending =False) df =missalabeled_text[missalabeled_text["target"] > 1] df.index.tolist()
Natural Language Processing with Disaster Tweets
14,311,680
metrics = [] for _target in train_targets.columns: metrics.append(log_loss(train_targets.loc[:, _target], res.loc[:, _target])) print(f'OOF Metric: {np.mean(metrics)}' )<compute_train_metric>
train_df["rebuild_target"] = train_df["target"].copy() train_df.loc[train_df["text"]=="like for the music video I want some real action shit like burning buildings and police chases not some weak ben winston shit","rebuild_target"]=0 train_df.loc[train_df["text"]=="Hellfire! We don\x89Ûªt even want to think about it or...
Natural Language Processing with Disaster Tweets
14,311,680
metrics = [] res.loc[train['cp_type']==1, train_targets.columns] = 0 for _target in train_targets.columns: metrics.append(log_loss(train_targets.loc[:, _target], res.loc[:, _target])) print(f'OOF Metric with postprocessing: {np.mean(metrics)}' )<feature_engineering>
k=2 SEED= 1337 sk = StratifiedKFold(n_splits=k,random_state=SEED,shuffle=True) Disaster = train_df["target"] == 1 print("Whole Training Set Shape = {}".format(train_df.shape)) print("Whole Training Set Unique keyword Count = {}".format(train_df["keyword"].nunique())) print("Whole training Set Target Rate(Disaster){}/{...
Natural Language Processing with Disaster Tweets
14,311,680
ss.loc[test['cp_type']==1, train_targets.columns] = 0<save_to_csv>
class ClassificationReport(Callback): def __init__(self,train_data=() ,val_data=()): super(Callback,self ).__init__() self.X_train,self.y_train = train_data self.train_precision_scores = [] self.train_recall_scores = [] self.train_f1_scores = [] self.X_val,self.y_val = val_data self.val_precision_scores = [] self.val_r...
Natural Language Processing with Disaster Tweets
14,311,680
ss.to_csv('submission.csv', index=False )<install_modules>
class BertDisasterDetecter: def __init__(self,max_seq_length=128,epoch=100,batch_size=128,lr=1e-3): self.bert=hub.KerasLayer("https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/1", trainable=True) self.epoch = epoch self.lr = lr self.max_seq_length = max_seq_length self.batch_size = batch_size vocab_file = s...
Natural Language Processing with Disaster Tweets
14,311,680
!pip install --no-deps '.. /input/timm-package/timm-0.1.26-py3-none-any.whl' > /dev/null !pip install --no-deps '.. /input/pycocotools/pycocotools-2.0-cp37-cp37m-linux_x86_64.whl' > /dev/null<define_variables>
clf = BertDisasterDetecter(max_seq_length=128,lr=1e-3,epoch=2,batch_size=32) clf.train()
Natural Language Processing with Disaster Tweets
14,311,680
img_size = 1024<concatenate>
ypred= clf.predict(test_df["text_cleaned"].values )
Natural Language Processing with Disaster Tweets
14,311,680
def get_valid_transforms() : return A.Compose([ A.Resize(height=img_size, width=img_size, p=1.0), ToTensorV2(p=1.0), ], p=1.0 )<data_type_conversions>
model_submission = pd.read_csv("/kaggle/input/nlp-getting-started/sample_submission.csv") model_submission['target'] = np.round(ypred ).astype('int') model_submission.to_csv('model_submission.csv', index=False) model_submission.describe()
Natural Language Processing with Disaster Tweets
14,407,462
DATA_ROOT_PATH = '.. /input/global-wheat-detection/test' class DatasetRetriever(Dataset): def __init__(self, image_ids, transforms=None): super().__init__() self.image_ids = image_ids self.transforms = transforms def __getitem__(self, index: int): image_id = self.image_ids[index] image = cv2.imread(f'{DATA_ROOT_PATH}/{...
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
14,407,462
dataset = DatasetRetriever( image_ids=np.array([path.split('/')[-1][:-4] for path in glob(f'{DATA_ROOT_PATH}/*.jpg')]), transforms=get_valid_transforms() ) def collate_fn(batch): return tuple(zip(*batch)) data_loader = DataLoader( dataset, batch_size=2, shuffle=False, num_workers=4, drop_last=False, collate_fn=coll...
!pip install -U tensorflow_text==2.3
Natural Language Processing with Disaster Tweets
14,407,462
def load_net(checkpoint_path): config = get_efficientdet_config('tf_efficientdet_d4') net = EfficientDet(config, pretrained_backbone=False) config.num_classes = 1 config.image_size=img_size net.class_net = HeadNet(config, num_outputs=config.num_classes, norm_kwargs=dict(eps=.001, momentum=.01)) checkpoint = torch.loa...
!pip install -q tf-models-official==2.3
Natural Language Processing with Disaster Tweets
14,407,462
def make_predictions(images, score_threshold=0.2): images = torch.stack(images ).cuda().float() predictions = [] with torch.no_grad() : det = net(images, torch.tensor([1]*images.shape[0] ).float().cuda()) for i in range(images.shape[0]): boxes = det[i].detach().cpu().numpy() [:,:4] scores = det[i].detach().cpu().numpy...
import tensorflow as tf import tensorflow_hub as hub import tensorflow_text as text from official.nlp import optimization
Natural Language Processing with Disaster Tweets
14,407,462
def format_prediction_string(boxes, scores): pred_strings = [] for j in zip(scores, boxes): pred_strings.append("{0:.4f} {1} {2} {3} {4}".format(j[0], j[1][0], j[1][1], j[1][2], j[1][3])) return " ".join(pred_strings )<predict_on_test>
batch_size = 32 seed = 42 train_ds = tf.data.Dataset.from_tensor_slices(( train_df['text'].tolist() ,train_df['target'].tolist())).batch(batch_size )
Natural Language Processing with Disaster Tweets
14,407,462
results = [] for images, image_ids in data_loader: predictions = make_predictions(images) for i, image in enumerate(images): boxes, scores, labels = run_wbf(predictions, image_index=i) boxes = boxes.astype(np.int32 ).clip(min=0, max=1023) image_id = image_ids[i] boxes[:, 2] = boxes[:, 2] - boxes[:, 0] boxes[:, 3] = ...
bert_model_name = 'bert_en_uncased_L-12_H-768_A-12' map_name_to_handle = { 'bert_en_uncased_L-12_H-768_A-12': 'https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/3', 'bert_en_cased_L-12_H-768_A-12': 'https://tfhub.dev/tensorflow/bert_en_cased_L-12_H-768_A-12/3', 'bert_multi_cased_L-12_H-768_A-12': 'https://tf...
Natural Language Processing with Disaster Tweets
14,407,462
test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.to_csv('submission.csv', index=False) test_df.head()<define_variables>
def build_classifier_model() : text_input = tf.keras.layers.Input(shape=() , dtype=tf.string, name='text') preprocessing_layer = hub.KerasLayer(tfhub_handle_preprocess, name='preprocessing') encoder_inputs = preprocessing_layer(text_input) encoder = hub.KerasLayer(tfhub_handle_encoder, trainable=True, name='BERT_enc...
Natural Language Processing with Disaster Tweets
14,407,462
half = False<train_model>
loss = tf.keras.losses.BinaryCrossentropy(from_logits=True) metrics = tf.metrics.BinaryAccuracy()
Natural Language Processing with Disaster Tweets
14,407,462
device = torch.device('cuda:0') model = torch.load('/kaggle/input/wheat-submit/best_wheat1024.pt', map_location=device)['model'].to(device ).float().eval() if half: model.half()<define_variables>
epochs = 20 steps_per_epoch = tf.data.experimental.cardinality(train_ds ).numpy() num_train_steps = steps_per_epoch * epochs num_warmup_steps = int(0.1*num_train_steps) init_lr = 3e-5 optimizer = optimization.create_optimizer(init_lr=init_lr, num_train_steps=num_train_steps, num_warmup_steps=num_warmup_steps, optimize...
Natural Language Processing with Disaster Tweets
14,407,462
img_paths = glob.glob('/kaggle/input/global-wheat-detection/test/*.jpg') print(img_paths )<categorify>
classifier_model.compile(optimizer=optimizer, loss=loss, metrics=metrics )
Natural Language Processing with Disaster Tweets
14,407,462
def inference_detector(model, img_path): dataset = LoadImages(img_path, img_size=1024) path, img, im0, vid_cap = next(iter(dataset)) img = torch.from_numpy(img ).to(device) img = img.half() if half else img.float() img /= 255.0 if img.ndimension() == 3: img = img.unsqueeze(0) pred = model(img, augment=True)[0] pred ...
print(f'Training model with {tfhub_handle_encoder}') history = classifier_model.fit(x=train_ds, epochs=epochs )
Natural Language Processing with Disaster Tweets
14,407,462
img_paths = glob.glob('/kaggle/input/global-wheat-detection/test/*.jpg') results = [] for img_path in tqdm(img_paths): det = inference_detector_wbf(model, img_path) pred_strings = [] for bbox in det: pred_strings.append("{0:.4f} {1} {2} {3} {4}".format(bbox[4], bbox[0], bbox[1], bbox[2]-bbox[0], bbox[3]-bbox[1])) pre...
probs = classifier_model.predict(test_df["text"]) threshold = 0.4 preds = np.where(probs[:,] > threshold, 1, 0 )
Natural Language Processing with Disaster Tweets
14,407,462
test_df.to_csv('submission.csv', index=False )<install_modules>
submission=pd.read_csv('/kaggle/input/nlp-getting-started/sample_submission.csv' )
Natural Language Processing with Disaster Tweets
14,407,462
!pip install.. /input/mmcvwhl/addict-2.2.1-py3-none-any.whl !pip install.. /input/mmdetection20-5-13/mmcv-0.5.1-cp37-cp37m-linux_x86_64.whl !pip install.. /input/mmdetection20-5-13/terminal-0.4.0-py3-none-any.whl !pip install.. /input/mmdetection20-5-13/terminaltables-3.1.0-py3-none-any.whl<import_modules>
submission["target"]=preds
Natural Language Processing with Disaster Tweets
14,407,462
<install_modules><EOS>
submission.to_csv('submission.csv', index=False, header=True )
Natural Language Processing with Disaster Tweets
8,543,886
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<install_modules>
pd.options.mode.chained_assignment = None pd.set_option('display.max_colwidth', -1) pd.set_option('display.max_rows', 1000 )
Natural Language Processing with Disaster Tweets
8,543,886
!python setup.py install<import_modules>
train_origin_df = pd.read_csv('/kaggle/input/nlp-getting-started/train.csv') test_origin_df = pd.read_csv('/kaggle/input/nlp-getting-started/test.csv') train_df = train_origin_df.copy() test_df = test_origin_df.copy() def callback(operation_future): result = operation_future.result()
Natural Language Processing with Disaster Tweets
8,543,886
import pycocotools<install_modules>
dataset_origin_df = pd.concat([train_df, test_df], axis=0, sort=True) dataset_origin_df.reset_index(inplace=True, drop=True )
Natural Language Processing with Disaster Tweets
8,543,886
!pip install -v -e .<define_variables>
words_containing_alpha_df = pd.DataFrame(columns = ['word', 'real', 'fake']) for row in tqdm(dataset_origin_df.iterrows()): row = row[1] result = re.findall('@+\w*', row['text']) if(len(result)> 0): for word in result: real = 1 if row['target'] == 1 else 0 fake = 1 if row['target'] != 1 else 0 temp_df = pd.DataFrame(...
Natural Language Processing with Disaster Tweets
8,543,886
config_txt = config_file = open("/kaggle/working/mmdetection/config.py", "w") n = config_file.write(config_txt) config_file.close()<define_variables>
words_containing_alpha_df = words_containing_alpha_df.groupby(['word'], as_index=False)['real', 'fake'].sum() words_containing_alpha_df['total'] = words_containing_alpha_df['real'] + words_containing_alpha_df['fake'] words_containing_alpha_df = words_containing_alpha_df.sort_values(by = 'total', ascending = False) wor...
Natural Language Processing with Disaster Tweets
8,543,886
def format_prediction_string(boxes, scores): pred_strings = [] for j in zip(scores, boxes): pred_strings.append("{0:.4f} {1} {2} {3} {4}".format(j[0], j[1][0], j[1][1], j[1][2], j[1][3])) return " ".join(pred_strings) <load_from_csv>
threshold_no_of_words = 5 threshold_ratio_of_real_or_fake = 0.75 sub_words_df = words_containing_alpha_df.loc[(words_containing_alpha_df['total'] >= threshold_no_of_words)&(words_containing_alpha_df[['real', 'fake']].max(axis=1)/words_containing_alpha_df['total'] >= threshold_ratio_of_real_or_fake), :] sub_words_df
Natural Language Processing with Disaster Tweets
8,543,886
checkpoint_path = '.. /input/resnest3fcos1iouatseven/epoch_40.pth' config_path = '/kaggle/working/mmdetection/config.py' model = init_detector(config_path, checkpoint_path, device='cuda:0') val_df = pd.read_csv('.. /input/global-wheat-detection/sample_submission.csv') all_image_ids = set(val_df['image_id'].unique()) ...
sub_words_df.drop(0, axis=0, inplace=True )
Natural Language Processing with Disaster Tweets
8,543,886
NMS_IOU_THR = 0.6 NMS_CONF_THR = 0.25 best_iou_thr = 0.6 best_skip_box_thr = 0.43 best_final_score = 0 best_score_threshold = 0 SEED = 42 EPO = 15 WEIGHTS = '.. /input/yolov5test/yolo5x_panet_1.pt' CONFIG = '.. /input/configtest/yolo5_PANET.yaml' DATA = '.. /input/configyolo5/wheat0.yaml' is_TEST = len(os.listdir('.. /...
def remove_words_containing_alpha_by_threshold(text): containing_words = re.findall('@+\w*', text) if(len(containing_words)> 0): for word in containing_words: if(word not in np.array(sub_words_df['word'])) : text = text.replace(word, " ID") return text
Natural Language Processing with Disaster Tweets
8,543,886
def set_seed(seed): random.seed(seed) np.random.seed(seed) os.environ["PYTHONHASHSEED"] = str(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = True set_seed(SEED) marking = pd.read_csv('.. /input/global-wheat-detection/train.csv'...
def clean_1_2_1(tweet): tweet = re.sub(r"%20", " ", tweet) tweet = re.sub(r" ", " ", tweet) tweet = re.sub(r"\x89Û_", "", tweet) tweet = re.sub(r"\x89ÛÒ", "", tweet) tweet = re.sub(r"\x89ÛÓ", "", tweet) tweet = re.sub(r"\x89ÛÏWhen", "When", tweet) tweet = re.sub(r"\x89ÛÏ", "", tweet) tweet = re.sub(r"China\x89Ûª...
Natural Language Processing with Disaster Tweets
8,543,886
def makePseudolabel() : source = '.. /input/global-wheat-detection/test/' weights = WEIGHTS imagenames = os.listdir(source) device = torch.device('cuda')if torch.cuda.is_available() else torch.device('cpu') model = torch.load(weights, map_location=device)['model'].float() model.to(device ).eval() dataset = LoadImages...
def remove_url(text): url_pattern = re.compile(r'https?://\S*|www\.\S*') return url_pattern.sub(r'URL', text) def remove_url_for_labelling(text): url_pattern = re.compile(r'https?://\S*|www\.\S*') return url_pattern.sub(r'', text )
Natural Language Processing with Disaster Tweets
8,543,886
if PSEUDO or VALIDATE: convertTrainLabel()<find_best_params>
EMOTICONS = { u":‑\)":"Happy face smiley", u":\)":"Happy face smiley", u":-\]":"Happy face smiley", u":\]":"Happy face smiley", u":-3":"Happy face smiley", u":->":"Happy face smiley", u":>":"Happy face smiley", u"8-\)":"Happy face smiley", u":o\)":"Happy face smiley", u":-\}":"Happy face smiley", u":\}":"Happy face smi...
Natural Language Processing with Disaster Tweets
8,543,886
if VALIDATE and is_TEST: all_predictions = validate() for score_threshold in tqdm(np.arange(0, 1, 0.01), total=np.arange(0, 1, 0.01 ).shape[0]): final_score = calculate_final_score(all_predictions, best_iou_thr, best_skip_box_thr, score_threshold) if final_score > best_final_score: best_final_score = final_score bes...
EMOTICONS_fix = { u":‑\)":"happy", u":\)":"happy", u":-\]":"happy", u":\]":"happy", u":-3":"happy", u":->":"happy", u":>":"happy", u"8-\)":"happy", u":o\)":"happy", u":-\}":"happy", u":\}":"happy", u":-\)":"happy", u":c\)":"happy", u":\^\)":"happy", u"=\]":"happy", u"=\)":"happy", u":‑D":"happy", u"8‑D":"happy", u"X‑D"...
Natural Language Processing with Disaster Tweets
8,543,886
def format_prediction_string(boxes, scores): pred_strings = [] for j in zip(scores, boxes): pred_strings.append("{0:.4f} {1} {2} {3} {4}".format(j[0], j[1][0], j[1][1], j[1][2], j[1][3])) return " ".join(pred_strings) def detect() : source = '.. /input/global-wheat-detection/test/' weights = 'weights/best.pt' if not o...
def convert_emoticons(text): for emot in EMOTICONS_fix.items() : if emot[0] in text: text = text.replace(emot[0],".I feel "+emot[1]+".") return text
Natural Language Processing with Disaster Tweets
8,543,886
results = detect() test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.to_csv('submission.csv', index=False) test_df.head()<define_variables>
def remove_emoji(text): emoji_pattern = re.compile("[" u"\U0001F600-\U0001F64F" u"\U0001F300-\U0001F5FF" u"\U0001F680-\U0001F6FF" u"\U0001F1E0-\U0001F1FF" u"\U00002702-\U000027B0" u"\U000024C2-\U0001F251" "]+", flags=re.UNICODE) return emoji_pattern.sub(r' ', text) remove_emoji("Omg another Earthquake 😔😔" )
Natural Language Processing with Disaster Tweets
8,543,886
NMS_IOU_THR = 0.6 NMS_CONF_THR = 0.5 best_iou_thr = 0.6 best_skip_box_thr = 0.43 best_final_score = 0 best_score_threshold = 0 EPO = 15 WEIGHTS = '.. /input/best-yolov5x-fold0pt/best_yolov5x_fold0.pt' CONFIG = '.. /input/best-yolov5x-fold0pt/yolov5x.yaml' DATA = '.. /input/best-yolov5x-fold0pt/wheat0.yaml' is_TEST = le...
Abbreviation = { '?':"I have a question", '?4U':"I have a question for you", ';S':"Hmm? What did you say?", '^^':"read line", '<3':"sideways heart", '<3':"broken heart", '<33':"heart or love", '@TEOTD':"At the end of the day", '0.02':"My(or your)two cents worth", "'1TG, 2TG'":" number of items needed for win ", '1UP':"...
Natural Language Processing with Disaster Tweets
8,543,886
def convertTrainLabel() : df = pd.read_csv('.. /input/global-wheat-detection/train.csv') bboxs = np.stack(df['bbox'].apply(lambda x: np.fromstring(x[1:-1], sep=','))) for i, column in enumerate(['x', 'y', 'w', 'h']): df[column] = bboxs[:,i] df.drop(columns=['bbox'], inplace=True) df['x_center'] = df['x'] + df['w']/2...
def convert_Abbreviation(text): for abb in Abbreviation.items() : if(not abb[0].isdigit())and(" "+abb[0]+" " in text)and(len(abb[0])>3): text = text.replace(abb[0],abb[1]) return text
Natural Language Processing with Disaster Tweets
8,543,886
def run_wbf(boxes, scores, image_size=1024, iou_thr=0.5, skip_box_thr=0.7, weights=None): labels = [np.zeros(score.shape[0])for score in scores] boxes = [box/(image_size)for box in boxes] boxes, scores, labels = weighted_boxes_fusion(boxes, scores, labels, weights=None, iou_thr=iou_thr, skip_box_thr=skip_box_thr) boxe...
bracket_pattern = re.compile('\[|\]') time_pattern = re.compile('\d+(( \\|\/)\d+)+') number_pattern = re.compile('\d+(,|\.|\d+)*') including_number_pattern = re.compile('\s\d+(\W*\d)*\s') hashtag_pattern = re.compile(' alpha_pattern = re.compile('@') remove_except_chracter_pattern = re.compile('[ ](?=[ ])|[^A-Za-z...
Natural Language Processing with Disaster Tweets
8,543,886
@jit(nopython=True) def calculate_iou(gt, pr, form='pascal_voc')-> float: if form == 'coco': gt = gt.copy() pr = pr.copy() gt[2] = gt[0] + gt[2] gt[3] = gt[1] + gt[3] pr[2] = pr[0] + pr[2] pr[3] = pr[1] + pr[3] dx = min(gt[2], pr[2])- max(gt[0], pr[0])+ 1 if dx < 0: return 0.0 dy = min(gt[3], pr[3])- max(gt[1], pr[1...
def remove_reg(text, reg): if reg == time_pattern: return reg.sub(r' TIME ', text) elif reg == number_pattern: return reg.sub(r'00', text) else: return reg.sub(r' ', text )
Natural Language Processing with Disaster Tweets
8,543,886
def log(text): print(text) def optimize(space, all_predictions, n_calls=10): @use_named_args(space) def score(**params): log('-'*10) log(params) final_score = calculate_final_score(all_predictions, **params) log(f'final_score = {final_score}') log('-'*10) return -final_score return gp_minimize(func=score, dimens...
remove_reg("sd1:2f",time_pattern )
Natural Language Processing with Disaster Tweets
8,543,886
def makePseudolabel() : source = '.. /input/global-wheat-detection/test/' weights = WEIGHTS imagenames = os.listdir(source) device = torch.device('cuda')if torch.cuda.is_available() else torch.device('cpu') model = torch.load(weights, map_location=device)['model'].float() model.to(device ).eval() dataset = LoadImages...
repeated_pattern = re.compile(r'(\!|\? )(( \!|\?){1,})') unnecessary_pattern = re.compile(r"'|"") def remove_punctuation(text): text = unnecessary_pattern.sub(r' ', text) return repeated_pattern.sub(r'\1', text )
Natural Language Processing with Disaster Tweets
8,543,886
if PSEUDO or VALIDATE: convertTrainLabel()<find_best_params>
remove_punctuation("1!! !!! ???? ?
Natural Language Processing with Disaster Tweets
8,543,886
if VALIDATE and is_TEST: all_predictions = validate() for score_threshold in tqdm(np.arange(0, 1, 0.01), total=np.arange(0, 1, 0.01 ).shape[0]): final_score = calculate_final_score(all_predictions, best_iou_thr, best_skip_box_thr, score_threshold) if final_score > best_final_score: best_final_score = final_score bes...
redundant_white_spaces_pattern = re.compile(r'\s+') redundant_url = re.compile(r'url(\s*url)+') redundant_id = re.compile(r'id(\s*id)+') def remove_redundant_white_spaces(text): text = redundant_url.sub(r'\1', text) text = redundant_id.sub(r'\1', text) text = text.strip() text = redundant_white_spaces_pattern.sub(...
Natural Language Processing with Disaster Tweets
8,543,886
def format_prediction_string(boxes, scores): pred_strings = [] for j in zip(scores, boxes): pred_strings.append("{0:.4f} {1} {2} {3} {4}".format(j[0], j[1][0], j[1][1], j[1][2], j[1][3])) return " ".join(pred_strings) def detect() : source = '.. /input/global-wheat-detection/test/' weights = 'weights/best.pt' if not o...
reg_list = [bracket_pattern, number_pattern, time_pattern, including_number_pattern, hashtag_pattern, alpha_pattern, remove_except_chracter_pattern] def preprocessor(dataset, function_list, columns): for column in columns: cleaned_colname = column+"_cleaned" dataset[cleaned_colname] = dataset[column] for i, function in...
Natural Language Processing with Disaster Tweets
8,543,886
results = detect() test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.to_csv('submission.csv', index=False) test_df.head()<define_variables>
function_list = [ remove_words_containing_alpha_by_threshold, clean_1_2_1,clean_1_2_2,clean_1_2_3,clean_1_2_4, clean_1_2_6,clean_1_2_7,clean_1_2_8, remove_url, convert_emoticons, mylower, bracket_pattern, time_pattern, including_number_pattern, hashtag_pattern, alpha_pattern, remove_punctuation, remove_redundant_white_...
Natural Language Processing with Disaster Tweets
8,543,886
sys.path.insert(0, ".. /input/weightedboxesfusion") sys.path.append(".. /input/yolov5train") NMS_IOU_THR = 0.6 NMS_CONF_THR = 0.5 best_iou_thr = 0.6 best_skip_box_thr = 0.43 best_final_score = 0 best_score_threshold = 0 EPO = 15 WEIGHTS = '.. /input/yolov5weight/last0712.pt' CONFIG = '.. /input/wheatyolov5/yolov5x.ya...
def compare_2col(df, target_colname, base_colname): result_colname = target_colname+"_from_"+base_colname df[result_colname] = df.apply(lambda row : row[base_colname] != row[target_colname], axis=1) total = df.shape[0] changed = len(df[df[result_colname]==True]) print(f'{base_colname}에서 {target_colname}가 되면서 전체 {tota...
Natural Language Processing with Disaster Tweets
8,543,886
def makePseudolabel() : source = '.. /input/global-wheat-detection/test/' weights = WEIGHTS imagenames = os.listdir(source) device = torch.device('cuda')if torch.cuda.is_available() else torch.device('cpu') model = torch.load(weights, map_location=device)['model'].float() model.to(device ).eval() dataset = LoadImages...
df_temp = dataset_origin_df.copy() func_num = 14 preprocessor(df_temp, function_list[:func_num], preprocess_target_cols) df_temp['text'] = df_temp['text_cleaned']
Natural Language Processing with Disaster Tweets
8,543,886
def convertTrainLabel() : df = pd.read_csv('.. /input/global-wheat-detection/train.csv') bboxs = np.stack(df['bbox'].apply(lambda x: np.fromstring(x[1:-1], sep=','))) for i, column in enumerate(['x', 'y', 'w', 'h']): df[column] = bboxs[:,i] df.drop(columns=['bbox'], inplace=True) df['x_center'] = df['x'] + df['w']/2...
check_cleaning(df_temp, function_list[func_num],'text_cleaned', 'text',100)
Natural Language Processing with Disaster Tweets
8,543,886
def run_wbf(boxes, scores, image_size=1024, iou_thr=0.5, skip_box_thr=0.7, weights=None): labels = [np.zeros(score.shape[0])for score in scores] boxes = [box/(image_size)for box in boxes] boxes, scores, labels = weighted_boxes_fusion(boxes, scores, labels, weights=None, iou_thr=iou_thr, skip_box_thr=skip_box_thr) boxe...
df_temp[df_temp['text'].str.contains('camilacabello97', na=False, case=False)]
Natural Language Processing with Disaster Tweets
8,543,886
@jit(nopython=True) def calculate_iou(gt, pr, form='pascal_voc')-> float: if form == 'coco': gt = gt.copy() pr = pr.copy() gt[2] = gt[0] + gt[2] gt[3] = gt[1] + gt[3] pr[2] = pr[0] + pr[2] pr[3] = pr[1] + pr[3] dx = min(gt[2], pr[2])- max(gt[0], pr[0])+ 1 if dx < 0: return 0.0 dy = min(gt[3], pr[3])- max(gt[1], pr[1...
preprocessor(train_df, function_list, preprocess_target_cols) preprocessor(test_df, function_list, preprocess_target_cols )
Natural Language Processing with Disaster Tweets
8,543,886
def log(text): print(text) def optimize(space, all_predictions, n_calls=10): @use_named_args(space) def score(**params): log('-'*10) log(params) final_score = calculate_final_score(all_predictions, **params) log(f'final_score = {final_score}') log('-'*10) return -final_score return gp_minimize(func=score, dimens...
def remove_cleaned_col(df): for col in preprocess_target_cols: cleaned_colname = col+"_cleaned" df[col] = df[cleaned_colname] df.drop(columns=[cleaned_colname], axis=1, inplace=True) remove_cleaned_col(train_df) remove_cleaned_col(test_df )
Natural Language Processing with Disaster Tweets
8,543,886
def makePseudolabel() : source = '.. /input/global-wheat-detection/test/' weights = WEIGHTS imagenames = os.listdir(source) device = torch.device('cuda')if torch.cuda.is_available() else torch.device('cpu') model = torch.load(weights, map_location=device)['model'].float() model.to(device ).eval() dataset = LoadImages...
mislabeled_corrected_df = pd.read_csv('/kaggle/input/nlp-wdt-hapjeong/mislabeled_corrected_V19.csv')
Natural Language Processing with Disaster Tweets
8,543,886
if PSEUDO or VALIDATE: convertTrainLabel()<find_best_params>
i=0 for index, row in mislabeled_corrected_df[mislabeled_corrected_df['target'].isin([0.0,1.0])].iterrows() : i=i+1 train_df.loc[train_df['id'] == row['id'], 'target'] = int(row['target']) print(i )
Natural Language Processing with Disaster Tweets
8,543,886
if VALIDATE and is_TEST: all_predictions = validate() for score_threshold in tqdm(np.arange(0, 1, 0.01), total=np.arange(0, 1, 0.01 ).shape[0]): final_score = calculate_final_score(all_predictions, best_iou_thr, best_skip_box_thr, score_threshold) if final_score > best_final_score: best_final_score = final_score bes...
i=0 for index, row in mislabeled_corrected_df[~mislabeled_corrected_df['target'].isin([0.0,1.0])].iterrows() : i=i+1 train_df = train_df[train_df['id'] != row['id']] print(i )
Natural Language Processing with Disaster Tweets
8,543,886
def format_prediction_string(boxes, scores): pred_strings = [] for j in zip(scores, boxes): pred_strings.append("{0:.4f} {1} {2} {3} {4}".format(j[0], j[1][0], j[1][1], j[1][2], j[1][3])) return " ".join(pred_strings) def detect() : source = '.. /input/global-wheat-detection/test/' weights = 'weights/best.pt' if not o...
train_df.to_csv('train_cleaned.csv', index=False) test_df.to_csv('test_cleaned.csv', index=False)
Natural Language Processing with Disaster Tweets
8,543,886
results = detect() test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.to_csv('submission.csv', index=False) test_df.head()<install_modules>
import numpy as np import pandas as pd import time from datetime import datetime
Natural Language Processing with Disaster Tweets
8,543,886
!pip uninstall -y tensorflow !pip install chainer-chemistry==0.5.0<import_modules>
train = pd.read_csv('train_cleaned.csv') test = pd.read_csv('test_cleaned.csv' )
Natural Language Processing with Disaster Tweets
8,543,886
import random import numpy as np import pandas as pd import chainer import chainer_chemistry from IPython.display import display<load_from_csv>
from google.cloud import storage, automl_v1beta1 as automl from google.api_core.gapic_v1.client_info import ClientInfo from automlwrapper import AutoMLWrapper
Natural Language Processing with Disaster Tweets
8,543,886
def load_dataset() : train = pd.merge(pd.read_csv('.. /input/champs-scalar-coupling/train.csv'), pd.read_csv('.. /input/champs-scalar-coupling/scalar_coupling_contributions.csv')) test = pd.read_csv('.. /input/champs-scalar-coupling/test.csv') counts = train['molecule_name'].value_counts() moles = list(counts.index) ...
PROJECT_ID = 'kaggle-nlp-wdt' BUCKET_NAME = 'kaggle-nlp-wdt-lcm' region = 'us-central1' storage_client = storage.Client(project=PROJECT_ID) client = automl.AutoMlClient(client_info=ClientInfo()) print(f'Starting AutoML notebook at {datetime.fromtimestamp(time.time() ).strftime("%Y-%m-%d, %H:%M:%S UTC")}' )
Natural Language Processing with Disaster Tweets
8,543,886
class Graph: def __init__(self, points_df, list_atoms): self.points = points_df[['x', 'y', 'z']].values self._dists = distance.cdist(self.points, self.points) self.adj = self._dists < 1.5 self.num_nodes = len(points_df) self.atoms = points_df['atom'] dict_atoms = {at: i for i, at in enumerate(list_atoms)} atom_index ...
VERSION = 'V19' BUCKET_PATH = 'preprocessing/'+VERSION+'/' FILE_NAME = 'train_cleaned'+'_'+VERSION training_gcs_path = BUCKET_PATH+FILE_NAME+'.csv' dataset_display_name = FILE_NAME model_display_name = 'model_'+FILE_NAME
Natural Language Processing with Disaster Tweets
8,543,886
train_dataset = DictDataset(graphs=train_graphs, targets=train_targets) valid_dataset = DictDataset(graphs=valid_graphs, targets=valid_targets) test_dataset = DictDataset(graphs=test_graphs, targets=test_targets )<feature_engineering>
train.loc[:,['text','target']].to_csv('train.csv', index=False, header=False )
Natural Language Processing with Disaster Tweets
8,543,886
class SchNetUpdateBN(SchNetUpdate): def __init__(self, *args, **kwargs): super(SchNetUpdateBN, self ).__init__(*args, **kwargs) with self.init_scope() : self.bn = GraphBatchNormalization(args[0]) def __call__(self, h, adj, **kwargs): v = self.linear[0](h) v = self.cfconv(v, adj) v = self.linear[1](v) v = F.softplu...
bucket = storage.Bucket(storage_client, name=BUCKET_NAME) if not bucket.exists() : bucket.create(location=BUCKET_REGION )
Natural Language Processing with Disaster Tweets
8,543,886
class SameSizeSampler(OrderSampler): def __init__(self, structures_groups, moles, batch_size, random_state=None, use_remainder=False): self.structures_groups = structures_groups self.moles = moles self.batch_size = batch_size if random_state is None: random_state = np.random.random.__self__ self._random = random_state ...
def upload_blob(bucket_name, source_file_name, destination_blob_name): bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(destination_blob_name) blob.upload_from_filename(source_file_name) print('File {} uploaded to {}'.format( source_file_name, 'gs://' + bucket_name + '/' + destination_blob_name)...
Natural Language Processing with Disaster Tweets
8,543,886
optimizer = optimizers.Adam(alpha=1e-3) optimizer.setup(model )<categorify>
upload_blob(BUCKET_NAME, 'train.csv', training_gcs_path)
Natural Language Processing with Disaster Tweets
8,543,886
def coupling_converter(batch, device): list_array = list() list_dists = list() list_targets = list() list_pairs_index = list() with_target = 'fc' in batch[0]['targets'].columns for i, d in enumerate(batch): list_array.append(d['graphs'].input_array) list_dists.append(d['graphs'].dists) if with_target: list_targets.ap...
amw = AutoMLWrapper(client=client, project_id=PROJECT_ID, bucket_name=BUCKET_NAME, region='us-central1', dataset_display_name=dataset_display_name, model_display_name=model_display_name)
Natural Language Processing with Disaster Tweets
8,543,886
class TypeWiseEvaluator(Evaluator): def __init__(self, iterator, target, converter, device, name, is_validate=False, is_submit=False): super(TypeWiseEvaluator, self ).__init__( iterator, target, converter=converter, device=device) self.is_validate = is_validate self.is_submit = is_submit self.name = name def calc_sco...
print(f'Getting dataset ready at {datetime.fromtimestamp(time.time() ).strftime("%Y-%m-%d, %H:%M:%S UTC")}') if not amw.get_dataset_by_display_name(dataset_display_name): print('dataset not found') amw.create_dataset() amw.import_gcs_data(training_gcs_path) amw.dataset print(f'Dataset ready at {datetime.fromtimestam...
Natural Language Processing with Disaster Tweets
8,543,886
chainer.config.train = True trainer.run()<install_modules>
print(f'Getting model trained at {datetime.fromtimestamp(time.time() ).strftime("%Y-%m-%d, %H:%M:%S UTC")}') if not amw.get_model_by_display_name(model_display_name): print(f'Training model at {datetime.fromtimestamp(time.time() ).strftime("%Y-%m-%d, %H:%M:%S UTC")}') amw.train_model() print(f'Model trained.Ensuring ...
Natural Language Processing with Disaster Tweets
8,543,886
!pip install tensorflow-gpu==2.0a0<import_modules>
amw.model_full_path
Natural Language Processing with Disaster Tweets
8,543,886
print(tf.__version__ )<set_options>
print(f'Begin getting predictions at {datetime.fromtimestamp(time.time() ).strftime("%Y-%m-%d, %H:%M:%S UTC")}') prediction_client = automl.PredictionServiceClient() amw.set_prediction_client(prediction_client) predictions_df = amw.get_predictions(test, input_col_name='text', limit=None, threshold=0.5, verbose=False)...
Natural Language Processing with Disaster Tweets
8,543,886
tf.test.is_gpu_available( cuda_only=False, min_cuda_compute_capability=None ) <define_variables>
submission_df = pd.concat([test['id'], predictions_df['class']], axis=1) submission_df.head()
Natural Language Processing with Disaster Tweets
8,543,886
tf.random.set_seed(42) datadir = ".. /input/"<choose_model_class>
submission_df = submission_df.rename(columns={'class':'target'}) submission_df.head()
Natural Language Processing with Disaster Tweets
8,543,886
<normalization><EOS>
submission_df.to_csv("submission.csv", index=False, header=True )
Natural Language Processing with Disaster Tweets
14,068,986
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<choose_model_class>
nltk.download('stopwords', quiet=True) stopwords = stopwords.words('english') sns.set(style="white", font_scale=1.2) plt.rcParams["figure.figsize"] = [10,8] pd.set_option.display_max_columns = 0 pd.set_option.display_max_rows = 0
Natural Language Processing with Disaster Tweets
14,068,986
class Update_Func_1(tf.keras.layers.Layer): def __init__(self, intermediate_dim, state_dim): super(Update_Func_1, self ).__init__() self.concat_layer = tf.keras.layers.Concatenate() self.hidden_layer_1 = tf.keras.layers.Dense(units=intermediate_dim, activation=tf.nn.relu) self.output_layer = tf.keras.layers.Dense(unit...
train = pd.read_csv(".. /input/nlp-getting-started/train.csv") test = pd.read_csv(".. /input/nlp-getting-started/test.csv" )
Natural Language Processing with Disaster Tweets
14,068,986
class Adj_Updater_1(tf.keras.layers.Layer): def __init__(self, intermediate_dim, state_dim): super(Adj_Updater_1, self ).__init__() self.concat_layer = tf.keras.layers.Concatenate() self.hidden_layer_1 = tf.keras.layers.Dense(units=intermediate_dim, activation=tf.nn.relu) self.output_layer = tf.keras.layers.Dense(unit...
null_counts = pd.DataFrame({"Num_Null": train.isnull().sum() }) null_counts["Pct_Null"] = null_counts["Num_Null"] / train.count() * 100 null_counts
Natural Language Processing with Disaster Tweets
14,068,986
class Edge_Regressor(tf.keras.layers.Layer): def __init__(self, intermediate_dim): super(Edge_Regressor, self ).__init__() self.concat_layer = tf.keras.layers.Concatenate() self.hidden_layer_1 = tf.keras.layers.Dense(units=intermediate_dim, activation=tf.nn.relu) self.hidden_layer_2 = tf.keras.layers.Dense(units=inter...
len(train["keyword"].value_counts() )
Natural Language Processing with Disaster Tweets
14,068,986
class MP_Layer(tf.keras.layers.Layer): def __init__(self, mp_int_dim, up_int_dim, out_int_dim, state_dim): super(MP_Layer, self ).__init__(self) self.state_dim = state_dim self.message_passers_1 = Message_Passer_1(intermediate_dim = mp_int_dim, state_dim = state_dim) self.update_functions_1 = Update_Func_1(intermedia...
def keyword_disaster_probabilities(x): tweets_w_keyword = np.sum(train["keyword"].fillna("" ).str.contains(x)) tweets_w_keyword_disaster = np.sum(train["keyword"].fillna("" ).str.contains(x)& train["target"] == 1) return tweets_w_keyword_disaster / tweets_w_keyword keywords_vc["Disaster_Probability"] = keywords_vc.ind...
Natural Language Processing with Disaster Tweets
14,068,986
class MP_Layer_edge_only(tf.keras.layers.Layer): def __init__(self, mp_int_dim, up_int_dim, out_int_dim, state_dim): super(MP_Layer_edge_only, self ).__init__(self) self.adj_updaters_1 = Adj_Updater_1(intermediate_dim = up_int_dim, state_dim = state_dim) self.adj_updaters_2 = Adj_Updater_1(intermediate_dim = up_int_d...
keywords_vc.sort_values(by="Disaster_Probability", ascending=False ).head(10 )
Natural Language Processing with Disaster Tweets
14,068,986
adj_input = tf.keras.Input(shape=(None,), name='adj_input') nod_input = tf.keras.Input(shape=(None,), name='nod_input') class MPNN(tf.keras.Model): def __init__(self, mp_int_dim, up_int_dim, out_int_dim, state_dim, T): super(MPNN, self ).__init__(self) self.MP = [MP_Layer(mp_int_dim, up_int_dim, out_int_dim, state_d...
len(train["location"].value_counts() )
Natural Language Processing with Disaster Tweets
14,068,986
def log_mae(orig , preds): mask = tf.where(tf.equal(orig, 0), orig, tf.ones_like(orig)) nums = tf.boolean_mask(orig, mask) preds = tf.boolean_mask(preds, mask) reconstruction_error = tf.math.log(tf.reduce_mean(tf.abs(tf.subtract(nums, preds)))) return reconstruction_error def mae(orig , preds): mask = tf.where(tf.equ...
def create_corpus(target): corpus = [] for w in train.loc[train["target"] == target]["text"].str.split() : for i in w: corpus.append(i) return corpus def create_corpus_dict(target): corpus = create_corpus(target) stop_dict = defaultdict(int) for word in corpus: if word in stopwords: stop_dict[word] += 1 return sorte...
Natural Language Processing with Disaster Tweets