kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
15,318,234
results_plabel = [] for images, image_ids in test_data_loader: predictions = make_tta_predictions(images) for i, image in enumerate(images): image_id = image_ids[i] image_ = cv2.imread(f'{DATA_ROOT_PATH}/{image_id}.jpg', cv2.IMREAD_COLOR) h,w,_ = np.shape(image_) boxes, scores, labels = run_wbf(predictions, image_in...
bert_layer = hub.KerasLayer('https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/1', trainable=True )
Natural Language Processing with Disaster Tweets
15,318,234
results_df = pd.DataFrame(results_plabel, columns=['image_id', 'width','height','source','x','y','w','h']) results_df.head()<predict_on_test>
K = 2 skf = StratifiedKFold(n_splits=K, shuffle=True )
Natural Language Processing with Disaster Tweets
15,318,234
results = [] for images, image_ids in test_data_loader: predictions = make_tta_predictions(images) for i, image in enumerate(images): boxes, scores, labels = run_wbf(predictions, image_index=i) boxes =(boxes*2 ).astype(np.int32 ).clip(min=0, max=1023) image_id = image_ids[i] boxes[:, 2] = boxes[:, 2] - boxes[:, 0] b...
class ClassificationReport(Callback): def __init__(self, train_data=() , validation_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 = validation_data self.val_precision_sco...
Natural Language Processing with Disaster Tweets
15,318,234
test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.to_csv('submission.csv', index=False )<import_modules>
class DisasterDetector: def __init__(self, bert_layer, optimizer, max_seq_length=128, lr=0.0001, epochs=15, batch_size=32): self.bert_layer = bert_layer self.max_seq_length = max_seq_length vocab_file = self.bert_layer.resolved_object.vocab_file.asset_path.numpy() do_lower_case = self.bert_layer.resolved_object.do_lowe...
Natural Language Processing with Disaster Tweets
15,318,234
import numpy as np import pandas as pd import os from tqdm.auto import tqdm import shutil as sh<install_modules>
sgd = SGD(1e-3) clf = DisasterDetector(bert_layer,sgd, max_seq_length=128, lr=0.0001, epochs=10, batch_size=32) clf.train(train_set['text'], train_set['target'] )
Natural Language Processing with Disaster Tweets
15,318,234
!cp -r.. /input/yolov5-pseudo-labeling/* .<install_modules>
y_pred = clf.predict(test_set['text']) y_pred_thres = [1 if pred[0] >=0.5 else 0 for pred in y_pred] y_pred_df = pd.DataFrame(y_pred_thres, columns=['target'] )
Natural Language Processing with Disaster Tweets
15,318,234
!pip install --no-deps '.. /input/weightedboxesfusion/' > /dev/null<feature_engineering>
sample_subm = pd.read_csv('.. /input/nlp-getting-started/sample_submission.csv') id = sample_subm.id
Natural Language Processing with Disaster Tweets
15,318,234
R_fold = 1 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'] ...
subm = pd.concat([id, y_pred_df], axis=1 )
Natural Language Processing with Disaster Tweets
15,318,234
<load_pretrained><EOS>
subm.to_csv('sample_subm.csv', index=False, header = True )
Natural Language Processing with Disaster Tweets
15,118,972
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<load_pretrained>
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
15,118,972
<define_variables>
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
15,118,972
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 )<import_modules>
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
15,118,972
from utils.datasets import * from utils.utils import *<train_on_grid>
len(train["keyword"].value_counts() )
Natural Language Processing with Disaster Tweets
15,118,972
def detect1Image_aug(im0, imgsz, model, device, conf_thres, iou_thres): img = letterbox(im0, new_shape=imgsz)[0] img = img[:, :, ::-1].transpose(2, 0, 1) img = np.ascontiguousarray(img) img = torch.from_numpy(img ).to(device) img = img.float() img /= 255.0 if img.ndimension() == 3: img = img.unsqueeze(0) pred = mod...
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
15,118,972
def clip_coords2(boxes, img_shape): boxes[:, 0].clamp_(0, img_shape[1]) boxes[:, 1].clamp_(0, img_shape[0]) boxes[:, 2].clamp_(0, img_shape[1]) boxes[:, 3].clamp_(0, img_shape[0]) def scale_coords2(coords,factorx,factory, img0_shape): coords[:, 0::2] *= factorx coords[:, 1::2] *= factory clip_coords2(coords, img0_s...
keywords_vc.sort_values(by="Disaster_Probability", ascending=False ).head(10 )
Natural Language Processing with Disaster Tweets
15,118,972
!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<install_modules>
len(train["location"].value_counts() )
Natural Language Processing with Disaster Tweets
15,118,972
!pip install /kaggle/input/orkatzfdata/yacs-0.1.7-py3-none-any.whl !mkdir fvcore !cp -R '/kaggle/input/orkatzfdata/fvcore-0.1.dev200407/fvcore-0.1.dev200407/'./fvcore !pip install fvcore/fvcore-0.1.dev200407/. !mkdir detectron2-ResNeSt !cp -R /kaggle/input/orkatzfdata/detectron2-ResNeSt/*./detectron2-ResNeSt/ !pip ins...
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
15,118,972
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(c...
corpus_disaster, corpus_non_disaster = create_corpus(1), create_corpus(0) counter_disaster, counter_non_disaster = Counter(corpus_disaster), Counter(corpus_non_disaster) x_disaster, y_disaster, x_non_disaster, y_non_disaster = [], [], [], [] counter = 0 for word, count in counter_disaster.most_common() [0:100]: if(wo...
Natural Language Processing with Disaster Tweets
15,118,972
models2 = [load_net7('.. /input/tempb7/best-checkpoint-015epoch.bin'), load_net7('.. /input/tempb7/best-checkpoint-020epoch.bin'), load_net7('.. /input/tempb7/best-checkpoint-022epoch.bin'),] models = [ load_net('.. /input/effdetbestpth/best-fold0-augmix.pth'), load_net('.. /input/effdetbestpth/best-fold3.pth'), load_n...
def bigrams(target): corpus = train[train["target"] == target]["text"] count_vec = CountVectorizer(ngram_range=(2, 2)).fit(corpus) bag_of_words = count_vec.transform(corpus) sum_words = bag_of_words.sum(axis=0) words_freq = [(word, sum_words[0, idx])for word, idx in count_vec.vocabulary_.items() ] words_freq =sorted...
Natural Language Processing with Disaster Tweets
15,118,972
cfg = get_cfg() cfg.merge_from_file(model_zoo.get_config_file("COCO-Detection/faster_cascade_rcnn_ResNeSt_101_FPN_syncbn_range-scale_1x.yaml")) cfg.MODEL.ROI_HEADS.NUM_CLASSES = 1 cfg.MODEL.WEIGHTS = os.path.join('/kaggle/input/best-inrae-1/', "model_final.pth") cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.47 cfg.DATASET...
def remove_pattern(input_txt, pattern): r = re.findall(pattern, input_txt) for i in r: input_txt = re.sub(i, '', input_txt) return input_txt train['tweet'] = np.vectorize(remove_pattern )(train['text'], " test['tweet'] = np.vectorize(remove_pattern )(test['text'], " train.head() train['tweet'] = train['tweet'].str.re...
Natural Language Processing with Disaster Tweets
15,118,972
models3 =[predictor1]<data_type_conversions>
warnings.filterwarnings("ignore") tqdm.pandas() stopword=set(STOPWORDS) lem = WordNetLemmatizer() tokenizer=TweetTokenizer() np.random.seed(0) random_state = 29
Natural Language Processing with Disaster Tweets
15,118,972
DATA_ROOT_PATH = '.. /input/global-wheat-detection/test' class TestDatasetRetriever(Dataset): def __init__(self, image_ids, transforms=None,transforms2=None): super().__init__() self.image_ids = image_ids self.transforms = transforms self.transforms2 = transforms2 def __getitem__(self, index: int): image_id = self.imag...
!pip install GPUtil def free_gpu_cache() : print("Initial GPU Usage") gpu_usage() torch.cuda.empty_cache() cuda.select_device(0) cuda.close() cuda.select_device(0) for obj in gc.get_objects() : if torch.is_tensor(obj): del obj gc.collect() print("GPU Usage after emptying the cache") gpu_usage()
Natural Language Processing with Disaster Tweets
15,118,972
def make_predictions( images, images1,image_ids, score_threshold=0.25, ): images = images.cuda().float() images1 = images1.cuda().float() image_id = image_ids rh,rw,_ = cv2.imread(f'{DATA_ROOT_PATH}/{image_id}.jpg' ).shape Hscale512 = rh/512 Wscale512 = rw/512 Hscale1024 = rh/1024 Wscale1024 = rw/1024 predictions = [...
train = pd.read_csv(".. /input/nlp-getting-started/train.csv") test = pd.read_csv(".. /input/nlp-getting-started/test.csv") sub= pd.read_csv(".. /input/nlp-getting-started/sample_submission.csv" )
Natural Language Processing with Disaster Tweets
15,118,972
def clip_coords3(boxes, img_shape): boxes[:, 0].clamp_(0, img_shape[1]) boxes[:, 1].clamp_(0, img_shape[0]) boxes[:, 2].clamp_(0, img_shape[1]) boxes[:, 3].clamp_(0, img_shape[0]) return boxes<compute_test_metric>
abbreviations = { "$" : " dollar ", "€" : " euro ", "4ao" : "for adults only", "a.m" : "before midday", "a3" : "anytime anywhere anyplace", "aamof" : "as a matter of fact", "acct" : "account", "adih" : "another day in hell", "afaic" : "as far as i am concerned", "afaict" : "as far as i can tell", "afaik" : "as far as i...
Natural Language Processing with Disaster Tweets
15,118,972
def run_wbf2(predictions, image_index, image_size=1024, iou_thr=0.34, skip_box_thr=0.33, 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[imag...
def remove_URL(text): url = re.compile(r'https?://\S+|www\.\S+') return url.sub(r'URL',text) def remove_HTML(text): html=re.compile(r'<.*?>') return html.sub(r'',text) def remove_not_ASCII(text): text = ''.join([word for word in text if word in string.printable]) return text def word_abbrev(word): return abbreviat...
Natural Language Processing with Disaster Tweets
15,118,972
def detect() : transforms = get_valid_transforms() transforms2 = get_valid_transforms2() source = '.. /input/global-wheat-detection/test/' weights = 'weights/best.pt' weights800 = '.. /input/yolo800/best_yolov5x_fold0_800.pt' if not os.path.exists(weights): weights = '.. /input/yolov5pth/weightsbest_yolov5x_fold3.pt' i...
def clean_tweet(text): text = remove_URL(text) text = remove_HTML(text) text = remove_not_ASCII(text) text = text.lower() text = replace_abbrev(text) text = remove_mention(text) text = remove_number(text) text = remove_emoji(text) text = transcription_sad(text) text = transcription_smile(text) text = transcrip...
Natural Language Processing with Disaster Tweets
15,118,972
results = detect() test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.to_csv('submission.csv', index=False) test_df.head()<install_modules>
train["clean_text"] = train["text"].apply(clean_tweet) test["clean_text"] = test["text"].apply(clean_tweet) train["clean_tokens"] = train["clean_text"].apply(lambda x: word_tokenize(x)) test["clean_tokens"] = test["clean_text"].apply(lambda x: word_tokenize(x))
Natural Language Processing with Disaster Tweets
15,118,972
! pip install --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext".. /input/nvidiaapex/<install_modules>
skip_gram_model = Word2Vec(train['clean_tokens'],size=150,window=3,min_count=2,sg=1) skip_gram_model.train(train['clean_tokens'],total_examples=len(train['clean_tokens']),epochs=10) cbow_model = Word2Vec(train['clean_tokens'],size=150,window=3,min_count=2) cbow_model.train(train['clean_tokens'],total_examples=len(tr...
Natural Language Processing with Disaster Tweets
15,118,972
!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>
max_features=5000 count_vectorizer = CountVectorizer(max_features=max_features) sparce_matrix_train=count_vectorizer.fit_transform(train['clean_text']) sparce_matrix_test=count_vectorizer.fit_transform(train['clean_text']) def count_vector(data): count_vectorizer = CountVectorizer() vect = count_vectorizer.fit_trans...
Natural Language Processing with Disaster Tweets
15,118,972
look_at_on_kernel = 1<set_options>
metrics = pd.DataFrame(columns=['model' ,'vectoriser', 'f1 score', 'train accuracy','test accuracy'] )
Natural Language Processing with Disaster Tweets
15,118,972
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>
models=[ XGBClassifier(max_depth=6, n_estimators=1000), LogisticRegression(random_state=random_state), SVC(random_state=random_state), MultinomialNB() , DecisionTreeClassifier(random_state = random_state), KNeighborsClassifier() , RandomForestClassifier(random_state=random_state), ]
Natural Language Processing with Disaster Tweets
15,118,972
marking = pd.read_csv('.. /input/pure-box/cleanedTrainNoIndexOnLimit.csv' )<define_search_model>
for model in models: y = train.target x = X_train_count x_train, x_test, y_train, y_test = train_test_split(x,y, test_size = 0.3) fit_and_predict(model,x_train,x_test,y_train,y_test,'Count vector') x = X_train_tfidf x_train, x_test, y_train, y_test = train_test_split(x,y, test_size = 0.3) fit_and_predict(model,x_tra...
Natural Language Processing with Disaster Tweets
15,118,972
def get_train_transforms() : return A.Compose( [ A.RandomSizedCrop(min_max_height=(800, 800), height=1024, width=1024, p=0.5), A.OneOf([ A.HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit= 0.2, val_shift_limit=0.2, p=0.9), A.RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.2, p=0.9), ],p=0.9), A....
metrics = metrics.sort_values('f1 score',ascending=False )
Natural Language Processing with Disaster Tweets
15,118,972
warnings.filterwarnings("ignore") 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 = mo...
free_gpu_cache()
Natural Language Processing with Disaster Tweets
15,118,972
class TrainGlobalConfig: num_workers = 2 batch_size = 1 if apex_on: batch_size *= 2 n_epochs = 3 lr = 0.0001 folder = 'plabel_model' verbose = True verbose_step = 1 step_scheduler = False validation_scheduler = True SchedulerClass = torch.optim.lr_scheduler.ReduceLROnPlateau scheduler_params = dict( mode='min', factor...
from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow import keras from keras.models import Sequential from keras.layers import Dense, Embedding, LSTM,GRU, Dropout, Activation, Input, Flatten, Bidirectional, Conv1D, MaxPooling1D from ...
Natural Language Processing with Disaster Tweets
15,118,972
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}/{...
def train_lstm(x_train,x_test,y_train,y_test,vectorizer_name,vocab_size,input_length): epochs = 1 verbose = 1 batch_size = 32 embed_dim = 32 optimizer = optimizers.Adam(lr=0.002) model = Sequential() model.add(Embedding(vocab_size, embed_dim,input_length = input_length)) model.add(Dropout(0.2)) model.add(LSTM(32, drop...
Natural Language Processing with Disaster Tweets
15,118,972
dataset = DatasetRetriever( image_ids=np.array([path.split('/')[-1][:-4] for path in glob(f'{DATA_ROOT_PATH}/*.jpg')]), transforms=get_test_transforms() ) def collate_fn(batch): return tuple(zip(*batch)) data_loader = DataLoader( dataset, batch_size=1, shuffle=False, num_workers=0, drop_last=False, collate_fn=colla...
y = train['target'].values x_train, x_test, y_train, y_test = train_test_split(X_train_skip_gram,y, test_size = 0.3) train_lstm(x_train,x_test,y_train,y_test, 'skip gram vector',5329,150)
Natural Language Processing with Disaster Tweets
15,118,972
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=1024 net.class_net = HeadNet(config, num_outputs=config.num_classes, norm_kwargs=dict(eps=.001, momentum=.01)) checkpoint = torch.load(ch...
%reset -f
Natural Language Processing with Disaster Tweets
15,118,972
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...
!pip install GPUtil def free_gpu_cache() : print("Initial GPU Usage") gpu_usage() torch.cuda.empty_cache() cuda.select_device(0) cuda.close() cuda.select_device(0) for obj in gc.get_objects() : if torch.is_tensor(obj): del obj gc.collect() print("GPU Usage after emptying the cache") gpu_usage() free_gpu_cache()
Natural Language Processing with Disaster Tweets
15,118,972
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]))<categorify>
import re import torch from transformers import ElectraTokenizer, ElectraForSequenceClassification,AdamW import torch from sklearn.metrics import classification_report import random import time import datetime import numpy as np import pandas as pd from transformers import get_linear_schedule_with_warmup from torch.uti...
Natural Language Processing with Disaster Tweets
15,118,972
def make_tta_predictions(images, score_threshold=0.01): 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...
if torch.cuda.is_available() : device = torch.device("cuda") print('We will use the GPU:', torch.cuda.get_device_name(0)) else: print('No GPU available, using the CPU instead.') device = torch.device("cpu" )
Natural Language Processing with Disaster Tweets
15,118,972
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 )<categorify>
train = pd.read_csv(".. /input/nlp-getting-started/train.csv") test = pd.read_csv(".. /input/nlp-getting-started/test.csv") df_train= train df_test= test
Natural Language Processing with Disaster Tweets
15,118,972
results_plabel = [] for images, image_ids in data_loader: predictions = make_tta_predictions(images) for i, image in enumerate(images): image_id = image_ids[i] image_ = cv2.imread(f'{DATA_ROOT_PATH}/{image_id}.jpg', cv2.IMREAD_COLOR) h,w,_ = np.shape(image_) boxes, scores, labels = run_wbf(predictions, image_index=i...
def preprocess(text): text=text.lower() text = re.sub(r'https?:\/\/.*[\r ]*', '', text) text = re.sub(r'http?:\/\/.*[\r ]*', '', text) text=text.replace(r'&amp;?',r'and') text=text.replace(r'&lt;',r'<') text=text.replace(r'&gt;',r'>') text = re.sub(r"(?:\@)\w+", '', text) text=text.encode("ascii",errors="ignore" ...
Natural Language Processing with Disaster Tweets
15,118,972
results_df = pd.DataFrame(results_plabel, columns=['image_id', 'width','height','source','x','y','w','h']) results_df.head()<feature_engineering>
df_train=df_train[["text","target"]]
Natural Language Processing with Disaster Tweets
15,118,972
results_df['image_id'] = results_df['image_id'].apply(lambda x: DATA_ROOT_PATH+'/'+ x+'.jpg' )<feature_engineering>
texts = df_train.text.values labels = df_train.target.values
Natural Language Processing with Disaster Tweets
15,118,972
TRAIN_ROOT_PATH = '.. /input/global-wheat-detection/train' marking['image_id'] = marking['image_id'].apply(lambda x: TRAIN_ROOT_PATH+'/'+ x+'.jpg' )<concatenate>
torch.cuda.empty_cache() tokenizer = ElectraTokenizer.from_pretrained('google/electra-base-discriminator') model = ElectraForSequenceClassification.from_pretrained('google/electra-base-discriminator',num_labels=2) model.cuda()
Natural Language Processing with Disaster Tweets
15,118,972
if len(os.listdir('.. /input/global-wheat-detection/test/')) <11: train_data_plabel = results_df else: train_data_plabel = pd.concat([results_df, marking], axis=0 )<feature_engineering>
indices=tokenizer.batch_encode_plus(texts,max_length=64,add_special_tokens=True, return_attention_mask=True,pad_to_max_length=True,truncation=True) input_ids=indices["input_ids"] attention_masks=indices["attention_mask"]
Natural Language Processing with Disaster Tweets
15,118,972
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) df_folds = train_data_plabel[['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[:, 'strati...
train_inputs, validation_inputs, train_labels, validation_labels = train_test_split(input_ids, labels, random_state=42, test_size=0.2) train_masks, validation_masks, _, _ = train_test_split(attention_masks, labels, random_state=42, test_size=0.2 )
Natural Language Processing with Disaster Tweets
15,118,972
TRAIN_ROOT_PATH = '.. /input/global-wheat-detection/train' class DatasetRetriever(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 ...
train_inputs = torch.tensor(train_inputs) validation_inputs = torch.tensor(validation_inputs) train_labels = torch.tensor(train_labels, dtype=torch.long) validation_labels = torch.tensor(validation_labels, dtype=torch.long) train_masks = torch.tensor(train_masks, dtype=torch.long) validation_masks = torch.tensor(v...
Natural Language Processing with Disaster Tweets
15,118,972
fold_number = 0 train_dataset = DatasetRetriever( image_ids=df_folds[df_folds['fold'] != fold_number].index.values, marking=train_data_plabel, transforms=get_train_transforms() , test=False, ) validation_dataset = DatasetRetriever( image_ids=df_folds[df_folds['fold'] == fold_number].index.values, marking=train_data...
batch_size = 32 train_data = TensorDataset(train_inputs, train_masks, train_labels) train_sampler = RandomSampler(train_data) train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=batch_size) validation_data = TensorDataset(validation_inputs, validation_masks, validation_labels) validation_sam...
Natural Language Processing with Disaster Tweets
15,118,972
def collate_fn(batch): return tuple(zip(*batch)) 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=TrainGlobalConfi...
optimizer = AdamW(model.parameters() , lr = 6e-6, eps = 1e-8 ) epochs = 5 total_steps = len(train_dataloader)* epochs scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps = 0, num_training_steps = total_steps )
Natural Language Processing with Disaster Tweets
15,118,972
def get_net() : config = get_efficientdet_config('tf_efficientdet_d5') net = EfficientDet(config, pretrained_backbone=False) config.num_classes = 1 config.image_size = 1024 net.class_net = HeadNet(config, num_outputs=config.num_classes, norm_kwargs=dict(eps=.001, momentum=.01)) checkpoint = torch.load('.. /input/weig...
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
15,118,972
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>
seed_val = 42 random.seed(seed_val) np.random.seed(seed_val) torch.manual_seed(seed_val) torch.cuda.manual_seed_all(seed_val) loss_values = [] for epoch_i in range(0, epochs): print("") print('======== Epoch {:} / {:} ========'.format(epoch_i + 1, epochs)) print('Training...') t0 = time.time() total_loss = 0 mode...
Natural Language Processing with Disaster Tweets
15,118,972
if len(os.listdir('.. /input/global-wheat-detection/test/')) <1: pass else: run_training()<set_options>
print("") print("Running Validation...") t0 = time.time() model.eval() preds=[] true=[] eval_loss, eval_accuracy = 0, 0 nb_eval_steps, nb_eval_examples = 0, 0 for batch in validation_dataloader: batch = tuple(t.to(device)for t in batch) b_input_ids, b_input_mask, b_labels = batch with torch.no_grad() : outputs = mod...
Natural Language Processing with Disaster Tweets
15,118,972
time.sleep(1) def memory_cleanup() : for obj in gc.get_objects() : if torch.is_tensor(obj): del obj gc.collect() torch.cuda.empty_cache() memory_cleanup()<categorify>
report = {} report['model'] = 'Electra' report['test accuracy'] = 0.82 metrics = metrics.append(report,ignore_index=True )
Natural Language Processing with Disaster Tweets
15,118,972
results_plabel = [] for images, image_ids in data_loader: predictions = make_tta_predictions(images) for i, image in enumerate(images): image_id = image_ids[i] image_ = cv2.imread(f'{DATA_ROOT_PATH}/{image_id}.jpg', cv2.IMREAD_COLOR) h,w,_ = np.shape(image_) boxes, scores, labels = run_wbf(predictions, image_index=i...
flat_predictions = [item for sublist in preds for item in sublist] flat_predictions = np.argmax(flat_predictions, axis=1 ).flatten() flat_true_labels = [item for sublist in true for item in sublist]
Natural Language Processing with Disaster Tweets
15,118,972
results_df = pd.DataFrame(results_plabel, columns=['image_id', 'width','height','source','x','y','w','h']) results_df.head()<feature_engineering>
comments1 = df_test.text.values indices1=tokenizer.batch_encode_plus(comments1,max_length=128,add_special_tokens=True, return_attention_mask=True,pad_to_max_length=True,truncation=True) input_ids1=indices1["input_ids"] attention_masks1=indices1["attention_mask"] prediction_inputs1= torch.tensor(input_ids1) prediction...
Natural Language Processing with Disaster Tweets
15,118,972
results_df['image_id'] = results_df['image_id'].apply(lambda x: DATA_ROOT_PATH+'/'+ x+'.jpg' )<define_variables>
print('Predicting labels for {:,} test sentences...'.format(len(prediction_inputs1))) model.eval() predictions = [] for batch in prediction_dataloader1: batch = tuple(t.to(device)for t in batch) b_input_ids1, b_input_mask1 = batch with torch.no_grad() : outputs1 = model(b_input_ids1, token_type_ids=None, attention_ma...
Natural Language Processing with Disaster Tweets
15,118,972
TRAIN_ROOT_PATH = '.. /input/global-wheat-detection/train' <concatenate>
sample_sub=pd.read_csv('.. /input/nlp-getting-started/sample_submission.csv') submit=pd.DataFrame({'id':sample_sub['id'].values.tolist() ,'target':flat_predictions} )
Natural Language Processing with Disaster Tweets
15,118,972
<feature_engineering><EOS>
df_leak = pd.read_csv('/kaggle/input/disasters-on-social-media/socialmedia-disaster-tweets-DFE.csv', encoding ='ISO-8859-1')[['choose_one', 'text']] df_leak['target'] =(df_leak['choose_one'] == 'Relevant' ).astype(np.int8) df_leak['id'] = df_leak.index.astype(np.int16) df_leak.drop(columns=['choose_one', 'text'], inp...
Natural Language Processing with Disaster Tweets
14,922,728
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<create_dataframe>
import numpy as np import torch from torch.utils.data import DataLoader, Dataset, TensorDataset import sys import torch.nn as nn import torch.nn.functional as F from torch.utils import data import torch.optim as optim import seaborn as sns from collections import defaultdict import time import pandas as pd import matpl...
Natural Language Processing with Disaster Tweets
14,922,728
fold_number = 0 train_dataset = DatasetRetriever( image_ids=df_folds[df_folds['fold'] != fold_number].index.values, marking=train_data_plabel, transforms=get_train_transforms() , test=False, ) validation_dataset = DatasetRetriever( image_ids=df_folds[df_folds['fold'] == fold_number].index.values, marking=train_data...
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') print(device )
Natural Language Processing with Disaster Tweets
14,922,728
def collate_fn(batch): return tuple(zip(*batch)) 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=TrainGlobalConfi...
train_csv = pd.read_csv('/kaggle/input/nlp-getting-started/train.csv', keep_default_na = False) train_csv = train_csv.sample(frac=1 ).reset_index(drop=True) ninetyfive_percent = round(0.90*(len(train_csv))) train_data = train_csv.iloc[:ninetyfive_percent] valid_data = train_csv.iloc[ninetyfive_percent:] print('Num...
Natural Language Processing with Disaster Tweets
14,922,728
def get_net() : config = get_efficientdet_config('tf_efficientdet_d5') net = EfficientDet(config, pretrained_backbone=False) config.num_classes = 1 config.image_size=1024 net.class_net = HeadNet(config, num_outputs=config.num_classes, norm_kwargs=dict(eps=.001, momentum=.01)) checkpoint = torch.load('plabel_model/las...
test_csv = pd.read_csv('/kaggle/input/nlp-getting-started/test.csv', keep_default_na = False) test_dataset = mydataset(test_csv , name = 'test') test_dataloader = data.DataLoader(test_dataset, shuffle= False, batch_size = 1, num_workers=16,pin_memory=True )
Natural Language Processing with Disaster Tweets
14,922,728
if len(os.listdir('.. /input/global-wheat-detection/test/')) <1: pass else: run_training()<set_options>
def train(model, data_loader, valid_loader, criterion, optimizer, lr_scheduler, modelpath, device, epochs): model.train() train_loss= [] valid_loss = [] valid_acc = [] for epoch in range(epochs): avg_loss = 0.0 for batch_num,(tweet, input_id, attention_masks, target)in enumerate(data_loader): input_ids, attention_masks...
Natural Language Processing with Disaster Tweets
14,922,728
time.sleep(1) def memory_cleanup() : for obj in gc.get_objects() : if torch.is_tensor(obj): del obj gc.collect() torch.cuda.empty_cache() memory_cleanup()<categorify>
modelname = 'BERT' modelpath = 'saved_checkpoint_'+modelname train_loss, valid_loss, valid_acc = train(model, train_dataloader, validation_dataloader, criterion, optimizer, lr_scheduler, modelpath, device, epochs = num_Epochs )
Natural Language Processing with Disaster Tweets
14,922,728
def get_valid_transforms() : return A.Compose([ A.Resize(height=1024, width=1024, p=1.0), ToTensorV2(p=1.0), ], p=1.0 )<data_type_conversions>
def predict(model, test_loader, device): model.eval() target = [] for batch_num,(captions, input_id, attention_masks)in enumerate(test_loader): input_ids, attention_masks = input_id.to(device), attention_masks.to(device) output_dictionary = model(input_ids, token_type_ids=None, attention_mask=attention_masks, return_d...
Natural Language Processing with Disaster Tweets
14,922,728
<load_pretrained><EOS>
predict(model, test_dataloader, device )
Natural Language Processing with Disaster Tweets
14,958,171
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<categorify>
!pip install pytorch-pretrained-bert pytorch-nlp
Natural Language Processing with Disaster Tweets
14,958,171
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...
warnings.filterwarnings('ignore')
Natural Language Processing with Disaster Tweets
14,958,171
def process_det(index, det, score_threshold=0.25): boxes = det[index].detach().cpu().numpy() [:,:4] scores = det[index].detach().cpu().numpy() [:,4] boxes[:, 2] = boxes[:, 2] + boxes[:, 0] boxes[:, 3] = boxes[:, 3] + boxes[:, 1] boxes =(boxes ).clip(min=0, max=1023 ).astype(int) indexes = np.where(scores>score_thresho...
nltk.download('punkt' )
Natural Language Processing with Disaster Tweets
14,958,171
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]))<categorify>
pd.options.display.max_colwidth = 100 seed_val=42 tf.random.set_seed(seed_val) 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,958,171
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...
device = torch.device("cuda" if torch.cuda.is_available() else "cpu" )
Natural Language Processing with Disaster Tweets
14,958,171
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 )<categorify>
train_df = pd.read_csv('/kaggle/input/nlp-getting-started/train.csv') train_df.head()
Natural Language Processing with Disaster Tweets
14,958,171
results = [] for images, image_ids in data_loader: predictions = make_tta_predictions(images) for i, image in enumerate(images): boxes, scores, labels = run_wbf(predictions, image_index=i) boxes = boxes.round().astype(np.int32 ).clip(min=0, max=1023) image_id = image_ids[i] boxes[:, 2] = boxes[:, 2] - boxes[:, 0] bo...
print(train_df.info()) print("
Natural Language Processing with Disaster Tweets
14,958,171
test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.to_csv('submission.csv', index=False) test_df.head()<install_modules>
train_df['target'].value_counts(normalize=True )
Natural Language Processing with Disaster Tweets
14,958,171
!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>
test_df = pd.read_csv('/kaggle/input/nlp-getting-started/test.csv') test_df.head()
Natural Language Processing with Disaster Tweets
14,958,171
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 )<define_variables>
train_df[~train_df['keyword'].isnull() ][['keyword', 'text']]
Natural Language Processing with Disaster Tweets
14,958,171
TRAIN_DATA_PATH = '.. /input/global-wheat-detection/train/' TRAIN_CSV_PATH = '.. /input/global-wheat-detection/train.csv' TEST_DATA_PATH = '.. /input/global-wheat-detection/test/' if len(os.listdir('.. /input/global-wheat-detection/test/')) >11: PL_OPT = True else: PL_OPT = False warmup_opt = True warmup_epoch = 1 PL_l...
len(train_df['location'].unique() )
Natural Language Processing with Disaster Tweets
14,958,171
def get_train_transforms() : return A.Compose( [ A.RandomSizedCrop(min_max_height=(800, 800), height=1024, width=1024, p=0.5), A.OneOf([ A.HueSaturationValue(hue_shift_limit=0.2, sat_shift_limit= 0.2, val_shift_limit=0.2, p=0.9), A.RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.2, p=0.9), ],p=0.9), A....
train_df.drop(columns=['keyword', 'location'], inplace=True )
Natural Language Processing with Disaster Tweets
14,958,171
marking = pd.read_csv(TRAIN_CSV_PATH) 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 )<data_type_conversions>
spacy_en = spacy.load('en_core_web_sm', disable=['parser','ner']) bert_tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True )
Natural Language Processing with Disaster Tweets
14,958,171
class DatasetT(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'{TEST_DATA_PATH}/{image_id}.jpg', cv2.IMREAD_COLOR) image = cv2.cvtColor(image, cv...
abbreviations = { "$" : " dollar ", "€" : " euro ", "4ao" : "for adults only", "a.m" : "before midday", "a3" : "anytime anywhere anyplace", "aamof" : "as a matter of fact", "acct" : "account", "adih" : "another day in hell", "afaic" : "as far as i am concerned", "afaict" : "as far as i can tell", "afaik" : "as far as i...
Natural Language Processing with Disaster Tweets
14,958,171
class DatasetRetriever(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 = self.image_ids[index] if self.test or random.random() > 0...
special_characters = { "Surṳ":"Suruc", "JapÌ_n":"Japan" , "\x89ÛÏWhen":"When", "å£3million":"3 million", "fromåÊwounds":"from wounds", "m̼sica":"music", "donå«t":"do not", "didn`t":"did not", "i\x89Ûªm":"I am", "I\x89Ûªm":"I am", "it\x89Ûªs":"it is", "It\x89Ûªs":"It is", "i\x89Ûªd":"I would", "I\x89Ûªd":"I would", "...
Natural Language Processing with Disaster Tweets
14,958,171
def load_test_net(checkpoint_path): config = get_efficientdet_config('tf_efficientdet_d5') 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 = torc...
expand_contractions = { "I'm":"I am", "I'M":"I am", "i'm":"I am", "i'M":"I am", "i'd":"I would", "I'd":"I would", "i'll":"I will", "I'll":"I will", "i've":"I have", "I've":"I have", "you're":"you are", "You're":"You are", "you'd":"you would", "You'd":"You would", "you've":"you have", "You've":"You have", "you'll":"you ...
Natural Language Processing with Disaster Tweets
14,958,171
def load_train_net(checkpoint_path): config = get_efficientdet_config('tf_efficientdet_d5') 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 = t...
informal_abbreviations = { "b/c":"because", "w/e":"whatever", "w/out":"without", "w/o":"without", "w/":"with ", "<3":"love", "c/o":"care of", "p/u":"pick up", " ":" " }
Natural Language Processing with Disaster Tweets
14,958,171
class BaseWheatTTA: image_size = img_size 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_augmen...
def clean_text(text): cleaned_text = text.lower() cleaned_text = re.sub(r'https?:\S+|www\.\S+', '', cleaned_text) cleaned_text = re.sub(r'<.*?>', '', cleaned_text) cleaned_text = ''.join(ch for ch in cleaned_text if ch in string.printable) cleaned_text = ' '.join(abbreviations[word] if word in abbreviations else wor...
Natural Language Processing with Disaster Tweets
14,958,171
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>
def add_special_token(text): cleaned_text = "[CLS] " + text + " [SEP]" return cleaned_text
Natural Language Processing with Disaster Tweets
14,958,171
def make_tta_predictions(images, models, score_threshold): with torch.no_grad() : images = torch.stack(images ).float().cuda() assert images.shape[0] == 1 predictions = [] boxes_All = [] scores_All = [] for tta_transform in tta_transforms: for net in models: det = net(tta_transform.batch_augment(images.clone()), torch....
train_df['cleaned_text'] = np.vectorize(clean_text )(train_df['text']) train_df['cleaned_text'] = np.vectorize(add_special_token )(train_df['cleaned_text'] )
Natural Language Processing with Disaster Tweets
14,958,171
class TrainGlobalConfig: num_workers = 2 batch_size = PL_batchsize n_epochs = PL_epoch lr = PL_lr folder = 'plabel_model' verbose = True verbose_step = 1 step_scheduler = False validation_scheduler = True if PL_lr_sche == 'cos': SchedulerClass = torch.optim.lr_scheduler.CosineAnnealingLR scheduler_params = dict( T_max...
MAX_LEN = 128 BATCH_SZ=32
Natural Language Processing with Disaster Tweets
14,958,171
class WarmUp(_LRScheduler): def __init__(self, optimizer, total_iters, last_epoch=-1): self.total_iters = total_iters super(WarmUp, self ).__init__(optimizer, last_epoch) def get_lr(self): return [base_lr * self.last_epoch /(self.total_iters + 1e-8)for base_lr in self.base_lrs]<init_hyperparams>
def generate_input_attention_mask(tweets): tokenized_tweets = [bert_tokenizer.tokenize(tweet)for tweet in tweets] input_ids = [bert_tokenizer.convert_tokens_to_ids(x)for x in tokenized_tweets] input_ids = pad_sequences(input_ids, maxlen=MAX_LEN, dtype="long", truncating="post", padding="post") attention_masks = [] for...
Natural Language Processing with Disaster Tweets
14,958,171
warnings.filterwarnings("ignore") class Fitter: def __init__(self, model, device, config, train_loader_length): 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 = ...
train_input_ids, train_attention_masks = generate_input_attention_mask(train_df['cleaned_text'] )
Natural Language Processing with Disaster Tweets
14,958,171
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<categorify>
def recall(y_true, y_pred): true_positives = K.sum(K.round(y_true * y_pred)) possible_positives = K.sum(y_true) recall = true_positives /(possible_positives + K.epsilon()) return recall def precision(y_true, y_pred): true_positives = K.sum(K.round(y_true * y_pred)) predicted_positives = K.sum(K.round(y_pred)) precisi...
Natural Language Processing with Disaster Tweets
14,958,171
if PL_OPT: test_models = [] for p in path2: test_models.append(load_test_net(p)) results_plabel = [] for images, image_ids in data_loader: predictions = make_tta_predictions(images, test_models, PL_thr) for i, image in enumerate(images): assert i == 0 image_id = image_ids[i] image_ = cv2.imread(f'{TEST_DATA_PATH}/{ima...
train_inputs, validation_inputs, train_labels, validation_labels = train_test_split(train_input_ids, train_df['target'], train_size=0.8, random_state=100) train_masks, validation_masks, _, _ = train_test_split(train_attention_masks, train_df['target'], train_size=0.8, random_state=100) train_inputs = torch.tensor(tra...
Natural Language Processing with Disaster Tweets
14,958,171
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>
train_data = TensorDataset(train_inputs, train_masks, train_labels) train_sampler = RandomSampler(train_data) train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=BATCH_SZ) validation_data = TensorDataset(validation_inputs, validation_masks, validation_labels) validation_sampler = SequentialS...
Natural Language Processing with Disaster Tweets
14,958,171
if PL_OPT: final_models = [ load_test_net(f'plabel_model/last-checkpoint1.bin') ] else: final_models = [] for p in path1: final_models.append(load_test_net(p))<predict_on_test>
model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2) model.cuda()
Natural Language Processing with Disaster Tweets
14,958,171
results = [] for images, image_ids in data_loader: predictions = make_tta_predictions(images, final_models, OOF_thr) for i, image in enumerate(images): assert i == 0 boxes, scores, labels = run_wbf(predictions, img_size, WBF_iou_thr, WBF_skip_thr) if img_size == 512: boxes =(boxes*2 ).astype(np.int32 ).clip(min=0, ma...
param_optimizer = list(model.named_parameters()) no_decay = ['bias', 'gamma', 'beta'] optimizer_grouped_parameters = [ {'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay_rate': 0.01}, {'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_de...
Natural Language Processing with Disaster Tweets
14,958,171
test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.to_csv('submission.csv', index=False) test_df.head(10 )<import_modules>
train_loss_set = [] epochs = 4 for _ in range(epochs): model.train() tr_loss = 0 nb_tr_examples, nb_tr_steps = 0, 0 for step, batch in enumerate(train_dataloader): batch = tuple(t.to(device)for t in batch) b_input_ids, b_input_mask, b_labels = batch optimizer.zero_grad() loss = model(b_input_ids, token_type_ids=None, ...
Natural Language Processing with Disaster Tweets
14,958,171
from object_detection_utils import show_Nimages<set_options>
model.eval() eval_accuracy = 0 nb_eval_steps = 0 for batch in validation_dataloader: batch = tuple(t.to(device)for t in batch) b_input_ids, b_input_mask, b_labels = batch with torch.no_grad() : logits = model(b_input_ids, token_type_ids=None, attention_mask=b_input_mask) logits = logits.detach().cpu().numpy() label_i...
Natural Language Processing with Disaster Tweets
14,958,171
def seed_everything(seed=42): 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 <load_pretrained>
test_df.drop(columns=['keyword', 'location'], inplace=True) test_df['cleaned_text'] = np.vectorize(clean_text )(test_df['text']) test_df['cleaned_text'] = np.vectorize(add_special_token )(test_df['cleaned_text']) test_input_ids, test_attention_masks = generate_input_attention_mask(test_df['cleaned_text'] )
Natural Language Processing with Disaster Tweets
14,958,171
BEST_PATHS = ["/kaggle/input/best-models-frcnn/F0_68_nofinetune_clear_best.bin", "/kaggle/input/best-models-frcnn/F1_68_nofinetune_clear_best.bin", "/kaggle/input/5fold-68-clear/F2_68_nofinetune_clear_best.bin", "/kaggle/input/5fold-68-clear/F3_68_nofinetune_clear_best.bin"] for BEST_PATH in BEST_PATHS: ckp = torch.loa...
test_inputs = torch.tensor(test_input_ids, dtype=torch.long) test_attention = torch.tensor(test_attention_masks, dtype=torch.long) test_data = TensorDataset(test_inputs, test_attention) test_sampler = SequentialSampler(test_data) test_dataloader = DataLoader(test_data, sampler=test_sampler, batch_size = BATCH_SZ )
Natural Language Processing with Disaster Tweets