kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
18,398,566
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 )<load_from_csv>
train = pd.read_csv('/kaggle/input/nlp-getting-started/train.csv') test = pd.read_csv('/kaggle/input/nlp-getting-started/test.csv') print(train.shape, test.shape) train.sample(10, random_state=26 )
Natural Language Processing with Disaster Tweets
18,398,566
marking = pd.read_csv('.. /input/global-wheat-detection/train.csv') bboxs = np.stack(marking['bbox'].apply(lambda x: np.fromstring(x[1:-1], sep=','))) for i, column in enumerate(['x', 'y', 'w', 'h']): marking[column] = bboxs[:,i] marking.drop(columns=['bbox'], inplace=True )<feature_engineering>
def preprocess(df): df_new = df.copy(deep=True) df_new['text'] = df.apply(lambda row: re.sub('@[A-z0-9]', '', row['text'] ).lower() , axis=1) df_new['text_w_kword'] = df_new.apply(lambda row: 'keyword: ' + str(row['keyword'])+ '.'+ str(row['text']), axis=1) return df_new train_prep = preprocess(train) test_prep = p...
Natural Language Processing with Disaster Tweets
18,398,566
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...
X_train, X_valid, y_train, y_valid = train_test_split(train_prep['text_w_kword'], train_prep['target'], test_size=0.1, random_state=1 )
Natural Language Processing with Disaster Tweets
18,398,566
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...
tokenizer = DistilBertTokenizerFast.from_pretrained('/kaggle/input/huggingface-bert-variants/distilbert-base-uncased/distilbert-base-uncased/') train_encodings = tokenizer(list(X_train), truncation=True, padding='max_length', max_length=100) valid_encodings = tokenizer(list(X_valid), truncation=True, padding='max_len...
Natural Language Processing with Disaster Tweets
18,398,566
@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...
train_dataset = tf.data.Dataset.from_tensor_slices(( dict(train_encodings), y_train.values.astype('float32' ).reshape(( -1,1)) )) valid_dataset = tf.data.Dataset.from_tensor_slices(( dict(valid_encodings), y_valid.values.astype('float32' ).reshape(( -1,1)) )) train_dataset
Natural Language Processing with Disaster Tweets
18,398,566
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...
es = EarlyStopping(monitor='val_loss', verbose=1, patience=4, restore_best_weights=True )
Natural Language Processing with Disaster Tweets
18,398,566
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...
batch_size = 64 num_epochs = 15 num_train_steps =(X_train.shape[0] // batch_size)* num_epochs lr_scheduler = PolynomialDecay( initial_learning_rate=5e-5, end_learning_rate=1e-5, decay_steps=num_train_steps ) new_opt = Adam(learning_rate=lr_scheduler )
Natural Language Processing with Disaster Tweets
18,398,566
if PSEUDO or VALIDATE: convertTrainLabel()<find_best_params>
def f1_score(true, pred): ground_positives = K.sum(true, axis=0)+ K.epsilon() pred_positives = K.sum(pred, axis=0)+ K.epsilon() true_positives = K.sum(true * pred, axis=0)+ K.epsilon() precision = true_positives / pred_positives recall = true_positives / ground_positives f1 = 2 *(precision * recall)/(precision + recall...
Natural Language Processing with Disaster Tweets
18,398,566
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...
model = TFDistilBertForSequenceClassification.from_pretrained('/kaggle/input/huggingface-bert-variants/distilbert-base-uncased/distilbert-base-uncased/', num_labels=2) model.compile( optimizer=new_opt, loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) ) history = model.fit(train_dataset.batch(batc...
Natural Language Processing with Disaster Tweets
18,398,566
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...
test_encodings = tokenizer(list(test_prep['text_w_kword']), truncation=True, padding='max_length', max_length=100) test_dataset = tf.data.Dataset.from_tensor_slices(( dict(test_encodings) ))
Natural Language Processing with Disaster Tweets
18,398,566
results = detect() test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.to_csv('submission.csv', index=False) test_df.head()<import_modules>
test_preds = model.predict(test_dataset.batch(1))
Natural Language Processing with Disaster Tweets
18,398,566
import logging import os import re import gc import json from tqdm.auto import tqdm import numpy as np import pandas as pd import cv2 import matplotlib.pyplot as plt<install_modules>
class_preds = np.argmax(test_preds.logits, axis=1) class_preds
Natural Language Processing with Disaster Tweets
18,398,566
!pip install.. /input/pytorch-16/torch-1.6.0cu101-cp37-cp37m-linux_x86_64.whl<install_modules>
valid_preds = model.predict(valid_dataset.batch(batch_size))
Natural Language Processing with Disaster Tweets
18,398,566
!pip install.. /input/pytorch-16/torchvision-0.7.0cu101-cp37-cp37m-linux_x86_64.whl<install_modules>
valid_class_preds = np.argmax(valid_preds.logits, axis=1 )
Natural Language Processing with Disaster Tweets
18,398,566
!pip install.. /input/pretrainedmodels/pretrainedmodels-0.7.4/pretrainedmodels-0.7.4/ > /dev/null<install_modules>
print(classification_report(y_valid, valid_class_preds))
Natural Language Processing with Disaster Tweets
18,398,566
!pip install.. /input/wheat-pkgs/EfficientNet-PyTorch-master/EfficientNet-PyTorch-master/ > /dev/null<install_modules>
df_submission = pd.DataFrame({'id':test['id'].values, 'target':class_preds}) df_submission
Natural Language Processing with Disaster Tweets
18,398,566
<install_modules><EOS>
df_submission.to_csv('submission.csv', index=False )
Natural Language Processing with Disaster Tweets
20,927,228
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<import_modules>
print(tf.__version__ )
Natural Language Processing with Disaster Tweets
20,927,228
set_seed, create_logging, WheatDataset, FastDataLoader, collate, ModleWithLoss, CtdetLoss, ModelEMA, get_constant_schedule_with_warmup, train_one_epoch, get_train_transforms, freeze_bn )<define_variables>
df = pd.read_csv('.. /input/disaster-tweets-cleaned/df.csv') test_df = pd.read_csv('.. /input/disaster-tweets-cleaned/test_df.csv') print(df.shape, test_df.shape )
Natural Language Processing with Disaster Tweets
20,927,228
bifpn_path_0 = '.. /input/wheat-weights/model_centernet_effnetb5_bifpn_00099.pth' bifpn_path_1 = '.. /input/wheat-weights/model_centernet_effnetb5_bifpn_fold1_00099.pth' bifpn_path_3 = '.. /input/wheat-weights/model_centernet_effnetb5_bifpn_fold3_lb_ema_00099.pth'<init_hyperparams>
train_txts, val_txts, y_train, y_val = train_test_split( df[col].values, df['target'].values, shuffle = True, test_size = 0.15, stratify = df['target'].values, ) test_txts = test_df[col].values y_test = test_df['target'].values print('Train size:', train_txts.shape) print('Validation size:', val_txts.shape) print(...
Natural Language Processing with Disaster Tweets
20,927,228
class Config: arch = 'timm-efficientnet-b5' heads = {'hm': 1, 'wh': 2, 'reg': 2} head_conv = 64 reg_offset = True cat_spec_wh = False img_size = 1024 in_scale = 1024 / img_size down_ratio = 4 mean = [0.315290, 0.317253, 0.214556], std = [0.245211, 0.238036, 0.193879] num_classes = 1 pad = 63 batch_size = 8 K = 128 max_...
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased' )
Natural Language Processing with Disaster Tweets
20,927,228
def change_key(d): for _ in range(len(d)) : k, v = d.popitem(False) d['.'.join(k.split('.')[1:])] = v<load_from_csv>
def tokenize_txts(txts, max_len = 40): res = tokenizer( text = [tokenizer.tokenize(txt)for txt in txts], max_length = max_len, padding = 'max_length', truncation = True, is_split_into_words = True, ) return { 'input_word_ids': res['input_ids'], 'input_mask': res['attention_mask'], 'input_type_ids': res['token_type_i...
Natural Language Processing with Disaster Tweets
20,927,228
DIR_INPUT = '.. /input/global-wheat-detection' DIR_TRAIN = f'{DIR_INPUT}/train' DIR_TEST = f'{DIR_INPUT}/test' train_df = pd.read_csv(f'{DIR_INPUT}/train.csv') train_df.shape<data_type_conversions>
MAX_LEN = 35 BATCH_SIZE = 32
Natural Language Processing with Disaster Tweets
20,927,228
train_df['x'] = -1 train_df['y'] = -1 train_df['w'] = -1 train_df['h'] = -1 def expand_bbox(x): r = np.array(re.findall("([0-9]+[.]?[0-9]*)", x)) if len(r)== 0: r = [-1, -1, -1, -1] return r train_df[['x', 'y', 'w', 'h']] = np.stack(train_df['bbox'].apply(lambda x: expand_bbox(x))) train_df.drop(columns=['bbox'], inpl...
train_tokens = tokenize_txts(train_txts, MAX_LEN) val_tokens = tokenize_txts(val_txts, MAX_LEN) test_tokens = tokenize_txts(test_txts, MAX_LEN)
Natural Language Processing with Disaster Tweets
20,927,228
class WheatDatasetTest(torch.utils.data.Dataset): def __init__(self, opt, image_dir, transforms=None, mean=[0.315290, 0.317253, 0.214556], std=[0.245211, 0.238036, 0.193879]): self.opt = opt self.image_dir = image_dir self.img_id = os.listdir(self.image_dir) self.transforms = transforms self.mean = np.array(mean, dtyp...
print('Orginal txt: ', train_txts[0]) print() sample = train_tokens['input_word_ids'][0] print('Tokenized txt:', sample) print() print('Detokenizd txt:', detokenize_txt(sample))
Natural Language Processing with Disaster Tweets
20,927,228
def flip_lr(img): return np.ascontiguousarray(img[:, ::-1, :]) def deaug_lr(img, boxes): h, w = img.shape[:2] boxes[:,(0, 2)] = w - boxes[:,(2, 0)] return boxes def flip_ud(img): return np.ascontiguousarray(img[::-1, :, :]) def deaug_ud(img, boxes): h, w = img.shape[:2] boxes[:,(1, 3)] = w - boxes[:,(3, 1)] return bo...
train_ds = tf.data.Dataset.from_tensor_slices(( train_tokens, y_train)) val_ds = tf.data.Dataset.from_tensor_slices(( val_tokens, y_val)) test_ds = tf.data.Dataset.from_tensor_slices(( test_tokens, y_test)) train_ds = train_ds.batch(BATCH_SIZE) val_ds = val_ds.batch(BATCH_SIZE) test_ds = test_ds.batch(BATCH_SIZE )
Natural Language Processing with Disaster Tweets
20,927,228
testdataset = WheatDatasetTest(opt, DIR_TEST) print('Total number of images in test set: {}'.format(len(testdataset))) testdataset_lr = WheatDatasetTest(opt, DIR_TEST, transforms=flip_lr) testdataset_ud = WheatDatasetTest(opt, DIR_TEST, transforms=flip_ud )<find_best_model_class>
class MyF1(tf.keras.metrics.Metric): def __init__(self, name = 'mf1_score'): super(MyF1, self ).__init__(name) self.p = tf.metrics.Precision() self.r = tf.metrics.Recall() self.f1 = self.add_weight(name="f1", initializer="zeros") def update_state(self, actual, predicted, sample_weight = None): self.p.update_state(act...
Natural Language Processing with Disaster Tweets
20,927,228
def do_predict(opt, model, threshold, flip_type=0, return_ids=False, return_shapes=False): if flip_type == 0: test_dataset = testdataset deaug_transform = None elif flip_type == 1: test_dataset = testdataset_lr deaug_transform = deaug_lr elif flip_type == 2: test_dataset = testdataset_ud deaug_transform = deaug_ud dete...
class CSchedule(tf.keras.optimizers.schedules.LearningRateSchedule): def __init__(self, lr, freeze_epoch ,batch_size, data_size): super(CSchedule, self ).__init__() self.lr = lr self.bs = batch_size self.ds = data_size self.freeze_epoch = freeze_epoch def __call__(self, step): epoch = step /(self.ds / self.bs)+ 1 if no...
Natural Language Processing with Disaster Tweets
20,927,228
bifpn_model = PoseBiFPNNet(opt.arch, opt.heads, opt.head_conv) checkpoint = torch.load(bifpn_path_0, map_location=device) change_key(checkpoint['model']) bifpn_model.load_state_dict(checkpoint['model']) bifpn_model.to(device) del checkpoint gc.collect()<predict_on_test>
bert_handler = 'https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/3'
Natural Language Processing with Disaster Tweets
20,927,228
opt.pad = 63 opt.test_scales = [1.1, ] threshold = 0.30 bifpn0_pred_boxes_0 , bifpn0_pred_scores_0, h0_list, w0_list, img_ids = do_predict(opt, bifpn_model, threshold=threshold, flip_type=0, return_ids=True, return_shapes=True) bifpn0_pred_boxes_0_lr, bifpn0_pred_scores_0_lr = do_predict(opt, bifpn_model, threshold=th...
class MClassifier(tf.keras.Model): def __init__(self, dropout_rate): super(MClassifier, self ).__init__() self.bert_layer = hub.KerasLayer( bert_handler, name = 'feature_ext', trainable = True, ) self.dropout = tf.keras.layers.Dropout(dropout_rate) self.proba = tf.keras.layers.Dense(1, activation = 'sigmoid') def ...
Natural Language Processing with Disaster Tweets
20,927,228
del bifpn_model gc.collect() torch.cuda.empty_cache()<load_pretrained>
LEARNING_RATE = 2e-5 EPOCHS = 5 DP_RATE = 0.3 loss_objective = tf.keras.losses.BinaryCrossentropy()
Natural Language Processing with Disaster Tweets
20,927,228
bifpn_model = PoseBiFPNNet(opt.arch, opt.heads, opt.head_conv) checkpoint = torch.load(bifpn_path_1, map_location=device) change_key(checkpoint['model']) bifpn_model.load_state_dict(checkpoint['model']) bifpn_model.to(device) del checkpoint gc.collect()<predict_on_test>
def model_evaluation(model, ds, name): acc = tf.keras.metrics.BinaryAccuracy() f1 = MyF1() total_loss = [] y_hats = [] for X, y in ds: y_hat = model(X, training = False) loss = loss_objective(y, y_hat) acc.update_state(y, y_hat) f1.update_state(y, y_hat) total_loss.append(loss.numpy()) y_hats.append(y_hat) y_hats...
Natural Language Processing with Disaster Tweets
20,927,228
opt.pad = 63 opt.test_scales = [1.1, ] threshold = 0.30 bifpn1_pred_boxes_0 , bifpn1_pred_scores_0 = do_predict(opt, bifpn_model, threshold=threshold, flip_type=0, return_ids=False, return_shapes=False) bifpn1_pred_boxes_0_lr, bifpn1_pred_scores_0_lr = do_predict(opt, bifpn_model, threshold=threshold, flip_type=1, ret...
@tf.function def train_step(model, tr_vars, X, y): with tf.GradientTape() as tape: y_hat = model(X, training = True) loss = loss_objective(y, y_hat) grads = tape.gradient(loss, tr_vars) return loss, grads, y_hat def train_model(model, epochs, freeze_bert_on_epoch = None): clr = CSchedule(LEARNING_RATE, freeze_bert_o...
Natural Language Processing with Disaster Tweets
20,927,228
del bifpn_model gc.collect() torch.cuda.empty_cache()<load_pretrained>
model = MClassifier(DP_RATE,) y_test_hat = train_model(model, EPOCHS, freeze_bert_on_epoch = 3 )
Natural Language Processing with Disaster Tweets
20,927,228
bifpn_model = PoseBiFPNNet(opt.arch, opt.heads, opt.head_conv) checkpoint = torch.load(bifpn_path_3, map_location=device) change_key(checkpoint['model']) bifpn_model.load_state_dict(checkpoint['model']) bifpn_model.to(device) del checkpoint gc.collect()<predict_on_test>
y_model_hat = np.array([1 if x[0] >0.5 else 0 for x in y_test_hat]) print(classification_report(y_test, y_model_hat))
Natural Language Processing with Disaster Tweets
20,927,228
opt.pad = 63 opt.test_scales = [1.1, ] threshold = 0.30 bifpn3_pred_boxes_0 , bifpn3_pred_scores_0 = do_predict(opt, bifpn_model, threshold=threshold, flip_type=0, return_ids=False, return_shapes=False) bifpn3_pred_boxes_0_lr, bifpn3_pred_scores_0_lr = do_predict(opt, bifpn_model, threshold=threshold, flip_type=1, ret...
def train_gbm_cls(X_tr, y_tr, X_val, y_val, X_test, y_test): gbm_cls = LGBMClassifier( objective = 'binary', class_weight = 'balanced' ) gbm_cls.fit( X_tr, y_tr, eval_set =(X_val, y_val), early_stopping_rounds = 20, verbose = 0, ) print('Train') print(classification_report(y_train, gbm_cls.predict(X_tr))) print...
Natural Language Processing with Disaster Tweets
20,927,228
del bifpn_model gc.collect() torch.cuda.empty_cache()<categorify>
sub = pd.DataFrame(columns = ['id', 'target']) sub['id'] = test_df.id sub['target'] = gbm_y_hat
Natural Language Processing with Disaster Tweets
20,927,228
def normalize_boxes(boxes, h0, w0): boxes[:, 0] = boxes[:, 0] / w0 boxes[:, 1] = boxes[:, 1] / h0 boxes[:, 2] = boxes[:, 2] / w0 boxes[:, 3] = boxes[:, 3] / h0 return boxes def denormalize_clip_boxes(boxes, h0, w0): boxes[:, 0] = np.clip(boxes[:, 0] * w0, 0, w0-1) boxes[:, 1] = np.clip(boxes[:, 1] * h0, 0, h0-1) boxe...
nsub = pd.DataFrame(columns = ['id', 'target']) nsub['id'] = test_df.id nsub['target'] = y_model_hat nsub.to_csv('submission.csv', index = False )
Natural Language Processing with Disaster Tweets
20,267,711
sys.path.insert(0, ".. /input/weightedboxesfusion") iou_thr = 0.44 skip_box_thr = 0.00001 pred_boxes_ensemble = [] pred_scores_ensemble = [] for(b00, b01, b02, b03, b04, b05, b10, b11, b12, b13, b14, b15, b20, b21, b22, b23, b24, b25, s00, s01, s02, s03, s04, s05, s10, s11, s12, s13, s14, s15, s20, s21, s22, s23, s24,...
!pip install tweet_preprocessor !pip install datasets
Natural Language Processing with Disaster Tweets
20,267,711
pred_boxes_ensemble = [denormalize_clip_boxes(a, h0, w0)for a, h0, w0 in zip(pred_boxes_ensemble, h0_list, w0_list)] pred_scores_ensemble = [a for a in pred_scores_ensemble]<categorify>
train = pd.read_csv('/kaggle/input/nlp-getting-started/train.csv') test = pd.read_csv('/kaggle/input/nlp-getting-started/test.csv' )
Natural Language Processing with Disaster Tweets
20,267,711
data_dict_pseudo = [] id_generator = 20201000000 for idx,(bboxes, h0, w0)in enumerate(zip(tqdm(pred_boxes_ensemble), h0_list, w0_list)) : img_dict = { 'file_name': os.path.join(DIR_TEST, testdataset[idx][1]), 'height': h0, 'width': w0, 'id': id_generator, } annotations = [] for bbox in bboxes: xywh = np.round([bbox[0],...
sample_submission = pd.read_csv('/kaggle/input/nlp-getting-started/sample_submission.csv') sample_submission.head(20 )
Natural Language Processing with Disaster Tweets
20,267,711
data_dict_pseudo = [d for d in data_dict_pseudo if len(d['annotations'])> 0]<init_hyperparams>
train.dropna()
Natural Language Processing with Disaster Tweets
20,267,711
class TrainConfig: seed = 2519 arch = 'timm-efficientnet-b5' heads = { 'hm': 1, 'wh': 2, 'reg': 2} head_conv = 64 reg_offset = True data_root = '.. /input/global-wheat-detection' crop_size = 896 scale = 0. shift = 0. rotate = 15. shear = 5. down_ratio = 4 debug = False hm_weight = 1 off_weight = 1 wh_weight = 0.1 b...
print('train positive samples: %d' % train[train['target'] == 1].shape[0]) print('train negative samples: %d' % train[train['target'] == 0].shape[0] )
Natural Language Processing with Disaster Tweets
20,267,711
with open('.. /input/wheat-splits/wheat_train_3.json', 'r')as f: data_dict_train = json.load(f) with open('.. /input/wheat-splits/wheat_valid_3.json', 'r')as f: data_dict_valid = json.load(f )<create_dataframe>
def preprocess(text): text = text.replace(" text = p.clean(text) return text train['text'] = train['text'].apply(lambda x: preprocess(x)) test['text'] = test['text'].apply(lambda x: preprocess(x)) print(train['text'].values.tolist() [:5]) print(test['text'].values.tolist() [:5] )
Natural Language Processing with Disaster Tweets
20,267,711
def main(opt): set_seed(opt.seed) torch.backends.cudnn.benchmark = True create_logging(opt.logs_dir, 'w') train_dataset = WheatDataset( opt, opt.data_root, data_dict_train, data_dict_pseudo=data_dict_pseudo, img_size=1024, transforms=get_train_transforms(opt.crop_size), is_train=True, load_to_ram=False) logging.inf...
X_train, X_val, y_train, y_val = train_test_split(train['text'], train['target'], test_size=.1, random_state=42) X_test = test['text'].values.tolist() X_train = X_train.tolist() X_val = X_val.tolist() y_train = y_train.tolist() y_val = y_val.tolist()
Natural Language Processing with Disaster Tweets
20,267,711
gc.collect() torch.cuda.empty_cache() pseudo_model = PoseBiFPNNet(train_opt.arch, train_opt.heads, train_opt.head_conv) if len(os.listdir(DIR_TEST)) < 20: train_opt.total_epochs = 2 train_opt.stage_epochs = 2 data_dict_train = data_dict_train[:300] state_dict = main(train_opt) change_key(state_dict) pseudo_model.loa...
model = AutoModelForSequenceClassification.from_pretrained('vinai/bertweet-large') tokenizer = AutoTokenizer.from_pretrained("vinai/bertweet-large", use_fast=False )
Natural Language Processing with Disaster Tweets
20,267,711
opt.pad = 63 opt.test_scales = [1.1, ] threshold = 0.32 pseudo_pred_boxes_0 , pseudo_pred_scores_0, h0_list, w0_list, img_ids = do_predict(opt, pseudo_model, threshold=threshold, flip_type=0, return_ids=True, return_shapes=True) pseudo_pred_boxes_0_lr, pseudo_pred_scores_0_lr = do_predict(opt, pseudo_model, threshold=...
train_encodings = tokenizer(X_train, truncation=True, padding=True) val_encodings = tokenizer(X_val, truncation=True, padding=True )
Natural Language Processing with Disaster Tweets
20,267,711
pred_boxes_pseudo = [denormalize_clip_boxes(a, h0, w0)for a, h0, w0 in zip(pred_boxes_pseudo, h0_list, w0_list)] pred_scores_pseudo = [a for a in pred_scores_pseudo]<categorify>
class DisasterDataset(torch.utils.data.Dataset): def __init__(self, encodings, labels): self.encodings = encodings self.labels = labels def __getitem__(self, idx): item = {key: torch.tensor(val[idx])for key, val in self.encodings.items() } item['labels'] = torch.tensor(self.labels[idx]) return item def __len__(self): ...
Natural Language Processing with Disaster Tweets
20,267,711
def format_prediction_string(boxes, scores): pred_strings = [] for s, b in zip(scores, boxes.astype(int)) : pred_strings.append(f'{s:.4f} {b[0]} {b[1]} {b[2]} {b[3]}') return " ".join(pred_strings )<compute_test_metric>
acc = load_metric('accuracy') precision = load_metric('precision') recall = load_metric('recall') f1 = load_metric('f1') def compute_metrics(eval_pred): predictions, labels = eval_pred predictions = np.argmax(predictions, axis=1) acc_result = acc.compute(predictions=predictions, references=labels) precision_resul...
Natural Language Processing with Disaster Tweets
20,267,711
pred_strs = [] for bboxes, scores in zip(pred_boxes_pseudo, pred_scores_pseudo): if len(bboxes)> 0: bboxes[:, 2] -= bboxes[:, 0] bboxes[:, 3] -= bboxes[:, 1] bboxes = bboxes.round() pred_strs.append(format_prediction_string(bboxes, scores)) else: pred_strs.append('' )<create_dataframe>
nlp=pipeline("sentiment-analysis", model=model.to('cpu'), tokenizer=tokenizer) test_preds = [] for index, text in enumerate(test['text'].values.tolist()): if index % 10 == 0: print(index) if nlp(text)[0]['label'] == 'LABEL_0': test_preds.append(0) else: test_preds.append(1) test['target'] = test_preds
Natural Language Processing with Disaster Tweets
20,267,711
<save_to_csv><EOS>
submissions = test.drop(labels = ["keyword", "location", "text"], axis = 1) submissions.to_csv("submissions.csv", index = False )
Natural Language Processing with Disaster Tweets
19,958,768
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<init_hyperparams>
warnings.simplefilter(action='ignore', category=FutureWarning)
Natural Language Processing with Disaster Tweets
19,958,768
TIME_LIMIT = 6.9*60*60 Origin = False p_HF = True p_ROT = False eimg_size = 1024 pesudo_thres = 0.4 pesudo_iou = 0.35 pesudo_score_threshold = 0 img_size = 1024 NMS_IOU_THR = 0.6 NMS_CONF_THR = 0.35 best_iou_thr = 0.35 best_skip_box_thr = 0.35 best_final_score = 0 best_score_threshold = 0.1 EPO = 8 WEIGHTS = ".. /input...
try: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() print('Running on TPU ', tpu.master()) except ValueError: tpu = None if tpu: tf.config.experimental_connect_to_cluster(tpu) tf.tpu.experimental.initialize_tpu_system(tpu) strategy = tf.distribute.experimental.TPUStrategy(tpu) else: strategy = tf.distrib...
Natural Language Processing with Disaster Tweets
19,958,768
!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 sys.path.insert(0, ".. /input/timm-efficientdet-pytorch") sys.path.insert(0, ".. /input/omegaconf") <feature_engineering>
train_dir = ".. /input/nlp-getting-started/train.csv" df = pd.read_csv(train_dir) x =(df['text'] .str.lower() .str.replace('\x89Ûª|‰Ûª', "'") .str.replace(' |\x89.|\x9d *', ' ') .str.replace('&gt;', ">") .str.replace('&lt;', "<") .str.replace('&amp;', " and ") .str.replace('won't', 'will not') .str.replace('can't', ...
Natural Language Processing with Disaster Tweets
19,958,768
def convertTrainLabel(max_label_numbers): df = pd.read_csv(csv_file) 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['x1'] = df['x'] + df['w'] df['y1'] = df['y'] + df['h'...
tokenizer = AutoTokenizer.from_pretrained('vinai/bertweet-base', normalization=True, use_fast = False, add_special_tokens=True, pad_to_max_length=True, return_attention_mask=True) train_token = tokenizer(x_train.tolist() , padding="max_length", truncation=True, return_tensors = 'tf' ).data val_token = tokenizer(x_val....
Natural Language Processing with Disaster Tweets
19,958,768
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...
with strategy.scope() : bert_model = TFRobertaModel.from_pretrained("vinai/bertweet-base") def build_model(hidden_n, drop = 0.3, lr = 1e-5, weight_decay = 1e-6): with strategy.scope() : input_ids = tf.keras.Input(shape=(128,),dtype='int32', name = 'input_ids') attention_masks = tf.keras.Input(shape=(128,),dtype='int3...
Natural Language Processing with Disaster Tweets
19,958,768
@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...
grid = [{'hidden_n': 16, 'drop': 0.3, 'lr': 1e-5, 'weight_decay': 1e-6}, {'hidden_n': 32, 'drop': 0.3, 'lr': 1e-5, 'weight_decay': 1e-6}, {'hidden_n': 32, 'drop': 0.3, 'lr': 5e-6, 'weight_decay': 1e-6}, {'hidden_n': 32, 'drop': 0.25, 'lr': 1e-5, 'weight_decay': 5e-6}, {'hidden_n': 32, 'drop': 0.35, 'lr': 1e-5, 'weight_...
Natural Language Processing with Disaster Tweets
19,958,768
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...
TEST_PATH = ".. /input/nlp-getting-started/test.csv" df = pd.read_csv(TEST_PATH) x =(df['text'] .str.lower() .str.replace('\x89Ûª|‰Ûª', "'") .str.replace(' |\x89.|\x9d *', ' ') .str.replace('&gt;', ">") .str.replace('&lt;', "<") .str.replace('&amp;', " and ") .str.replace('won't', 'will not') .str.replace('can't', '...
Natural Language Processing with Disaster Tweets
19,958,768
<categorify><EOS>
df[['id', 'target']].to_csv("submissions.csv", index = False )
Natural Language Processing with Disaster Tweets
15,639,884
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<choose_model_class>
pip install -U lightautoml
Natural Language Processing with Disaster Tweets
15,639,884
model_struct = 'tf_efficientdet_d7' def get_valnet_file(Get_Path): config = get_efficientdet_config(model_struct) 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, momentu...
pip install -U transformers
Natural Language Processing with Disaster Tweets
15,639,884
if is_TEST: if PSEUDO: remain_times = 60 !python train.py -TRAIN_EPOCHS {EPO} -cfgfile {CONFIG} -op {OPTIMIZER} -dir /kaggle/working/convertor -pretrained {WEIGHTS} -train_label_path convertor/train.txt -val_label_path convertor/val.txt -optimizer radam -iou-type ciou -l 0.0001 -g 0 -classes 1 -maxboxes {max_label_numb...
import os import time import numpy as np import pandas as pd from sklearn.metrics import f1_score from sklearn.model_selection import train_test_split import torch import matplotlib.pyplot as plt from lightautoml.automl.presets.text_presets import TabularNLPAutoML from lightautoml.dataset.roles import DatetimeRole from...
Natural Language Processing with Disaster Tweets
15,639,884
if VALIDATE and is_TEST: all_predictions = validate() for score_threshold in tqdm(np.arange(0.1, 0.25, 0.01), total=np.arange(0.1, 0.25, 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...
N_THREADS = 4 RANDOM_STATE = 42 TEST_SIZE = 0.2 TIMEOUT = 6 * 3600 TARGET_NAME = 'target'
Natural Language Processing with Disaster Tweets
15,639,884
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_cv2(pesudo_result): use_cuda = True DATA_ROOT_PATH = '.. /input/global-wheat-detection/t...
np.random.seed(RANDOM_STATE) torch.set_num_threads(N_THREADS )
Natural Language Processing with Disaster Tweets
15,639,884
results = detect_cv2(pesudo_result) test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.to_csv('submission.csv', index=False) test_df.head()<import_modules>
%%time train_data = pd.read_csv('.. /input/nlp-getting-started/train.csv') train_data.head()
Natural Language Processing with Disaster Tweets
15,639,884
sys.path.insert(0, ".. /input/weightedboxesfusion") device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print(device) <choose_model_class>
test_data = pd.read_csv('.. /input/nlp-getting-started/test.csv') test_data.head()
Natural Language Processing with Disaster Tweets
15,639,884
def load_resnet101_model(checkpoint_path): num_classes = 2 backbone = resnet_fpn_backbone('resnet101', pretrained= False) model_faster = FasterRCNN(backbone, num_classes) in_features = model_faster.roi_heads.box_predictor.cls_score.in_features model_faster.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_...
submission = pd.read_csv('.. /input/nlp-getting-started/sample_submission.csv') submission.head()
Natural Language Processing with Disaster Tweets
15,639,884
resnet101_33e = ".. /input/resnet10133e-1024/cp33.pt" resnet50 = ".. /input/resnet50-40e/resnet50_40e.pt" resnet101_25e = ".. /input/resnet101mymodel/cp25.pt" resnet152_20e = ".. /input/resnet152-20e/cp20.pt" resnet152_19e =".. /input/resnet152-19e/cp19(1 ).pt"<load_pretrained>
train_data.target.value_counts()
Natural Language Processing with Disaster Tweets
15,639,884
models = [ load_resnet50_model(resnet50), load_resnet152_model(resnet152_20e), load_resnet152_model(resnet152_19e) ]<data_type_conversions>
train_data['keyword'].value_counts(dropna = False )
Natural Language Processing with Disaster Tweets
15,639,884
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_data['location'].value_counts(dropna = False )
Natural Language Processing with Disaster Tweets
15,639,884
def get_valid_transforms() : return A.Compose([ ToTensorV2(p=1.0), ], p=1.0 )<define_variables>
def clean_text(text): return text
Natural Language Processing with Disaster Tweets
15,639,884
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_pretrained>
all_data = pd.concat([ train_data.drop(TARGET_NAME, axis = 1), test_data ] ).reset_index(drop = True) all_data['location'] = all_data['location'].astype(str) all_data.loc[all_data['location'].value_counts() [all_data['location']].values < 5, 'location'] = "RARE_VALUE" all_data.loc[all_data['location'] == 'nan', 'loca...
Natural Language Processing with Disaster Tweets
15,639,884
dataset = DatasetRetriever(np.array([path.split('/')[-1][:-4] for path in glob.glob(f'{DATA_ROOT_PATH}/*.jpg')]),get_valid_transforms()) def collate_fn(batch): return tuple(zip(*batch)) data_loader = DataLoader( dataset, batch_size=1, shuffle=False, num_workers=2, drop_last=False, collate_fn=collate_fn )<categorify>
y_train = train_data.target.values train_data = all_data[:len(train_data)] train_data[TARGET_NAME] = y_train test_data = all_data[len(train_data):]
Natural Language Processing with Disaster Tweets
15,639,884
class BaseWheatTTA: image_size = 1024 def augment(self, image): raise NotImplementedError def batch_augment(self, images): raise NotImplementedError def deaugment_boxes(self, boxes): raise NotImplementedError class TTAHorizontalFlip(BaseWheatTTA): def augment(self, image): return image.flip(1) def batch_augment(se...
%%time roles = {'target': TARGET_NAME, 'text': ['text'], 'drop': ['id']}
Natural Language Processing with Disaster Tweets
15,639,884
def make_tta_predictions(model,images, score_threshold=0.35): model.eval() model.to(device) with torch.no_grad() : images = torch.stack(images ).float().cuda() predictions = [] for tta_transform in tta_transforms: result = [] det = model(tta_transform.batch_augment(images.clone())) for i in range(images.shape[0]): box...
%%time automl = TabularNLPAutoML(task = task, timeout = TIMEOUT, cpu_limit = N_THREADS, reader_params = {'cv': 5}, general_params = {'nested_cv': False, 'use_algos': [['linear_l2', 'lgb', 'nn']]}, text_params = {'lang': 'en'}, nn_params = {'lang': 'en', 'bert_name': 'vinai/bertweet-base', 'opt_params': { 'lr': 1e-5}, '...
Natural Language Processing with Disaster Tweets
15,639,884
tta_transforms = [] for tta_combination in product([TTAHorizontalFlip() , None], [TTAVerticalFlip() , None], [TTARotate90() , TTARotate180() , TTARotate270() , None]): tta_transforms.append(TTACompose([tta_transform for tta_transform in tta_combination if tta_transform])) <define_variables>
automl.collect_used_feats()
Natural Language Processing with Disaster Tweets
15,639,884
validation_image_precisions = [] iou_thresholds = [x for x in np.arange(0.5, 0.76, 0.05)] results = [] ts = 0.147 for images, image_ids in data_loader: predictions = make_ensemble_predictions(images) for i, image in enumerate(images): boxes, scores, labels = run_wbf(predictions, image_index=i, iou_thr=0.35, skip_box_t...
test_pred = automl.predict(test_data) print('Prediction for test data: {} Shape = {}'.format(test_pred, test_pred.shape))
Natural Language Processing with Disaster Tweets
15,639,884
test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.to_csv('submission.csv', index=False) test_df.head(10 )<install_modules>
def select_threshold_f1(y_true, y_pred): best_score = -1 best_thr = None for thr in np.arange(0, 1.01, 0.01): score = f1_score(y_true,(y_pred > thr ).astype(int)) if score > best_score: best_score = score best_thr = thr print('Best score: {} Best selected threshold: {:.2f}'.format(best_score, best_thr)) return best_thr...
Natural Language Processing with Disaster Tweets
15,639,884
!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<set_options>
submission['target'] =(test_pred.data[:, 0] > best_thr ).astype(int) submission
Natural Language Processing with Disaster Tweets
15,639,884
SEED = 42 def seed_everything(seed): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = True seed_everything(SEED )<load_from_csv>
submission['target'].value_counts()
Natural Language Processing with Disaster Tweets
15,639,884
marking = pd.read_csv('.. /input/global-wheat-detection/train.csv') bboxs = np.stack(marking['bbox'].apply(lambda x: np.fromstring(x[1:-1], sep=','))) for i, column in enumerate(['x', 'y', 'w', 'h']): marking[column] = bboxs[:,i] marking.drop(columns=['bbox'], inplace=True) marking.sample(10 )<feature_engineering>
submission.to_csv('LightAutoML_preds_without_id.csv', index = False )
Natural Language Processing with Disaster Tweets
14,591,530
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) df_folds = marking[['image_id']].copy() df_folds.loc[:, 'bbox_count'] = 1 df_folds = df_folds.groupby('image_id' ).count() df_folds.loc[:, 'source'] = marking[['image_id', 'source']].groupby('image_id' ).min() ['source'] df_folds.loc[:, 'stratify_group']...
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print("Using %s" %(device)) seed_val = 42 random.seed(seed_val) np.random.seed(seed_val) torch.manual_seed(seed_val) torch.cuda.manual_seed_all(seed_val )
Natural Language Processing with Disaster Tweets
14,591,530
TRAIN_ROOT_PATH = '.. /input/global-wheat-detection/train' class WheatDataset(Dataset): def __init__(self, marking, image_ids, transforms=None, test=False): super().__init__() self.image_ids = image_ids self.marking = marking self.transforms = transforms self.test = test def __getitem__(self, index: int): image_id = se...
def clean_text(text): text = text.lower() text = re.sub(r'[!]+', '!', text) text = re.sub(r'[?]+', '?', text) text = re.sub(r'[.]+', '.', text) text = re.sub(r"'", "", text) text = re.sub('\s+', ' ', text ).strip() text = re.sub(r'&amp;?', r'and', text) text = re.sub(r"https?:\/\/t.co\/[A-Za-z0-9]+", "", text) te...
Natural Language Processing with Disaster Tweets
14,591,530
fold_number = 0 train_dataset = WheatDataset( image_ids=df_folds[df_folds['fold'] != fold_number].index.values, marking=marking, transforms=get_train_transforms() , test=False, ) validation_dataset = WheatDataset( image_ids=df_folds[df_folds['fold'] == fold_number].index.values, marking=marking, transforms=get_vali...
train = pd.read_csv("/kaggle/input/nlp-getting-started/train.csv") test = pd.read_csv("/kaggle/input/nlp-getting-started/test.csv") train['text_new'] = train['text'].apply(clean_text) test['text'] = test['text'].apply(clean_text) train_texts = list(train["text"]) train_labels = list(train["target"]) res_texts = l...
Natural Language Processing with Disaster Tweets
14,591,530
class AverageMeter(object): def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count<train_model>
tokenizer = DistilBertTokenizerFast.from_pretrained('distilbert-base-uncased') train_encoding = tokenizer(x_train, truncation=True, padding=True) test_encoding = tokenizer(x_test, truncation=True, padding=True) res_encoding = tokenizer(res_texts, truncation=True, padding=True )
Natural Language Processing with Disaster Tweets
14,591,530
class Fitter: def __init__(self, model, device, config): self.config = config self.epoch = 0 self.base_dir = f'./{config.folder}' if not os.path.exists(self.base_dir): os.makedirs(self.base_dir) self.log_path = f'{self.base_dir}/log.txt' self.best_summary_loss = 10**5 self.model = model self.device = device param_opti...
class TwitterDataset(Dataset): def __init__(self, encodings, labels): self.encodings = encodings self.labels = labels def __getitem__(self, idx): item = {key: torch.tensor(val[idx])for key, val in self.encodings.items() } item['labels'] = torch.tensor(self.labels[idx]) return item def __len__(self): return len(self.la...
Natural Language Processing with Disaster Tweets
14,591,530
class TrainGlobalConfig: num_workers = 2 batch_size = 4 n_epochs = 3 lr = 0.0002 folder = 'effdet5-cutmix-augmix' verbose = True verbose_step = 1 step_scheduler = False validation_scheduler = True SchedulerClass = torch.optim.lr_scheduler.ReduceLROnPlateau scheduler_params = dict( mode='min', factor=0.5, patience=1, v...
def flat_accuracy(preds, labels): pred_flat = np.argmax(preds, axis=1 ).flatten() labels_flat = labels.flatten() return np.sum(pred_flat == labels_flat)/ len(labels_flat )
Natural Language Processing with Disaster Tweets
14,591,530
def collate_fn(batch): return tuple(zip(*batch))<load_pretrained>
step_nums = 30 model = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased') model.to(device) train_loader = DataLoader(train_dataset, batch_size=16, shuffle=True) test_dataloader = DataLoader(test_dataset, batch_size=16, shuffle=True) optim = AdamW(model.parameters() , lr=2e-5) scheduler ...
Natural Language Processing with Disaster Tweets
14,591,530
def run_training() : device = torch.device('cuda:0') net.to(device) train_loader = torch.utils.data.DataLoader( train_dataset, batch_size=TrainGlobalConfig.batch_size, sampler=RandomSampler(train_dataset), pin_memory=False, drop_last=True, num_workers=TrainGlobalConfig.num_workers, collate_fn=collate_fn, ) val_loa...
epoth_num=5 model = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased') model.to(device) train_loader = DataLoader(train_dataset, batch_size=16, shuffle=True) test_dataloader = DataLoader(test_dataset, batch_size=16, shuffle=True) optim = AdamW(model.parameters() , lr=2e-5) total_steps =...
Natural Language Processing with Disaster Tweets
14,591,530
def get_net() : config = get_efficientdet_config('tf_efficientdet_d5') net = EfficientDet(config, pretrained_backbone=False) checkpoint = torch.load('.. /input/efficientdet/efficientdet_d5-ef44aea8.pth') net.load_state_dict(checkpoint) config.num_classes = 1 config.image_size = 512 net.class_net = HeadNet(config, n...
print("Restoring the best model weights.") model.load_state_dict(torch.load("./model.weights")) model.eval() class TwitterValDataset(Dataset): def __init__(self, encodings): self.encodings = encodings def __getitem__(self, idx): item = {key: torch.tensor(val[idx])for key, val in self.encodings.items() } return item de...
Natural Language Processing with Disaster Tweets
15,318,234
run_training()<categorify>
train_set = pd.read_csv('.. /input/nlp-getting-started/train.csv') test_set = pd.read_csv('.. /input/nlp-getting-started/test.csv' )
Natural Language Processing with Disaster Tweets
15,318,234
def get_test_transforms() : return A.Compose([ A.Resize(height=512, width=512, p=1.0), ToTensorV2(p=1.0), ], p=1.0 )<data_type_conversions>
import re
Natural Language Processing with Disaster Tweets
15,318,234
DATA_ROOT_PATH = '.. /input/global-wheat-detection/test' class TestDatasetRetriever(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_PAT...
def clean_url(x): cleaned_x = re.sub(r'http\S{0,}', r'', x) return cleaned_x
Natural Language Processing with Disaster Tweets
15,318,234
dataset = TestDatasetRetriever( image_ids=np.array([path.split('/')[-1][:-4] for path in glob(f'{DATA_ROOT_PATH}/*.jpg')]), transforms=get_test_transforms() ) test_data_loader = DataLoader( dataset, batch_size=1, shuffle=False, num_workers=4, drop_last=False, collate_fn=collate_fn )<choose_model_class>
train_set['text'] = train_set['text'].apply(clean_url) test_set['text'] = test_set['text'].apply(clean_url )
Natural Language Processing with Disaster Tweets
15,318,234
def load_net(checkpoint_path): config = get_efficientdet_config('tf_efficientdet_d5') net = EfficientDet(config, pretrained_backbone=False) config.num_classes = 1 config.image_size=512 net.class_net = HeadNet(config, num_outputs=config.num_classes, norm_kwargs=dict(eps=.001, momentum=.01)) checkpoint = torch.load(che...
def clean_new_line(x): return re.sub(r" ", " ", x )
Natural Language Processing with Disaster Tweets
15,318,234
class BaseWheatTTA: image_size = 512 def augment(self, image): raise NotImplementedError def batch_augment(self, images): raise NotImplementedError def deaugment_boxes(self, boxes): raise NotImplementedError class TTAHorizontalFlip(BaseWheatTTA): def augment(self, image): return image.flip(1) def batch_augment(self, i...
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 )
Natural Language Processing with Disaster Tweets
15,318,234
tta_transforms = [] for tta_combination in product([TTAHorizontalFlip() , None], [TTAVerticalFlip() , None], [TTARotate90() , None]): tta_transforms.append(TTACompose([tta_transform for tta_transform in tta_combination if tta_transform]))<find_best_model_class>
train_set['text'] = train_set['text'].apply(clean_new_line) train_set['text'] = train_set['text'].apply(remove_emoji) train_set['text'] = train_set['text'].apply(lower_case )
Natural Language Processing with Disaster Tweets
15,318,234
def make_tta_predictions(images, score_threshold=0.25): with torch.no_grad() : images = torch.stack(images ).float().cuda() predictions = [] for tta_transform in tta_transforms: result = [] det = net(tta_transform.batch_augment(images.clone()), torch.tensor([1]*images.shape[0] ).float().cuda()) for i in range(images.s...
test_set['text'] = test_set['text'].apply(clean_new_line) test_set['text'] = test_set['text'].apply(remove_emoji) test_set['text'] = test_set['text'].apply(lower_case )
Natural Language Processing with Disaster Tweets
15,318,234
def run_wbf(predictions, image_index, image_size=512, iou_thr=0.44, skip_box_thr=0.43, weights=None): boxes = [(prediction[image_index]['boxes']/(image_size-1)).tolist() for prediction in predictions] scores = [prediction[image_index]['scores'].tolist() for prediction in predictions] labels = [np.ones(prediction[image_...
!wget --quiet https://raw.githubusercontent.com/tensorflow/models/master/official/nlp/bert/tokenization.py
Natural Language Processing with Disaster Tweets
15,318,234
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>
import tokenization from sklearn.model_selection import StratifiedKFold, StratifiedShuffleSplit from sklearn.metrics import precision_score, recall_score, f1_score import tensorflow as tf import tensorflow_hub as hub from tensorflow import keras from tensorflow.keras.optimizers import Adam, SGD from tensorflow.keras.la...
Natural Language Processing with Disaster Tweets