kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
14,958,171
SEED=42 seed_everything(SEED) APEX = False ACCUM = 2 SWAP_VALID_AND_TRAIN = False N_VIZ = 10 USE_NMS = False SCORE_THRESHOLD = 0.65 NMS_IOU_THRESHOLD = 0.5 IMG_SIZE = 1024 WBF_IOU, WBF_SKIP_BOX = 0.44, 0.38 PP_SHRINK = [-1,0] WBF_SCORE_THRESHOLD = 0.265 USE_BOUNDS_FILTER = True LOWER_BOUND, UPPER_BOUND = 70, 175000 ...
model.eval() predictions = [] for batch in test_dataloader: batch = tuple(t.to(device)for t in batch) b_input_ids, b_mask = batch with torch.no_grad() : logits = model(b_input_ids, token_type_ids=None, attention_mask = b_mask) logits = logits.detach().cpu().numpy() predictions.append(logits) test_predictions = [item...
Natural Language Processing with Disaster Tweets
14,958,171
<import_modules><EOS>
submission = pd.DataFrame({'id':test_df['id'], 'target':test_predictions}) submission.to_csv('./submission.csv', index=False )
Natural Language Processing with Disaster Tweets
14,910,610
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<set_options>
import numpy as np import pandas as pd import tensorflow as tf import csv import re
Natural Language Processing with Disaster Tweets
14,910,610
%%writefile./modeling/wheat_detector.py class WheatDetector(nn.Module): def __init__(self, cfg, **kwargs): super(WheatDetector, self ).__init__() self.backbone = resnest_fpn_backbone(pretrained=False) self.base = FasterRCNN(self.backbone, num_classes=cfg.MODEL.NUM_CLASSES, **kwargs) def forward(self, images, targets=...
def convert_test_attributes_to_onehot(df, value_list): one_hots = np.zeros(( len(df), len(value_list))) for index, row in df.iterrows() : if row['keyword'] != '': try: one_hots[index, value_list.index(row['keyword'])] = 1 except ValueError: continue if row['keyword'] != '': try: one_hots[index, value_list.index(row['l...
Natural Language Processing with Disaster Tweets
14,910,610
sys.path.insert(0, "./external/wbf") warnings.filterwarnings("ignore") 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 TTAReduceSaturation(BaseWh...
def build_model(lstm_shape, dense_shape): dropout = 0.8 dense_input = tf.keras.layers.Input(shape=(dense_shape)) dense1 = tf.keras.layers.Dense(50 )(dense_input) lstm_input = tf.keras.layers.Input(shape=(lstm_shape)) lstm1 = tf.keras.layers.GaussianNoise(0.075 )(lstm_input) lstm2 = tf.keras.layers.LSTM(units=500, ret...
Natural Language Processing with Disaster Tweets
14,910,610
class Tester: def __init__(self, models, device, cfg, test_loader, n_viz=N_VIZ): self.config = cfg self.test_loader = test_loader self.base_dir = f'{self.config.OUTPUT_DIR}' if not os.path.exists(self.base_dir): os.makedirs(self.base_dir) self.log_path = f'{self.base_dir}/log.txt' self.score_threshold = SCORE_THRESHOL...
MAX_TWEET_LENGTH = 280 VECTORS_PER_WORD = 50 BATCH_SIZE = 256 NUM_EPOCHS = 40
Natural Language Processing with Disaster Tweets
14,910,610
cfg['OUTPUT_DIR'] = "/kaggle/working/" cfg['DATASETS']['ROOT_DIR'] = "/kaggle/input/global-wheat-detection" cfg['TEST']['IMS_PER_BATCH'] = 1 cfg['TEST']['WEIGHT'] = BEST_PATHS cfg<load_from_csv>
print('Loading test and training data') test_data = pd.read_csv('/kaggle/input/nlp-getting-started/test.csv') train_data = pd.read_csv('/kaggle/input/nlp-getting-started/train.csv') print('Loading GloVe file') glove_data = pd.read_csv('/kaggle/input/glove50d/glove.6B.50d.txt', sep=' ', index_col=0, header = None, q...
Natural Language Processing with Disaster Tweets
14,910,610
<categorify><EOS>
model = build_model([MAX_TWEET_LENGTH, VECTORS_PER_WORD], len(df_one_hot_attributes.columns)) model.summary() checkpoint_save = tf.keras.callbacks.ModelCheckpoint('saved_model.h5', save_best_only=True, monitor='val_acc', mode='min') model.fit(x=[df_one_hot_attributes, vectorized_training_data], y=train_data['target'],...
Natural Language Processing with Disaster Tweets
13,338,682
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<split>
import tensorflow as tf from transformers import BertTokenizer, TFBertModel, AdamWeightDecay from tensorflow import keras import matplotlib.pyplot as plt import string import re import numpy as np import pandas as pd import emoji import os from sklearn.metrics import accuracy_score from skopt.utils import use_named_arg...
Natural Language Processing with Disaster Tweets
13,338,682
marking_list, train_ids_list, valid_ids_list = [], [], [] for ii in range(len(BEST_PATHS)) : print(' ** weights -- cfg.DATASETS.VALID_FOLD = ii marking, train_ids0, valid_ids0 = split_dataset(cfg) if SWAP_VALID_AND_TRAIN: print('swap!!') valid_ids, train_ids =train_ids0, valid_ids0 else: train_ids, valid_ids =train_i...
train = pd.read_csv('.. /input/nlp-getting-started/train.csv', header = 0, encoding="utf8") test = pd.read_csv('.. /input/nlp-getting-started/test.csv', header = 0, encoding="utf8") train = train.drop(columns=['id', 'keyword', 'location']) test = test.drop(columns=['id', 'keyword', 'location']) train = train.drop_d...
Natural Language Processing with Disaster Tweets
13,338,682
<set_options>
def remove_tweet_object(tweet): tweet = re.sub(r"https?://\S+|www\.\S+", " ", tweet) tweet = re.sub(r" tweet = re.sub(r"@\w+", " ", tweet) tweet = emoji.get_emoji_regexp().sub(" ", tweet) return tweet def text_filter(tweet): tweet = tweet.lower() tweet = re.sub(r"’", "'", tweet) tweet = remove_tweet_object(tweet) ...
Natural Language Processing with Disaster Tweets
13,338,682
%%writefile./data/transforms/build.py def get_train_transforms(cfg): return A.Compose( [ A.Resize(1024, 1024, p=1.0), A.RandomSizedCrop(min_max_height=cfg.INPUT.RSC_MIN_MAX_HEIGHT, height=cfg.INPUT.RSC_HEIGHT, width=cfg.INPUT.RSC_WIDTH, p=cfg.INPUT.RSC_PROB), A.OneOf([ A.HueSaturationValue(hue_shift_limit=cfg.INPUT.HS...
X_train, X_val, y_train, y_val = train_test_split(train.text, train.target, test_size=0.2, random_state=42 )
Natural Language Processing with Disaster Tweets
13,338,682
warnings.filterwarnings("ignore") def build_dataset(cfg, marking,train_ids, valid_ids): train_dataset = train_wheat( root = cfg.DATASETS.ROOT_DIR, image_ids=train_ids, marking=marking, transforms=build_transforms(cfg, is_train=True), test=False, ) validation_dataset = train_wheat( root=cfg.DATASETS.ROOT_DIR, image...
name_bert = "bert-base-uncased" tokenizer = BertTokenizer.from_pretrained(name_bert, do_lower_case=True) bert_model = TFBertModel.from_pretrained(name_bert, output_hidden_states=True, trainable=True) bert_w = bert_model.get_weights()
Natural Language Processing with Disaster Tweets
13,338,682
class Fitter: def __init__(self, model, device, cfg, train_loader, val_loader, logger, mixed_precision=APEX, accum=ACCUM): self.config = cfg self.epoch = 0 self.train_loader = train_loader self.val_loader = val_loader self.base_dir = f'{self.config.OUTPUT_DIR}' if not os.path.exists(self.base_dir): os.makedirs(self.bas...
combined = pd.concat([X_train, X_val, test.text], axis=0) combined = tokenizer(combined.values.tolist() , padding=True, truncation=True, return_tensors='tf') train_input =(combined["input_ids"][:len(X_train)], combined["attention_mask"][:len(X_train)], combined["token_type_ids"][:len(X_train)]) val_input =(combined[...
Natural Language Processing with Disaster Tweets
13,338,682
cfg.defrost() cfg['DATASETS']['ROOT_DIR'] = NEW_INPUT_PATH cfg.INPUT.HSV_H = HSV_H cfg.INPUT.HSV_S = HSV_S cfg.INPUT.HSV_V = HSV_V cfg.INPUT.BC_B = BC_B cfg.INPUT.BC_C = BC_C cfg.INPUT.COTOUT_NUM_HOLES=0 cfg.SOLVER.BASE_LR = BASE_LR cfg.SOLVER.BIAS_LR_FACTOR = BIAS_LR_FACTOR cfg.SOLVER.MOMENTUM=MOMENTUM cfg.SOLVER.WARM...
bert_model.set_weights(bert_w) optimizer = AdamWeightDecay(learning_rate=3e-5, weight_decay_rate=0.01, exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"]) loss = keras.losses.BinaryCrossentropy(from_logits=False, label_smoothing=0.0) input_word_ids = keras.layers.Input(shape=(train_input[0].shape[1],), dt...
Natural Language Processing with Disaster Tweets
13,338,682
fitters=[] for ii,path in enumerate(cfg['TEST']['WEIGHT']): cfg['OUTPUT_DIR'] = OUTPUT_DIRS[ii] checkpoint = torch.load(path) cfg.SOLVER.MAX_EPOCHS = checkpoint['epoch']+PSEUDO_EPOCHS+1 if n_test <11: cfg.SOLVER.MAX_EPOCHS = checkpoint['epoch']+PSEUDO_EPOCHS_COMMIT+1 print('epochs = %d+%d+%d'%(checkpoint['epoch'],PSEU...
model_bert_enc = keras.models.Model(inputs=[input_word_ids, input_mask, segment_ids], outputs=relu) train_text_vect = model_bert_enc.predict(train_input) val_text_vect = model_bert_enc.predict(val_input) test_text_vect = model_bert_enc.predict(test_input) print("Done" )
Natural Language Processing with Disaster Tweets
13,338,682
best_paths = [] for ii in range(len(OUTPUT_DIRS)) : if os.path.exists(OUTPUT_DIRS[ii]+'best-checkpoint.bin'): best_path = OUTPUT_DIRS[ii]+'best-checkpoint.bin' elif os.path.exists(OUTPUT_DIRS[ii]+'last-checkpoint.bin'): best_path = OUTPUT_DIRS[ii]+'last-checkpoint.bin' else: best_path = BEST_PATHS[ii] best_paths.append...
space = [Real(1, 1e3, prior="log-uniform", name="C_svm", transform="identity"), Real(1, 1e3, prior="log-uniform", name="C_lr", transform="identity"), Categorical(['hinge', 'squared_hinge'], name="loss_svm", transform="identity"), Categorical(['l1', 'l2', 'elasticnet'], name="penalty_sgd", transform="identity"), Categor...
Natural Language Processing with Disaster Tweets
13,338,682
if True: cfg['OUTPUT_DIR'] = "/kaggle/working/" cfg['DATASETS']['ROOT_DIR'] = "/kaggle/input/global-wheat-detection" cfg['TEST']['WEIGHT'] = best_paths cfg['TEST']['IMS_PER_BATCH'] = 1 print(cfg) test_loader = make_test_data_loader(cfg) tester = Tester(models=models, device=device, cfg=cfg, test_loader=test_loader, n...
estimators = [ ('1', make_pipeline(MinMaxScaler() , LinearSVC(C=res.x[0], loss=res.x[2] ,random_state=42))), ('2', make_pipeline(MinMaxScaler() , GaussianNB())) , ('3', make_pipeline(MinMaxScaler() , SGDClassifier(penalty=res.x[3], loss=res.x[4],random_state=42))), ] clf = StackingClassifier(estimators=estimators, f...
Natural Language Processing with Disaster Tweets
13,338,682
<set_options><EOS>
df_submission = pd.read_csv('.. /input/nlp-getting-started/sample_submission.csv', index_col=0 ).fillna('') df_submission['target'] = clf.predict(test_text_vect) df_submission.to_csv('submission.csv') df_submission
Natural Language Processing with Disaster Tweets
14,011,004
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<load_from_csv>
for dirname, _, filenames in os.walk('/kaggle/input'): for filename in filenames: print(os.path.join(dirname, filename))
Natural Language Processing with Disaster Tweets
14,011,004
def load_dataset(root): csv = pd.read_csv(os.path.join(root, "train.csv")) data = {} for i in csv.index: key = csv["image_id"][i] bbox = json.loads(csv["bbox"][i]) bbox = [bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3], 0.0] if key in data: data[key].append(bbox) else: data[key] = [bbox] return sorted( [(k, ...
tweets = 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
14,011,004
def load_model(path, ctx=mx.cpu()): net = gcv.model_zoo.yolo3_darknet53_custom(["wheat"], pretrained_base=False) net.set_nms(post_nms=150) net.load_parameters(path, ctx=ctx) return net <normalization>
stop = set(stopwords.words('english')) corpus0 = [] [corpus0.append(word.lower())for tweet in tweets[tweets.target == 0].text for word in word_tokenize(tweet)] corpus1 = [] [corpus1.append(word.lower())for tweet in tweets[tweets.target == 1].text for word in word_tokenize(tweet)] def count_top_stopwords(corpus): stopwo...
Natural Language Processing with Disaster Tweets
14,011,004
def inference(models, path): raw = load_image(path) rh, rw, _ = raw.shape classes_list = [] scores_list = [] bboxes_list = [] for _ in range(16): img, flips = gcv.data.transforms.image.random_flip(raw, px=0.5, py=0.5) x, _ = gcv.data.transforms.presets.yolo.transform_test(img, short=img_s) _, _, xh, xw = x.shape rot...
stop = ENGLISH_STOP_WORDS.union(stop) def remove_url(txt): return ' '.join(re.sub('([^0-9A-Za-z \t])|(\w+:\/\/\S+)', '', txt ).split()) corpus0 = [] [corpus0.append(word.lower())for tweet in tweets[tweets.target == 0].text for word in word_tokenize(remove_url(tweet)) ] corpus0 = list(filter(lambda x: x not in stop, c...
Natural Language Processing with Disaster Tweets
14,011,004
rounds = 2 max_epochs = 5 learning_rate = 0.001 batch_size = 2 img_s = 1024 threshold = 0.1 context = mx.gpu() print("Loading pre-trained model...") model = load_model(".. /input/yolov3/global-wheat-yolo3-darknet53_best2.params", ctx=context) print("Loading training set...") dataset = load_dataset("/kaggle/input/glo...
tweets['polarity'] = [TextBlob(tweet ).sentiment.polarity for tweet in tweets.text] tweets['subjectivity'] = [TextBlob(tweet ).sentiment.subjectivity for tweet in tweets.text] tweets['exclaimation_num'] = [tweet.count('!')for tweet in tweets.text] tweets['questionmark_num'] = [tweet.count('?')for tweet in tweets.text] ...
Natural Language Processing with Disaster Tweets
14,011,004
sys.path.insert(0, "/kaggle/input/weightedboxesfusion") <define_variables>
tweets.keyword.fillna('None', inplace=True) def decontraction(phrase): phrase = re.sub(r"won't", "will not", phrase) phrase = re.sub(r"can't", "can not", phrase) phrase = re.sub(r"n't", " not", phrase) phrase = re.sub(r"'re", " are", phrase) phrase = re.sub(r"'s", " is", phrase) phrase = re.sub(r"'d", " would", p...
Natural Language Processing with Disaster Tweets
14,011,004
DATA_DIR = "/kaggle/input/global-wheat-detection" MODELS_IN_DIR = "/kaggle/input/frcnn152foldthree"<load_from_csv>
tweets.text = tweets.text.apply(lambda x: remove_url(x)) def remove_punct(text): new_punct = re.sub('\ |\!|\?', '', punctuation) table = str.maketrans('','', new_punct) return text.translate(table) tweets.text = tweets.text.apply(lambda x: remove_punct(x)) def replace_amp(text): text = re.sub(r' amp ', ' and ', text...
Natural Language Processing with Disaster Tweets
14,011,004
test_df = pd.read_csv(os.path.join(DATA_DIR, "sample_submission.csv")) test_df.shape<feature_engineering>
lemmatizer = WordNetLemmatizer() def lemma(text): words = word_tokenize(text) return ' '.join([lemmatizer.lemmatize(w.lower() , pos='v')for w in words]) tweets.text = tweets.text.apply(lambda x: lemma(x))
Natural Language Processing with Disaster Tweets
14,011,004
class WheatDataset(Dataset): def __init__(self, dataframe, image_dir, transforms=None): super().__init__() self.image_ids = dataframe['image_id'].unique() self.df = dataframe self.image_dir = image_dir self.transforms = transforms def __len__(self)-> int: return len(self.image_ids) def __getitem__(self, idx: int): ima...
def generate_ngrams(text, n): words = word_tokenize(text) return [' '.join(ngram)for ngram in list(get_data(ngrams(words, n)))if not all(w in stop for w in ngram)] def get_data(gen): try: for elem in gen: yield elem except(RuntimeError, StopIteration): return
Natural Language Processing with Disaster Tweets
14,011,004
def get_model() : backbone = resnet_fpn_backbone('resnet152', pretrained=False) model = FasterRCNN(backbone, num_classes=2) return model<load_pretrained>
bigrams_disaster = tweets[tweets.target==1].text.apply(lambda x: generate_ngrams(x, 2)) bigrams_ndisaster = tweets[tweets.target==0].text.apply(lambda x: generate_ngrams(x, 2)) bigrams_d_dict = {} for bgs in bigrams_disaster: for bg in bgs: if bg in bigrams_d_dict: bigrams_d_dict[bg] += 1 else: bigrams_d_dict[bg] = 1 b...
Natural Language Processing with Disaster Tweets
14,011,004
DEVICE = torch.device('cuda')if torch.cuda.is_available() else torch.device('cpu') model = get_model() model.load_state_dict(torch.load(os.path.join(MODELS_IN_DIR, "best_model.pth"))) model.eval() model.to(DEVICE) 1 == 1<categorify>
trigrams_disaster = tweets[tweets.target==1].text.apply(lambda x: generate_ngrams(x, 3)) trigrams_ndisaster = tweets[tweets.target==0].text.apply(lambda x: generate_ngrams(x, 3)) trigrams_d_dict = {} for tgs in trigrams_disaster: for tg in tgs: if tg in trigrams_d_dict: trigrams_d_dict[tg] += 1 else: trigrams_d_dict[tg...
Natural Language Processing with Disaster Tweets
14,011,004
def get_test_transforms() : return A.Compose([ A.Resize(height=1024, width=1024, p=1.0), ToTensorV2(p=1.0), ], p=1.0 )<create_dataframe>
def remove_stopwords(text): word_tokens = word_tokenize(text) return ' '.join([w.lower() for w in word_tokens if not w.lower() in stop]) tweets['text_nostopwords'] = tweets.text.apply(lambda x: remove_stopwords(x))
Natural Language Processing with Disaster Tweets
14,011,004
def collate_fn(batch): return tuple(zip(*batch)) test_dataset = WheatDataset(test_df, os.path.join(DATA_DIR, "test"), get_test_transforms()) test_data_loader = DataLoader( test_dataset, batch_size=4, shuffle=False, num_workers=1, drop_last=False, collate_fn=collate_fn )<define_variables>
mask = np.array(Image.open('.. /input/twitterlogo3/twitter-logo-png-transparent.png')) reverse = mask[...,::-1,:] def wc_words(target, mask=mask): words = [word.lower() for tweet in tweets[tweets.target == target].text_nostopwords for word in tweet.split() ] words = list(filter(lambda w: w != 'like', words)) words = li...
Natural Language Processing with Disaster Tweets
14,011,004
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>
pd.reset_option('max_colwidth') tweets.drop('text_nostopwords', axis=1, inplace=True) tweets.head()
Natural Language Processing with Disaster Tweets
14,011,004
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...
X_train, X_val, y_train, y_val = train_test_split(tweets.drop(['keyword','location','target'],axis=1), tweets[['target']], test_size=0.2, stratify=tweets[['target']], random_state=0) X_train_text = X_train['text'] X_val_text = X_val['text'] print('X_train shape: ', X_train.shape) print('X_val shape: ', X_val.shape) ...
Natural Language Processing with Disaster Tweets
14,011,004
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>
print('Train Class Proportion: ', y_train['target'].value_counts() / len(y_train)* 100) print(' Validation Class Proportion: ', y_val['target'].value_counts() / len(y_val)* 100 )
Natural Language Processing with Disaster Tweets
14,011,004
def make_tta_predictions(images, score_threshold=0.5): with torch.no_grad() : images = torch.stack(images ).float().to(DEVICE) predictions = [] for tta_transform in tta_transforms: result = [] outputs = model(tta_transform.batch_augment(images.clone())) for i, image in enumerate(images): boxes = outputs[i]['boxes'].da...
tokenizer_1 = Tokenizer(num_words=5000, oov_token='<UNK>') tokenizer_1.fit_on_texts(X_train_text )
Natural Language Processing with Disaster Tweets
14,011,004
def run_wbf(predictions, image_index, image_size=1024, iou_thr=0.5, 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_...
X_train_text = tokenizer_1.texts_to_sequences(X_train_text) X_val_text = tokenizer_1.texts_to_sequences(X_val_text) print(X_train_text[:10]) print('') print(X_val_text[:10] )
Natural Language Processing with Disaster Tweets
14,011,004
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.round().astype(np.int32 ).clip(min=0, max=1023) image_id = image_ids[i] boxes[:, 2] = boxes[:, 2] - boxes[:, ...
tokenizer_1.sequences_to_texts([X_train_text[1]] )
Natural Language Processing with Disaster Tweets
14,011,004
test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString']) test_df.head()<save_to_csv>
vocab_size = len(tokenizer_1.word_index)+ 1 embeddings_index = dict() f = open('.. /input/glovetwitter27b100dtxt/glove.twitter.27B.200d.txt') for line in f: values = line.split() word = values[0] coefs = np.asarray(values[1:], dtype='float32') embeddings_index[word] = coefs f.close() print('Loaded %s word vectors.' %...
Natural Language Processing with Disaster Tweets
14,011,004
test_df.to_csv('submission.csv', index=False )<install_modules>
embedding_matrix = np.zeros(( vocab_size, 200)) for word, i in tokenizer_1.word_index.items() : embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector print('Embedding Matrix Shape:', embedding_matrix.shape )
Natural Language Processing with Disaster Tweets
14,011,004
!pip install --no-deps '.. /input/timm0130/timm-0.1.30-py3-none-any.whl' > /dev/null<install_modules>
num_epochs=15 dropout=0.2 recurrent_dropout=0.2 lr=0.0005 batch_size=128 class_weight = {0: y_train['target'].value_counts() [1]/len(y_train), 1: y_train['target'].value_counts() [0]/len(y_train)}
Natural Language Processing with Disaster Tweets
14,011,004
!pip install --no-deps '.. /input/pycocotools/pycocotools-2.0-cp37-cp37m-linux_x86_64.whl' > /dev/null<set_options>
lstm_model = Sequential() embedding_layer = Embedding(vocab_size, 200, weights=[embedding_matrix], input_length=maxlen, trainable=False) lstm_model.add(embedding_layer) lstm_model.add(LSTM(128, return_sequences=True, dropout=dropout, recurrent_dropout=recurrent_dropout)) lstm_model.add(LSTM(128)) lstm_model.add(Dense...
Natural Language Processing with Disaster Tweets
14,011,004
%matplotlib inline VerticalFlip, HorizontalFlip, IAASharpen, OneOf, Compose , BboxParams, Resize, HueSaturationValue ,RandomBrightnessContrast, ToGray , Cutout , RandomSizedCrop )<import_modules>
checkpoint = ModelCheckpoint('lstm_model.h5', monitor='val_acc', save_best_only=True) history = lstm_model.fit(X_train_text, y_train, batch_size=batch_size, callbacks=[checkpoint], epochs=num_epochs, class_weight=class_weight, validation_data=(X_val_text, y_val), verbose=1) plot_model_performance(history )
Natural Language Processing with Disaster Tweets
14,011,004
from effdet import get_efficientdet_config, EfficientDet, DetBenchTrain , DetBenchPredict from effdet.efficientdet import HeadNet<define_variables>
test['char_len'] = test.text.str.len() word_tokens = [len(word_tokenize(tweet)) for tweet in test.text] test['word_len'] = word_tokens sent_tokens = [len(sent_tokenize(tweet)) for tweet in test.text] test['sent_len'] = sent_tokens
Natural Language Processing with Disaster Tweets
14,011,004
DIR_PATH = '/kaggle/input/global-wheat-detection/' dir = glob.glob(os.path.join(DIR_PATH , '*')) dir.sort(reverse=True) train_paths = glob.glob(os.path.join(dir[1] , '*')) test_paths = glob.glob(os.path.join(dir[2] , '*'))<feature_engineering>
test['polarity'] = [TextBlob(tweet ).sentiment.polarity for tweet in test.text] test['subjectivity'] = [TextBlob(tweet ).sentiment.subjectivity for tweet in test.text] test['exclaimation_num'] = [tweet.count('!')for tweet in test.text] test['questionmark_num'] = [tweet.count('?')for tweet in test.text] def count_url_ha...
Natural Language Processing with Disaster Tweets
14,011,004
df = pd.read_csv(dir[0]) 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<feature_engineering>
test.keyword.fillna('None', inplace=True) def decontraction(phrase): phrase = re.sub(r"won't", "will not", phrase) phrase = re.sub(r"can't", "can not", phrase) phrase = re.sub(r"n't", " not", phrase) phrase = re.sub(r"'re", " are", phrase) phrase = re.sub(r"'s", " is", phrase) phrase = re.sub(r"'d", " would", phr...
Natural Language Processing with Disaster Tweets
14,011,004
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) df_folds = df[['image_id']].copy() df_folds.loc[:, 'bbox_count'] = 1 df_folds = df_folds.groupby('image_id' ).count() df_folds.loc[:, 'source'] = df[['image_id', 'source']].groupby('image_id' ).min() ['source'] df_folds.loc[:, 'stratify_group'] = np.char...
test.text = test.text.apply(lambda x: remove_url(x)) def remove_punct(text): new_punct = re.sub('\ |\!|\?', '', punctuation) table=str.maketrans('','',new_punct) return text.translate(table) test.text = test.text.apply(lambda x: remove_punct(x)) def replace_amp(text): text = re.sub(r" amp ", " and ", text) return t...
Natural Language Processing with Disaster Tweets
14,011,004
image_id = '8425a537b.jpg' image_path = glob.glob(os.path.join(dir[1] , image_id)) image , boxes = load_image_and_boxes(image_path[0]) show_image(image, boxes, "Image without bounding box" )<train_model>
lemmatizer = WordNetLemmatizer() def lemma(text): words = word_tokenize(text) return ' '.join([lemmatizer.lemmatize(w.lower() , pos='v')for w in words]) test.text = test.text.apply(lambda x: lemma(x))
Natural Language Processing with Disaster Tweets
14,011,004
image_id = 'b3c96d5ad.jpg' image_path = glob.glob(os.path.join(dir[1] , image_id)) image , boxes = load_image_and_boxes(image_path[0]) show_image(image, boxes, "Image with bounding box" )<normalization>
test_text = test['text'] test_text = tokenizer_1.texts_to_sequences(test_text) test_text = pad_sequences(test_text, padding='post', maxlen=50) print('X_test shape:', test_text.shape )
Natural Language Processing with Disaster Tweets
14,011,004
<normalization><EOS>
lstm_model.load_weights('lstm_model.h5') submission = test.copy() [['id']] submission['target'] = lstm_model.predict_classes(test_text) submission.to_csv('submission.csv', index=False) display(submission.head() )
Natural Language Processing with Disaster Tweets
21,936,667
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<feature_engineering>
train = pd.read_csv(".. /input/nlp-getting-started/train.csv") test = pd.read_csv(".. /input/nlp-getting-started/test.csv") train.head()
Natural Language Processing with Disaster Tweets
21,936,667
class WheatDataset(Dataset): def __init__(self , dataframe , image_ids, transforms = None): super().__init__() self.image_ids = image_ids self.dataframe = dataframe self.transforms = transforms def __getitem__(self, index: int): image_id = self.image_ids[index] image, boxes = self.load_image_and_boxes(index) labels = ...
!wget --quiet https://raw.githubusercontent.com/tensorflow/models/master/official/nlp/bert/tokenization.py !pip install sentencepiece
Natural Language Processing with Disaster Tweets
21,936,667
def collate_fn(batch): return tuple(zip(*batch))<create_dataframe>
import tensorflow_hub as hub import tokenization from sklearn.model_selection import train_test_split import tensorflow as tf
Natural Language Processing with Disaster Tweets
21,936,667
bs = 2 fold_number = 0 train_set = WheatDataset(dataframe=df, image_ids=df_folds[df_folds['fold'] != fold_number].index.values , transforms=transforms_train) valid_set = WheatDataset(dataframe=df, image_ids=df_folds[df_folds['fold'] == fold_number].index.values , transforms=transforms_valid) train_loader = DataLoader...
X = np.array(train['text']) y = np.array(train['target'] )
Natural Language Processing with Disaster Tweets
21,936,667
class Training: 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.best_calc_loss = 10**5 self.model = model self.device = device self.optimizer = torch.optim.AdamW(self.model.parameters...
def bert_encode(texts,tokenizer, max_len = 512): all_tokens = [] all_masks = [] all_segments = [] for text in texts: text = tokenizer.tokenize(text) text = text[:max_len-2] input_sequence = ["[CLS]"] + text + ["[SEP]"] tokens = tokenizer.convert_tokens_to_ids(input_sequence) pad_len = max_len - len(input_sequence) t...
Natural Language Processing with Disaster Tweets
21,936,667
def get_model(num_classes = 1): config = get_efficientdet_config('tf_efficientdet_d7x') model = EfficientDet(config, pretrained_backbone=False) checkpoint = torch.load('.. /input/efficientdetd7x/tf_efficientdet_d7x-f390b87c.pth') model.load_state_dict(checkpoint) config.num_classes = num_classes config.image_size =...
def build_model(bert_layer,max_len=512): input_word_ids = tf.keras.layers.Input(shape=(max_len,),dtype=tf.int32,name="input_word_ids") input_mask = tf.keras.layers.Input(shape=(max_len,),dtype=tf.int32,name="input_mask") input_segment_ids = tf.keras.layers.Input(shape=(max_len,),dtype=tf.int32,name="input_segment_ids...
Natural Language Processing with Disaster Tweets
21,936,667
class GlobalParametersTrain: lr = 0.0002 n_epochs = 20 folder = '.. /input/modelfasterrcnn' verbose = True verbose_step = 10 step_scheduler = False validation_scheduler = True SchedulerClass = torch.optim.lr_scheduler.ReduceLROnPlateau scheduler_params = dict(mode='min',factor=0.5,patience=1,verbose=False, threshold=0....
%%time module_url = "https://tfhub.dev/tensorflow/bert_en_uncased_L-24_H-1024_A-16/1" bert_layer = hub.KerasLayer(module_url, trainable=True )
Natural Language Processing with Disaster Tweets
21,936,667
def load_model(checkpoint_path): config = get_efficientdet_config('tf_efficientdet_d7x') model = EfficientDet(config, pretrained_backbone=False) config.num_classes = 1 config.image_size=512 model.class_net = HeadNet(config, num_outputs=config.num_classes, norm_kwargs=dict(eps=.001, momentum=.01)) checkpoint = torch.l...
vocab_file = bert_layer.resolved_object.vocab_file.asset_path.numpy() do_lower_case = bert_layer.resolved_object.do_lower_case.numpy() tokenizer = tokenization.FullTokenizer(vocab_file, do_lower_case )
Natural Language Processing with Disaster Tweets
21,936,667
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') def make_predictions(images , score_threshold=0.22): images = torch.stack(images ).cuda().float() predictions = [] with torch.no_grad() : outputs = model(images , torch.tensor([1.0] * images.shape[0], dtype=torch.float ).to(device), torch.tensor([im...
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2) train_input = bert_encode(X_train,tokenizer,max_len=264) val_input = bert_encode(X_test,tokenizer,max_len=264) test_input = bert_encode(test.text.values,tokenizer,max_len=264) train_labels = y_train val_labels = y_test
Natural Language Processing with Disaster Tweets
21,936,667
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 = [prediction[image_index]['...
checkpoint = ModelCheckpoint('model.h5', monitor='val_loss', save_best_only=True) es = EarlyStopping(monitor='val_loss',patience=3,verbose=1,restore_best_weights=True,min_delta=0.01) model.compile(optimizer=Adam(lr=1e-5),loss='binary_crossentropy',metrics=['accuracy']) train_history = model.fit( train_input, train_...
Natural Language Processing with Disaster Tweets
21,936,667
for j,(images, targets , image_ids)in enumerate(valid_loader): break predictions = make_predictions(images) i = 0 sample = images[i].permute(1,2,0 ).cpu().numpy() boxes, scores, labels = run_wbf(predictions, image_index=i) boxes = boxes.astype(np.int32 ).clip(min=0, max=511 )<categorify>
y_pred = model.predict(test_input) ans = pd.DataFrame({'id':np.array(test['id']),'target':np.array(y_pred.round().astype(int)).reshape(-1)}) ans.to_csv('submission.csv',index=False) ans
Natural Language Processing with Disaster Tweets
7,928,811
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(sel...
nltk.download('wordnet') nltk.download('punkt')
Natural Language Processing with Disaster Tweets
7,928,811
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>
df = pd.read_csv("/kaggle/input/nlp-getting-started/train.csv") df_test = pd.read_csv("/kaggle/input/nlp-getting-started/test.csv") df.sample(10 )
Natural Language Processing with Disaster Tweets
7,928,811
def make_tta_predictions(images, score_threshold=0.5): with torch.no_grad() : images = torch.stack(images ).float().cuda() predictions = [] for tta_transform in tta_transforms: result = [] outputs = model(tta_transform.batch_augment(images.clone()), torch.tensor([1]*images.shape[0] ).float().cuda() , torch.tensor([imag...
print("Training :") print("Length of the data :", len(df)) print(df.isnull().sum() )
Natural Language Processing with Disaster Tweets
7,928,811
test_transforms = Compose([ Resize(height=512, width=512, p=1.0), ToTensorV2(p=1.0), ], p=1.0 )<categorify>
print("Test :") print("Length of the data :", len(df_test)) print(df_test.isnull().sum() )
Natural Language Processing with Disaster Tweets
7,928,811
class TestDataset(Dataset): def __init__(self, image_ids, transforms=None): super().__init__() self.image_ids = image_ids self.transforms = transforms def __getitem__(self, index): image_id = self.image_ids[index] image = cv2.imread(f'{dir[2]}/{image_id}.jpg', cv2.IMREAD_COLOR) image = cv2.cvtColor(image, cv2.COLOR_BG...
tokens = word_tokenize(df["text"][0]) tokens = [word.lower() for word in tokens] print(df["text"][0]) print(tokens )
Natural Language Processing with Disaster Tweets
7,928,811
def collate_fn(batch): return tuple(zip(*batch))<create_dataframe>
words = [word for word in tokens if word.isalpha() ] print(words )
Natural Language Processing with Disaster Tweets
7,928,811
test_set = TestDataset(image_ids=np.array([path.split('/')[-1][:-4] for path in test_paths]),transforms=test_transforms) test_loader = DataLoader(test_set,batch_size=4,shuffle=False,num_workers=2,drop_last=False,collate_fn=collate_fn )<define_variables>
stop_words = set(stopwords.words("english")) words = [word for word in words if not word in stop_words] print(words )
Natural Language Processing with Disaster Tweets
7,928,811
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 )<save_to_csv>
porter = PorterStemmer() stemmed = [porter.stem(word)for word in words] print(stemmed )
Natural Language Processing with Disaster Tweets
7,928,811
SUBMISSION_PATH = '/kaggle/working' submission_id = 'submission' submission_path = os.path.join(SUBMISSION_PATH, '{}.csv'.format(submission_id)) sample_submission = pd.DataFrame(submission, columns=["image_id","PredictionString"]) sample_submission.to_csv(submission_path, index=False) submission_df = pd.read_csv(subm...
lemmatizer = WordNetLemmatizer() lemmatized = [lemmatizer.lemmatize(word)for word in words] print(lemmatized )
Natural Language Processing with Disaster Tweets
7,928,811
all_path = glob('.. /input/global-wheat-detection/test/*') DATA_ROOT_PATH = '.. /input/global-wheat-detection/test'<categorify>
def remove_URL(text): url = re.compile(r'https?://\S+|www\.\S+') return url.sub(r'',text) def remove_html(text): html=re.compile(r'<.*?>') return html.sub(r'',text) def remove_emoji(text): emoji_pattern = re.compile("[" u"\U0001F600-\U0001F64F" u"\U0001F300-\U0001F5FF" u"\U0001F680-\U0001F6FF" u"\U0001F1E0-\U0001F1...
Natural Language Processing with Disaster Tweets
7,928,811
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 join_list(tab): return " ".join(tab) df["text_preprocessed"] = df["tokens"].apply(join_list) df_test["text_preprocessed"] = df_test["tokens"].apply(join_list) def transform_keyword(word): return word.split('%20') df["keyword"] = df.keyword.fillna(" ") df_test["keyword"] = df_test.keyword.fillna(" ") df["keywo...
Natural Language Processing with Disaster Tweets
7,928,811
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}/{image_id}.jpg', cv2.IMREAD_COLOR) image = cv2.cvtColor(i...
X_all = pd.concat([df["text_preprocessed"], df_test["text_preprocessed"]]) sk_doc2bow = CountVectorizer() sk_doc2bow.fit(X_all) del X_all X = sk_doc2bow.transform(df["text_preprocessed"]) X_test = sk_doc2bow.transform(df_test["text_preprocessed"]) X_train, X_val, y_train, y_val = train_test_split(X, df["target"], t...
Natural Language Processing with Disaster Tweets
7,928,811
dataset = DatasetRetriever( image_ids=np.array([path.split('/')[-1][:-4] for path in glob(f'{DATA_ROOT_PATH}/*.jpg')]), transforms=get_valid_transforms() ) def collate_fn(batch): return tuple(zip(*batch)) data_loader = DataLoader( dataset, batch_size=4, shuffle=False, num_workers=2, drop_last=False, collate_fn=coll...
model = SVC(C=2, gamma=0.4, kernel='rbf' ).fit(X_train, y_train) y_val_pred = model.predict(X_val) print(accuracy_score(y_val, y_val_pred), f1_score(y_val, y_val_pred)) print(confusion_matrix(y_val, y_val_pred)) model = SVC(C=2, gamma=0.4, kernel='rbf' ).fit(X, df.target) y_test_pred = model.predict(X_test) sub_df ...
Natural Language Processing with Disaster Tweets
7,928,811
class CrossEntropyLabelSmooth(nn.Module): def __init__(self, num_classes, epsilon=0.1, use_gpu=True): super(CrossEntropyLabelSmooth, self ).__init__() self.num_classes = num_classes self.epsilon = epsilon self.use_gpu = use_gpu self.logsoftmax = nn.LogSoftmax(dim=1) def forward(self, inputs, targets): log_probs = ...
X_all = pd.concat([df["text_preprocessed"], df_test["text_preprocessed"]]) tfidf = TfidfVectorizer(stop_words = 'english') tfidf.fit(X_all) del X_all X = tfidf.transform(df["text_preprocessed"]) X_test = tfidf.transform(df_test["text_preprocessed"]) X_train, X_val, y_train, y_val = train_test_split(X, df["target"]...
Natural Language Processing with Disaster Tweets
7,928,811
def fastrcnn_loss(class_logits, box_regression, labels, regression_targets): labels = torch.cat(labels, dim=0) regression_targets = torch.cat(regression_targets, dim=0) labal_smooth_loss = CrossEntropyLabelSmooth(2) classification_loss = labal_smooth_loss(class_logits, labels) sampled_pos_inds_subset = torch.nonz...
model = SVC(C=2, gamma=0.4, kernel='rbf' ).fit(X_train, y_train) y_val_pred = model.predict(X_val) print(accuracy_score(y_val, y_val_pred), f1_score(y_val, y_val_pred)) print(confusion_matrix(y_val, y_val_pred)) model = SVC(C=2, gamma=0.4, kernel='rbf' ).fit(X, df.target) y_test_pred = model.predict(X_test) sub_df ...
Natural Language Processing with Disaster Tweets
7,928,811
def fpn_backbone_269(pretrained, norm_layer=misc_nn_ops.FrozenBatchNorm2d, trainable_layers=3): print(f' Pretarined is {pretrained}') backbone = resnest269e(pretrained=pretrained) assert trainable_layers <= 5 and trainable_layers >= 0 layers_to_train = ['layer4', 'layer3', 'layer2', 'layer1', 'conv1'][:trainable_laye...
X_all = pd.concat([df["text_preprocessed"], df_test["text_preprocessed"]]) tfidf = TfidfVectorizer(stop_words = 'english', min_df=10) tfidf.fit(X_all) del X_all X = tfidf.transform(df["text_preprocessed"]) X_test = tfidf.transform(df_test["text_preprocessed"]) X_train, X_val, y_train, y_val = train_test_split(X, d...
Natural Language Processing with Disaster Tweets
7,928,811
def fpn_backbone_101(pretrained, norm_layer=misc_nn_ops.FrozenBatchNorm2d, trainable_layers=3): print(f' Pretarined is {pretrained}') backbone = resnest101e(pretrained=pretrained) assert trainable_layers <= 5 and trainable_layers >= 0 layers_to_train = ['layer4', 'layer3', 'layer2', 'layer1', 'conv1'][:trainable_laye...
model = SVC(C=2, gamma=0.4, kernel='rbf' ).fit(X_train, y_train) y_val_pred = model.predict(X_val) print(accuracy_score(y_val, y_val_pred), f1_score(y_val, y_val_pred)) print(confusion_matrix(y_val, y_val_pred)) model = SVC(C=2, gamma=0.4, kernel='rbf' ).fit(X, df.target) y_test_pred = model.predict(X_test) sub_df ...
Natural Language Processing with Disaster Tweets
7,928,811
def load_net_269(checkpoint_path): model = WheatDetector_269() checkpoint=torch.load(checkpoint_path) model.load_state_dict(checkpoint['model_state_dict']) del checkpoint gc.collect() model.eval() ; return model.cuda() def load_net_101(checkpoint_path): model = WheatDetector_101() checkpoint=torch.load(checkpoint_pat...
X_all = pd.concat([df["text_preprocessed"], df_test["text_preprocessed"]]) tfidf = TfidfVectorizer(stop_words = 'english', min_df=5, ngram_range=(1, 3)) tfidf.fit(X_all) del X_all X = tfidf.transform(df["text_preprocessed"]) X_test = tfidf.transform(df_test["text_preprocessed"]) X_train, X_val, y_train, y_val = tra...
Natural Language Processing with Disaster Tweets
7,928,811
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...
model = SVC(C=2, gamma=0.4, kernel='rbf' ).fit(X_train, y_train) y_val_pred = model.predict(X_val) print(accuracy_score(y_val, y_val_pred), f1_score(y_val, y_val_pred)) print(confusion_matrix(y_val, y_val_pred)) model = SVC(C=2, gamma=0.4, kernel='rbf' ).fit(X, df.target) y_test_pred = model.predict(X_test) sub_df ...
Natural Language Processing with Disaster Tweets
7,928,811
def process_det(index, outputs, score_threshold=0.5): boxes = outputs[index]['boxes'].data.cpu().numpy() scores = outputs[index]['scores'].data.cpu().numpy() boxes =(boxes ).clip(min=0, max=1023 ).astype(int) indexes = np.where(scores>score_threshold) boxes = boxes[indexes] scores = scores[indexes] return boxes, scor...
X_all = pd.concat([df["tokens"], df_test["tokens"]] ).reset_index(drop=True) print(len(X_all)) mydict = Dictionary(X_all) corpus = [mydict.doc2bow(text)for text in X_all] tf_model = TfidfModel(corpus) corpus_tf = tf_model[corpus] print(len(corpus_tf)) lsi_model = LsiModel(corpus_tf, id2word=mydict, num_topics=200 )
Natural Language Processing with Disaster Tweets
7,928,811
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>
mydict.num_docs
Natural Language Processing with Disaster Tweets
7,928,811
def make_tta_predictions(images,net, score_threshold=0.1): with torch.no_grad() : images = torch.stack(images ).float().cuda() predictions = [] for tta_transform in tta_transforms: result = [] outputs = net(tta_transform.batch_augment(images.clone())) for i, image in enumerate(images): boxes = outputs[i]['boxes'].data....
for i, word in enumerate(mydict.items()): print(word) if i > 9: break
Natural Language Processing with Disaster Tweets
7,928,811
fold1 = {} for images, image_ids in data_loader: predictions = make_tta_predictions(images,models[0]) for i, image in enumerate(images): boxes, scores, labels = run_wbf(predictions, image_index=i) image_id = image_ids[i] fold1[image_id] = [boxes, scores, labels] print(' Completed') fold2 = {} for images, image_ids i...
lsi_model.num_topics
Natural Language Processing with Disaster Tweets
7,928,811
fold5 = {} for images, image_ids in data_loader: predictions = make_tta_predictions(images,models[4]) for i, image in enumerate(images): boxes, scores, labels = run_wbf(predictions, image_index=i) image_id = image_ids[i] fold5[image_id] = [boxes, scores, labels] print(' Completed') fold6 = {} for images, image_ids i...
def transform(df): corpus = [mydict.doc2bow(text)for text in df] corpus = tf_model[corpus] corpus = lsi_model[corpus] return corpus print(len(df["tokens"])) X = transform(df["tokens"]) print(len(X)) X_test = transform(df_test["tokens"]) X_train, X_val, y_train, y_val = train_test_split(X, df["target"], test_size=0.1,...
Natural Language Processing with Disaster Tweets
7,928,811
def run_last_wbf(model1,model2,model3,model4, model5,model6,model7,model8,model9,model10, iou_thr=0.5,skip_box_thr=0.43): box1,scores1,labels1 = model1 box2,scores2,labels2 = model2 box3,scores3,labels3 = model3 box4,scores4,labels4 = model4 box1 = box1/1023 box2 = box2/1023 box3 = box3/1023 box4 = box4/1023 box5,score...
def make_vec(X, num_top): matrix = np.zeros(( len(X), num_top)) for i, row in enumerate(X): matrix[i, list(map(lambda tup: tup[0], row)) ] = list(map(lambda tup: tup[1], row)) return matrix make_vec(X_train, lsi_model.num_topics ).shape
Natural Language Processing with Disaster Tweets
7,928,811
w = {} for row in range(len(all_path)) : image_id = all_path[row].split("/")[-1].split(".")[0] boxes,scores,labels = run_last_wbf(fold1[image_id],fold2[image_id],fold3[image_id],fold4[image_id], fold5[image_id],fold6[image_id],fold7[image_id],fold8[image_id],fold9[image_id],fold10[image_id]) boxes =(boxes*1023) index...
def transform(df, tf_model, model): corpus = [mydict.doc2bow(text)for text in df] corpus = tf_model[corpus] corpus = model[corpus] corpus = make_vec(corpus, model.num_topics) return corpus print(len(df["tokens"])) X = transform(df["tokens"], tf_model, lsi_model) print(len(X)) X_test = transform(df_test["tokens"], tf_...
Natural Language Processing with Disaster Tweets
7,928,811
def get_valid_transforms() : return A.Compose([ A.Resize(height=512, width=512, p=1.0), ToTensorV2(p=1.0), ], p=1.0 )<data_type_conversions>
model = SVC(C=2, gamma=0.4, kernel='rbf' ).fit(X_train, y_train) y_val_pred = model.predict(X_val) print(accuracy_score(y_val, y_val_pred), f1_score(y_val, y_val_pred)) print(confusion_matrix(y_val, y_val_pred)) model = SVC(C=2, gamma=0.4, kernel='rbf' ).fit(X, df.target) y_test_pred = model.predict(X_test) sub_df ...
Natural Language Processing with Disaster Tweets
7,928,811
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}/{image_id}.jpg', cv2.IMREAD_COLOR) image = cv2.cvtColor(i...
model = RandomForestClassifier(n_estimators=200, max_depth=None, random_state=42, n_jobs=-1 ).fit(X_train, y_train) y_val_pred = model.predict(X_val) print(accuracy_score(y_val, y_val_pred), f1_score(y_val, y_val_pred)) print(confusion_matrix(y_val, y_val_pred)) model = RandomForestClassifier(n_estimators=200, max_de...
Natural Language Processing with Disaster Tweets
7,928,811
dataset = DatasetRetriever( image_ids=np.array([path.split('/')[-1][:-4] for path in glob(f'{DATA_ROOT_PATH}/*.jpg')]), transforms=get_valid_transforms() ) def collate_fn(batch): return tuple(zip(*batch)) data_loader = DataLoader( dataset, batch_size=4, shuffle=False, num_workers=2, drop_last=False, collate_fn=coll...
lda_model = LdaModel(corpus_tf, id2word=mydict, num_topics=100, dtype=np.float64 )
Natural Language Processing with Disaster Tweets
7,928,811
class CrossEntropyLabelSmooth(nn.Module): def __init__(self, num_classes, epsilon=0.1, use_gpu=True): super(CrossEntropyLabelSmooth, self ).__init__() self.num_classes = num_classes self.epsilon = epsilon self.use_gpu = use_gpu self.logsoftmax = nn.LogSoftmax(dim=1) def forward(self, inputs, targets): log_probs = ...
lda_model.num_topics
Natural Language Processing with Disaster Tweets
7,928,811
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(sel...
print(len(df["tokens"])) X = transform(df["tokens"], tf_model, lda_model) print(len(X)) X_test = transform(df_test["tokens"], tf_model, lda_model) X_train, X_val, y_train, y_val = train_test_split(X, df["target"], test_size=0.1, random_state=42 )
Natural Language Processing with Disaster Tweets
7,928,811
def make_tta_predictions(images,net, score_threshold=0.1): with torch.no_grad() : images = torch.stack(images ).float().cuda() predictions = [] for tta_transform in tta_transforms: result = [] outputs = net(tta_transform.batch_augment(images.clone())) for i, image in enumerate(images): boxes = outputs[i]['boxes'].data....
model = SVC(C=2, gamma=0.4, kernel='rbf' ).fit(X_train, y_train) y_val_pred = model.predict(X_val) print(accuracy_score(y_val, y_val_pred), f1_score(y_val, y_val_pred)) print(confusion_matrix(y_val, y_val_pred)) model = SVC(C=2, gamma=0.4, kernel='rbf' ).fit(X, df.target) y_test_pred = model.predict(X_test) sub_df ...
Natural Language Processing with Disaster Tweets
7,928,811
fold0 = {} for images, image_ids in data_loader: predictions = make_tta_predictions(images,models[0]) for i, image in enumerate(images): boxes, scores, labels = run_wbf(predictions, image_index=i) image_id = image_ids[i] fold0[image_id] = [boxes, scores, labels] print(' Completed') fold1 = {} for images, image_ids i...
model = RandomForestClassifier(n_estimators=200, max_depth=None, random_state=42, n_jobs=-1 ).fit(X_train, y_train) y_val_pred = model.predict(X_val) print(accuracy_score(y_val, y_val_pred), f1_score(y_val, y_val_pred)) print(confusion_matrix(y_val, y_val_pred)) model = RandomForestClassifier(n_estimators=200, max_de...
Natural Language Processing with Disaster Tweets
7,928,811
def run_last_wbf(model1,model2,model3,model4,model5, iou_thr=0.5,skip_box_thr=0.43): box1,scores1,labels1 = model1 box2,scores2,labels2 = model2 box3,scores3,labels3 = model3 box4,scores4,labels4 = model4 box5,scores5,labels5 = model5 box1 = box1/1023 box2 = box2/1023 box3 = box3/1023 box4 = box4/1023 box5 = box5/1023 ...
print(len(df["tokens"])) X_1 = transform(df["tokens"], tf_model, lda_model) X_2 = transform(df["tokens"], tf_model, lsi_model) X = np.hstack(( X_1, X_2)) print(len(X)) X_test = transform(df_test["tokens"], tf_model, lda_model) X_1 = transform(df_test["tokens"], tf_model, lda_model) X_2 = transform(df_test["tokens"]...
Natural Language Processing with Disaster Tweets
7,928,811
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...
model = SVC(C=2, gamma=0.4, kernel='rbf' ).fit(X_train, y_train) y_val_pred = model.predict(X_val) print(accuracy_score(y_val, y_val_pred), f1_score(y_val, y_val_pred)) print(confusion_matrix(y_val, y_val_pred)) model = SVC(C=2, gamma=0.4, kernel='rbf' ).fit(X, df.target) y_test_pred = model.predict(X_test) sub_df ...
Natural Language Processing with Disaster Tweets
7,928,811
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_PA...
model = RandomForestClassifier(n_estimators=200, max_depth=None, random_state=42, n_jobs=-1 ).fit(X_train, y_train) y_val_pred = model.predict(X_val) print(accuracy_score(y_val, y_val_pred), f1_score(y_val, y_val_pred)) print(confusion_matrix(y_val, y_val_pred)) model = RandomForestClassifier(n_estimators=200, max_de...
Natural Language Processing with Disaster Tweets
7,928,811
def run_wbf(predictions, image_index, image_size=512, iou_thr=0.432, skip_box_thr=0.397, 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...
X_all = pd.concat([df["tokens"], df_test["tokens"]] ).reset_index(drop=True) model_w2v = Word2Vec(sentences=X_all, size=50, window=3, min_count=1, workers=-1) del X_all
Natural Language Processing with Disaster Tweets
7,928,811
y={} for images, image_ids in data_loader: predictions = make_predictions(images) for i, image in enumerate(images): boxes, scores, labels = run_wbf(predictions, image_index=i,) boxes =(boxes*2) y[image_ids[i]] = [boxes,scores,labels]<load_pretrained>
vector = model_w2v.wv['armageddon'] print(vector )
Natural Language Processing with Disaster Tweets
7,928,811
models = [ load_net('.. /input/efficientdetd52/0.bin'), load_net('.. /input/efficientdetd52/1.bin'), load_net('.. /input/efficientdetd52/2.bin'), load_net('.. /input/efficientdetd52/3.bin'), load_net('.. /input/efficientdetd52/4.bin'), load_net('.. /input/kaggleeffnet/plabel_model/last-checkpoint1.bin'), load_net('.. /...
print(len(df["tokens"])) X = [np.mean([model_w2v.wv[text] for text in texts], axis=0)for texts in df["tokens"]] X = np.array(X) print(len(X)) X_test = [np.mean([model_w2v.wv[text] for text in texts], axis=0)if len(texts)!= 0 else np.zeros(50)for texts in df_test["tokens"]] X_test = np.array(X_test) X_test.shape
Natural Language Processing with Disaster Tweets