kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
12,165,368
best_th = 0.38 preds_t,y_t = learn.TTA(is_test=True,n_aug=8) preds_t = np.stack(preds_t, axis=-1) preds_t = np.exp(preds_t) preds_t = preds_t.mean(axis=-1) preds_t = np.concatenate([np.zeros(( preds_t.shape[0],1)) +best_th, preds_t],axis=1) np.save('preds_dn201.npy', preds_t )<save_to_csv>
augmenter = WordAugmentation(device='cuda' )
Natural Language Processing with Disaster Tweets
12,165,368
sample_df = pd.read_csv(SAMPLE_SUB) sample_list = list(sample_df.Image) labels_list = ["new_whale"]+labels_list pred_list = [[labels_list[i] for i in p.argsort() [-5:][::-1]] for p in preds_t] pred_dic = dict(( key, value)for(key, value)in zip(learn.data.test_ds.fnames,pred_list)) pred_list_cor = [' '.join(pred_dic[i...
tqdm.tqdm.pandas() new_sentences_replace = train_set.progress_apply(lambda x: augmenter.apply(x["text"], n_word=max(int(len(x["text"])*0.05), 1), action='replace'), axis=1 )
Natural Language Processing with Disaster Tweets
12,165,368
!pip install lap Lambda, MaxPooling2D, Reshape <load_from_csv>
new_train_set_replace = pd.DataFrame({"text": new_sentences_replace.to_numpy() , "target": train_set.target.to_numpy() } )
Natural Language Processing with Disaster Tweets
12,165,368
TRAIN_DF = '.. /input/humpback-whale-identification/train.csv' SUB_Df = '.. /input/humpback-whale-identification/sample_submission.csv' TRAIN = '.. /input/humpback-whale-identification/train/' TEST = '.. /input/humpback-whale-identification/test/' P2H = '.. /input/metadata/p2h.pickle' P2SIZE = '.. /input/metadata/p2siz...
augmented_train_set = pd.concat([train_set[["text", "target"]], new_train_set_replace], ignore_index=True )
Natural Language Processing with Disaster Tweets
12,165,368
if isfile(P2SIZE): print("P2SIZE exists.") with open(P2SIZE, 'rb')as f: p2size = pickle.load(f) else: p2size = {} for p in tqdm(join): size = pil_image.open(expand_path(p)).size p2size[p] = size<compute_test_metric>
augmented_train_set.drop_duplicates(subset="text", inplace=True )
Natural Language Processing with Disaster Tweets
12,165,368
def match(h1, h2): for p1 in h2ps[h1]: for p2 in h2ps[h2]: i1 = pil_image.open(expand_path(p1)) i2 = pil_image.open(expand_path(p2)) if i1.mode != i2.mode or i1.size != i2.size: return False a1 = np.array(i1) a1 = a1 - a1.mean() a1 = a1 / sqrt(( a1 ** 2 ).mean()) a2 = np.array(i2) a2 = a2 - a2.mean() a2 = a2 / sqrt(...
!pip install fastai==2.0.16
Natural Language Processing with Disaster Tweets
12,165,368
def prefer(ps): if len(ps)== 1: return ps[0] best_p = ps[0] best_s = p2size[best_p] for i in range(1, len(ps)) : p = ps[i] s = p2size[p] if s[0] * s[1] > best_s[0] * best_s[1]: best_p = p best_s = s return best_p h2p = {} for h, ps in h2ps.items() : h2p[h] = prefer(ps) len(h2p), list(h2p.items())[:5]<set_options>
accuracy, Perplexity, F1Score
Natural Language Processing with Disaster Tweets
12,165,368
p2bb = pd.read_csv(BB_DF ).set_index("Image") old_stderr = sys.stderr sys.stderr = open('/dev/null' if platform.system() != 'Windows' else 'nul', 'w') sys.stderr = old_stderr img_shape =(384, 384, 1) anisotropy = 2.15 crop_margin = 0.05<normalization>
train_target_0, validate_target_0 = np.split(augmented_train_set[augmented_train_set.target == 0].sample(frac=1, random_state=1), [int (.85 * len(augmented_train_set[augmented_train_set.target == 0])) ]) train_target_1, validate_target_1 = np.split(augmented_train_set[augmented_train_set.target == 1].sample(frac=1, ra...
Natural Language Processing with Disaster Tweets
12,165,368
def build_transform(rotation, shear, height_zoom, width_zoom, height_shift, width_shift): rotation = np.deg2rad(rotation) shear = np.deg2rad(shear) rotation_matrix = np.array( [[np.cos(rotation), np.sin(rotation), 0], [-np.sin(rotation), np.cos(rotation), 0], [0, 0, 1]]) shift_matrix = np.array([[1, 0, height_shi...
test_set["target"] = test_set.text.apply(lambda x : learn.predict(x)[0]) test_set[["id", "target"]].to_csv("submission.csv", index=False )
Natural Language Processing with Disaster Tweets
12,108,082
def read_cropped_image(p, augment): if p in h2p: p = h2p[p] size_x, size_y = p2size[p] row = p2bb.loc[p] x0, y0, x1, y1 = row['x0'], row['y0'], row['x1'], row['y1'] dx = x1 - x0 dy = y1 - y0 x0 -= dx * crop_margin x1 += dx * crop_margin + 1 y0 -= dy * crop_margin y1 += dy * crop_margin + 1 if x0 < 0: x0 = 0 if x1 > s...
!wget --quiet https://raw.githubusercontent.com/tensorflow/models/master/official/nlp/bert/tokenization.py
Natural Language Processing with Disaster Tweets
12,108,082
def subblock(x, filter, **kwargs): x = BatchNormalization()(x) y = x y = Conv2D(filter,(1, 1), activation='relu', **kwargs )(y) y = BatchNormalization()(y) y = Conv2D(filter,(3, 3), activation='relu', **kwargs )(y) y = BatchNormalization()(y) y = Conv2D(K.int_shape(x)[-1],(1, 1), **kwargs )(y) y = Add()([x, y]) ...
import tokenization import matplotlib.pyplot as plt import seaborn as sns import re import nltk import spacy import sys import random import fuzzywuzzy from fuzzywuzzy import process from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from spacy.util import minibatch from ten...
Natural Language Processing with Disaster Tweets
12,108,082
h2ws = {} new_whale = 'new_whale' for p, w in tagged.items() : if w != new_whale: h = p2h[p] if h not in h2ws: h2ws[h] = [] if w not in h2ws[h]: h2ws[h].append(w) for h, ws in h2ws.items() : if len(ws)> 1: h2ws[h] = sorted(ws) w2hs = {} for h, ws in h2ws.items() : if len(ws)== 1: w = ws[0] if w not in w2hs: w2hs[w] =...
random_seed = 0 data = pd.read_csv('/kaggle/input/nlp-getting-started/train.csv') print(data.shape) data.head()
Natural Language Processing with Disaster Tweets
12,108,082
train = [] for hs in w2hs.values() : if len(hs)> 1: train += hs random.shuffle(train) train_set = set(train) w2ts = {} for w, hs in w2hs.items() : for h in hs: if h in train_set: if w not in w2ts: w2ts[w] = [] if h not in w2ts[w]: w2ts[w].append(h) for w, ts in w2ts.items() : w2ts[w] = np.array(ts) t2i = {} for i, ...
print(data.isnull().sum()) display(data.nunique() )
Natural Language Processing with Disaster Tweets
12,108,082
class TrainingData(Sequence): def __init__(self, score, steps=1000, batch_size=32): super(TrainingData, self ).__init__() self.score = -score self.steps = steps self.batch_size = batch_size for ts in w2ts.values() : idxs = [t2i[t] for t in ts] for i in idxs: for j in idxs: self.score[ i, j] = 10000.0 self.on_epoch_en...
def utils_preprocess_text(text, flg_stemm=False, flg_lemm=True, lst_stopwords=None): text = re.sub(r"https?://\S+|www\.\S+", "", text) html = re.compile(r"<.*?>|&([a-z0-9]+| text = re.sub(html, "", text) l = len(text) t = text text= re.sub(r'[^\x00-\x7f]',r'', text) text = re.sub(r'[^\w\s]', '', str(text ).lower()....
Natural Language Processing with Disaster Tweets
12,108,082
def set_lr(model, lr): K.set_value(model.optimizer.lr, float(lr)) def get_lr(model): return K.get_value(model.optimizer.lr) def score_reshape(score, x, y=None): if y is None: m = np.zeros(( x.shape[0], x.shape[0]), dtype=K.floatx()) m[np.triu_indices(x.shape[0], 1)] = score.squeeze() m += m.transpose() else: m = np...
lst_stopwords = nltk.corpus.stopwords.words("english") data["text_clean"] = data["text"].apply(lambda x: utils_preprocess_text(x, flg_stemm=False, flg_lemm=True, lst_stopwords=lst_stopwords)) data.head()
Natural Language Processing with Disaster Tweets
12,108,082
def prepare_submission(threshold, filename): vtop = 0 vhigh = 0 pos = [0, 0, 0, 0, 0, 0] with open(filename, 'wt', newline=' ')as f: f.write('Image,Id ') for i, p in enumerate(tqdm(submit)) : t = [] s = set() a = score[i, :] for j in list(reversed(np.argsort(a))): h = known[j] if a[j] < threshold and new_whale not i...
def clean_location(data): data['location'] = data['location'].str.lower() data['location'] = data['location'].str.strip() data['location'] = data['location'].apply(lambda x: re.sub(r',(?s ).*$', r'', x)if str(x)!= str(np.nan)else np.nan) return data
Natural Language Processing with Disaster Tweets
12,108,082
histories = [] steps = 0 if isfile('.. /input/piotte/mpiotte-standard.model'): tmp = keras.models.load_model('.. /input/piotte/mpiotte-standard.model') model.set_weights(tmp.get_weights()) tic = time.time() h2ws = {} for p, w in tagged.items() : if w != new_whale: h = p2h[p] if h not in h2ws: h2ws[h] = [] if w not in...
data = clean_location(data )
Natural Language Processing with Disaster Tweets
12,108,082
score = 0.45*score1 + 0.55*score2<train_model>
def replace_matches_in_column(df, column, string_to_match, min_ratio = 90): strings = df[column].unique() matches = fuzzywuzzy.process.extract(string_to_match, strings, limit=10, scorer=fuzzywuzzy.fuzz.token_sort_ratio) close_matches = [matches[0] for matches in matches if matches[1] >= min_ratio] rows_with_matches = ...
Natural Language Processing with Disaster Tweets
12,108,082
prepare_submission(0.92, 'submission_0.45_standard_0.55_boostrap-400.csv') toc = time.time() print("Submission time: ",(toc - tic)/ 60.)<import_modules>
locations = data.groupby('location' ).location.count().sort_values(ascending=False) locations = locations[locations.values > 3] locations = locations.index for loc in locations: replace_matches_in_column(df=data, column='location', string_to_match=loc )
Natural Language Processing with Disaster Tweets
12,108,082
!pip install lapjv==1.3.1 Lambda, MaxPooling2D, Reshape <load_from_csv>
def rename_location(data): data.loc[(data.location == 'united states'), 'location'] = 'usa' data.loc[(data.location == 'united states of america'), 'location'] = 'usa' data.loc[(data.location == 'us'), 'location'] = 'usa' data.loc[(data.location == 'u.s.'), 'location'] = 'usa' data.loc[(data.location == 'u.s.a'), 'loca...
Natural Language Processing with Disaster Tweets
12,108,082
TRAIN_DF = '.. /input/humpback-whale-identification/train.csv' SUB_Df = '.. /input/humpback-whale-identification/sample_submission.csv' TRAIN = '.. /input/humpback-whale-identification/train/' TEST = '.. /input/humpback-whale-identification/test/' P2H = '.. /input/metadata/p2h.pickle' P2SIZE = '.. /input/metadata/p2siz...
locations = data.groupby('location' ).location.count().sort_values(ascending=False) locations = locations[locations.values <= 3] locations = locations.index for loc in locations: data.loc[(data.location == loc), 'location'] = np.nan data.groupby('location' ).location.count().sort_values(ascending=False )
Natural Language Processing with Disaster Tweets
12,108,082
if isfile(P2SIZE): print("P2SIZE exists.") with open(P2SIZE, 'rb')as f: p2size = pickle.load(f) else: p2size = {} for p in tqdm(join): size = pil_image.open(expand_path(p)).size p2size[p] = size<compute_test_metric>
def concatenate(data): data['sequence'] = data['text_clean'].map(str)+ ' XXLOC ' + data['location'].map(str)\ + ' XXKEY ' + data['keyword'].map(str)+ ' TWTXX' return data data = concatenate(data) print(data.sequence[0]) print(data.sequence[98]) print(data.sequence[100] )
Natural Language Processing with Disaster Tweets
12,108,082
def match(h1, h2): for p1 in h2ps[h1]: for p2 in h2ps[h2]: i1 = pil_image.open(expand_path(p1)) i2 = pil_image.open(expand_path(p2)) if i1.mode != i2.mode or i1.size != i2.size: return False a1 = np.array(i1) a1 = a1 - a1.mean() a1 = a1 / sqrt(( a1 ** 2 ).mean()) a2 = np.array(i2) a2 = a2 - a2.mean() a2 = a2 / sqrt(...
test = pd.read_csv('/kaggle/input/nlp-getting-started/test.csv') test["text_clean"] = test["text"].apply(lambda x: utils_preprocess_text(x, flg_stemm=False, flg_lemm=True, lst_stopwords=lst_stopwords)) test = clean_location(test) locations = test.groupby('location' ).location.count().sort_values(ascending=False) loc...
Natural Language Processing with Disaster Tweets
12,108,082
def prefer(ps): if len(ps)== 1: return ps[0] best_p = ps[0] best_s = p2size[best_p] for i in range(1, len(ps)) : p = ps[i] s = p2size[p] if s[0] * s[1] > best_s[0] * best_s[1]: best_p = p best_s = s return best_p h2p = {} for h, ps in h2ps.items() : h2p[h] = prefer(ps) len(h2p), list(h2p.items())[:5] <set_options>
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]"] pad_len = max_len - len(input_sequence) tokens = tokenizer.convert_tokens_to_ids(input_sequence) to...
Natural Language Processing with Disaster Tweets
12,108,082
p2bb = pd.read_csv(BB_DF ).set_index("Image") old_stderr = sys.stderr sys.stderr = open('/dev/null' if platform.system() != 'Windows' else 'nul', 'w') sys.stderr = old_stderr img_shape =(384, 384, 1) anisotropy = 2.15 crop_margin = 0.05<normalization>
def build_model(bert_layer, max_len=512): input_word_ids = Input(shape=(max_len,), dtype=tf.int32, name="input_word_ids") input_mask = Input(shape=(max_len,), dtype=tf.int32, name="input_mask") segment_ids = Input(shape=(max_len,), dtype=tf.int32, name="segment_ids") _, sequence_output = bert_layer([input_word_ids, ...
Natural Language Processing with Disaster Tweets
12,108,082
def build_transform(rotation, shear, height_zoom, width_zoom, height_shift, width_shift): rotation = np.deg2rad(rotation) shear = np.deg2rad(shear) rotation_matrix = np.array( [[np.cos(rotation), np.sin(rotation), 0], [-np.sin(rotation), np.cos(rotation), 0], [0, 0, 1]]) shift_matrix = np.array([[1, 0, height_shi...
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
12,108,082
def read_cropped_image(p, augment): if p in h2p: p = h2p[p] size_x, size_y = p2size[p] row = p2bb.loc[p] x0, y0, x1, y1 = row['x0'], row['y0'], row['x1'], row['y1'] dx = x1 - x0 dy = y1 - y0 x0 -= dx * crop_margin x1 += dx * crop_margin + 1 y0 -= dy * crop_margin y1 += dy * crop_margin + 1 if x0 < 0: x0 = 0 if x1 > s...
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
12,108,082
def subblock(x, filter, **kwargs): x = BatchNormalization()(x) y = x y = Conv2D(filter,(1, 1), activation='relu', **kwargs )(y) y = BatchNormalization()(y) y = Conv2D(filter,(3, 3), activation='relu', **kwargs )(y) y = BatchNormalization()(y) y = Conv2D(K.int_shape(x)[-1],(1, 1), **kwargs )(y) y = Add()([x, y]) ...
train_input = bert_encode(data.sequence.values, tokenizer, max_len=65) test_input = bert_encode(test.sequence.values, tokenizer, max_len=65) train_labels = data.target.values
Natural Language Processing with Disaster Tweets
12,108,082
h2ws = {} new_whale = 'new_whale' for p, w in tagged.items() : if w != new_whale: h = p2h[p] if h not in h2ws: h2ws[h] = [] if w not in h2ws[h]: h2ws[h].append(w) for h, ws in h2ws.items() : if len(ws)> 1: h2ws[h] = sorted(ws) w2hs = {} for h, ws in h2ws.items() : if len(ws)== 1: w = ws[0] if w not in w2hs: w2hs[w] =...
checkpoint = ModelCheckpoint('model.h5', monitor='val_loss', save_best_only=True) train_history = model.fit( train_input, train_labels, validation_split=0.15, epochs=3, callbacks=[checkpoint], batch_size=8 )
Natural Language Processing with Disaster Tweets
12,108,082
train = [] for hs in w2hs.values() : if len(hs)> 1: train += hs random.shuffle(train) train_set = set(train) w2ts = {} for w, hs in w2hs.items() : for h in hs: if h in train_set: if w not in w2ts: w2ts[w] = [] if h not in w2ts[w]: w2ts[w].append(h) for w, ts in w2ts.items() : w2ts[w] = np.array(ts) t2i = {} for i, ...
model.load_weights('model.h5') test_pred = model.predict(test_input )
Natural Language Processing with Disaster Tweets
12,108,082
class TrainingData(Sequence): def __init__(self, score, steps=1000, batch_size=32): super(TrainingData, self ).__init__() self.score = -score self.steps = steps self.batch_size = batch_size for ts in w2ts.values() : idxs = [t2i[t] for t in ts] for i in idxs: for j in idxs: self.score[ i, j] = 10000.0 self.on_epoch_en...
submission = pd.read_csv("/kaggle/input/nlp-getting-started/sample_submission.csv") submission['target'] = test_pred.round().astype(int) submission.to_csv('submission.csv', index=False )
Natural Language Processing with Disaster Tweets
12,023,430
def set_lr(model, lr): K.set_value(model.optimizer.lr, float(lr)) def get_lr(model): return K.get_value(model.optimizer.lr) def score_reshape(score, x, y=None): if y is None: m = np.zeros(( x.shape[0], x.shape[0]), dtype=K.floatx()) m[np.triu_indices(x.shape[0], 1)] = score.squeeze() m += m.transpose() else: m = np...
path_data_test='/kaggle/input/nlp-getting-started/test.csv' test_data=pd.read_csv(path_data_test) path_data_train='/kaggle/input/nlp-getting-started/train.csv' train_data=pd.read_csv(path_data_train )
Natural Language Processing with Disaster Tweets
12,023,430
histories = [] steps = 0 tmp = keras.models.load_model('.. /input/reset-v3-100/siamese_v3_100') model.set_weights(tmp.get_weights()) set_lr(model, 4e-5) make_steps(5, 0.25) set_lr(model, 4e-5) make_steps(5, 0.25) model.save('siamese_v3_110' )<save_model>
def clean(text): text = re.sub(r" ","",text) text = text.lower() text = re.sub(r"\d","",text) text = re.sub(r'[^\x00-\x7f]',r' ',text) text = re.sub(r'[^\w\s]','',text) text = re.sub(r'http\S+|www.\S+', '', text) return text
Natural Language Processing with Disaster Tweets
12,023,430
set_lr(model, 4e-5) make_steps(5, 0.25) set_lr(model, 4e-5) make_steps(5, 0.25) model.save('siamese_v3_120' )<load_pretrained>
train_data['cleaned'] = train_data['text'].apply(lambda x : clean(x)) test_data['cleaned']= test_data['text'].apply(lambda x : clean(x))
Natural Language Processing with Disaster Tweets
12,023,430
<feature_engineering><EOS>
tweets_pipeline = Pipeline([('CVec', CountVectorizer(stop_words='english')) , ('Tfidf', TfidfTransformer())]) X=train_data['cleaned'].to_numpy() Y=train_data['target'].to_numpy() X_train_tranformed = tweets_pipeline.fit_transform(X) X_test=test_data['cleaned'] X_test_tranformed = tweets_pipeline.transform(X_test) t...
Natural Language Processing with Disaster Tweets
7,207,018
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<import_modules>
!pip install tweet-preprocessor
Natural Language Processing with Disaster Tweets
7,207,018
!pip install lap Lambda, MaxPooling2D, Reshape <load_from_csv>
import os from google.cloud import storage, automl_v1beta1 as automl import numpy as np import pandas as pd from sklearn import feature_extraction, linear_model, model_selection, preprocessing from sklearn.ensemble import RandomForestClassifier from sklearn.tree import DecisionTreeClassifier import scipy as sp from skl...
Natural Language Processing with Disaster Tweets
7,207,018
TRAIN_DF = '.. /input/humpback-whale-identification/train.csv' SUB_Df = '.. /input/humpback-whale-identification/sample_submission.csv' TRAIN = '.. /input/humpback-whale-identification/train/' TEST = '.. /input/humpback-whale-identification/test/' P2H = '.. /input/metadata/p2h.pickle' P2SIZE = '.. /input/metadata/p2siz...
from sklearn import metrics
Natural Language Processing with Disaster Tweets
7,207,018
if isfile(P2SIZE): print("P2SIZE exists.") with open(P2SIZE, 'rb')as f: p2size = pickle.load(f) else: p2size = {} for p in tqdm(join): size = pil_image.open(expand_path(p)).size p2size[p] = size<compute_test_metric>
stop = set(STOPWORDS ).union(set(['FAV' , 'RT'])) lemma = WordNetLemmatizer() preprocessor.set_options(preprocessor.OPT.URL, preprocessor.OPT.MENTION, preprocessor.OPT.NUMBER, preprocessor.OPT.RESERVED) def clean(text): text = preprocessor.clean(text) text = re.sub(r'[^\w\s]','',text) stop_free = " ".join([i for i i...
Natural Language Processing with Disaster Tweets
7,207,018
def match(h1, h2): for p1 in h2ps[h1]: for p2 in h2ps[h2]: i1 = pil_image.open(expand_path(p1)) i2 = pil_image.open(expand_path(p2)) if i1.mode != i2.mode or i1.size != i2.size: return False a1 = np.array(i1) a1 = a1 - a1.mean() a1 = a1 / sqrt(( a1 ** 2 ).mean()) a2 = np.array(i2) a2 = a2 - a2.mean() a2 = a2 / sqrt(...
train_df = pd.read_csv("/kaggle/input/nlp-getting-started/train.csv") test_df = pd.read_csv("/kaggle/input/nlp-getting-started/test.csv" )
Natural Language Processing with Disaster Tweets
7,207,018
def prefer(ps): if len(ps)== 1: return ps[0] best_p = ps[0] best_s = p2size[best_p] for i in range(1, len(ps)) : p = ps[i] s = p2size[p] if s[0] * s[1] > best_s[0] * best_s[1]: best_p = p best_s = s return best_p h2p = {} for h, ps in h2ps.items() : h2p[h] = prefer(ps) len(h2p), list(h2p.items())[:5]<set_options>
train_df.text = train_df.text.apply(clean) test_df.text = test_df.text.apply(clean )
Natural Language Processing with Disaster Tweets
7,207,018
p2bb = pd.read_csv(BB_DF ).set_index("Image") old_stderr = sys.stderr sys.stderr = open('/dev/null' if platform.system() != 'Windows' else 'nul', 'w') sys.stderr = old_stderr img_shape =(384, 384, 1) anisotropy = 2.15 crop_margin = 0.05<normalization>
PROJECT_ID = 'automl-kaggle-263107'
Natural Language Processing with Disaster Tweets
7,207,018
def build_transform(rotation, shear, height_zoom, width_zoom, height_shift, width_shift): rotation = np.deg2rad(rotation) shear = np.deg2rad(shear) rotation_matrix = np.array( [[np.cos(rotation), np.sin(rotation), 0], [-np.sin(rotation), np.cos(rotation), 0], [0, 0, 1]]) shift_matrix = np.array([[1, 0, height_shi...
BUCKET_NAME = 'automl-disaster-tweet-cleaned' BUCKET_REGION = 'us-central1'
Natural Language Processing with Disaster Tweets
7,207,018
def read_cropped_image(p, augment): if p in h2p: p = h2p[p] size_x, size_y = p2size[p] row = p2bb.loc[p] x0, y0, x1, y1 = row['x0'], row['y0'], row['x1'], row['y1'] dx = x1 - x0 dy = y1 - y0 x0 -= dx * crop_margin x1 += dx * crop_margin + 1 y0 -= dy * crop_margin y1 += dy * crop_margin + 1 if x0 < 0: x0 = 0 if x1 > s...
storage_client = storage.Client(project=PROJECT_ID) tables_gcs_client = automl.GcsClient(client=storage_client, bucket_name=BUCKET_NAME) automl_client = automl.AutoMlClient() prediction_client = automl.PredictionServiceClient() tables_client = automl.TablesClient(project=PROJECT_ID, region=BUCKET_REGION, client=autom...
Natural Language Processing with Disaster Tweets
7,207,018
def subblock(x, filter, **kwargs): x = BatchNormalization()(x) y = x y = Conv2D(filter,(1, 1), activation='relu', **kwargs )(y) y = BatchNormalization()(y) y = Conv2D(filter,(3, 3), activation='relu', **kwargs )(y) y = BatchNormalization()(y) y = Conv2D(K.int_shape(x)[-1],(1, 1), **kwargs )(y) y = Add()([x, y]) ...
bucket = storage.Bucket(storage_client, name=BUCKET_NAME) if not bucket.exists() : bucket.create(location=BUCKET_REGION )
Natural Language Processing with Disaster Tweets
7,207,018
h2ws = {} new_whale = 'new_whale' for p, w in tagged.items() : if w != new_whale: h = p2h[p] if h not in h2ws: h2ws[h] = [] if w not in h2ws[h]: h2ws[h].append(w) for h, ws in h2ws.items() : if len(ws)> 1: h2ws[h] = sorted(ws) w2hs = {} for h, ws in h2ws.items() : if len(ws)== 1: w = ws[0] if w not in w2hs: w2hs[w] =...
def upload_blob(bucket_name, source_file_name, destination_blob_name): bucket = storage_client.get_bucket(bucket_name) blob = bucket.blob(destination_blob_name) blob.upload_from_filename(source_file_name) print('File {} uploaded to {}.'.format( source_file_name, destination_blob_name)) def download_to_kaggle(buck...
Natural Language Processing with Disaster Tweets
7,207,018
train = [] for hs in w2hs.values() : if len(hs)> 1: train += hs random.shuffle(train) train_set = set(train) w2ts = {} for w, hs in w2hs.items() : for h in hs: if h in train_set: if w not in w2ts: w2ts[w] = [] if h not in w2ts[w]: w2ts[w].append(h) for w, ts in w2ts.items() : w2ts[w] = np.array(ts) t2i = {} for i, ...
train_df[['id','text','target']].to_csv('/kaggle/working/train.csv', index=False) test_df[['id','text']].to_csv('/kaggle/working/test.csv', index=False )
Natural Language Processing with Disaster Tweets
7,207,018
class TrainingData(Sequence): def __init__(self, score, steps=1000, batch_size=32): super(TrainingData, self ).__init__() self.score = -score self.steps = steps self.batch_size = batch_size for ts in w2ts.values() : idxs = [t2i[t] for t in ts] for i in idxs: for j in idxs: self.score[ i, j] = 10000.0 self.on_epoch_en...
upload_blob(BUCKET_NAME, '/kaggle/working/train.csv', 'train.csv') upload_blob(BUCKET_NAME, '/kaggle/working/test.csv', 'test.csv' )
Natural Language Processing with Disaster Tweets
7,207,018
def set_lr(model, lr): K.set_value(model.optimizer.lr, float(lr)) def get_lr(model): return K.get_value(model.optimizer.lr) def score_reshape(score, x, y=None): if y is None: m = np.zeros(( x.shape[0], x.shape[0]), dtype=K.floatx()) m[np.triu_indices(x.shape[0], 1)] = score.squeeze() m += m.transpose() else: m = np...
dataset_display_name = 'tweet_disaster_cleaned' new_dataset = False try: dataset = tables_client.get_dataset(dataset_display_name=dataset_display_name) except: new_dataset = True dataset = tables_client.create_dataset(dataset_display_name )
Natural Language Processing with Disaster Tweets
7,207,018
def prepare_submission(threshold, filename): vtop = 0 vhigh = 0 pos = [0, 0, 0, 0, 0, 0] with open(filename, 'wt', newline=' ')as f: f.write('Image,Id ') for i, p in enumerate(tqdm(submit)) : t = [] s = set() a = score[i, :] for j in list(reversed(np.argsort(a))): h = known[j] if a[j] < threshold and new_whale not i...
if new_dataset: gcs_input_uris = ['gs://' + BUCKET_NAME + '/train.csv'] import_data_operation = tables_client.import_data( dataset=dataset, gcs_input_uris=gcs_input_uris ) print('Dataset import_data_operation.result()
Natural Language Processing with Disaster Tweets
7,207,018
histories = [] steps = 0 if isfile('.. /input/piotte/mpiotte-standard.model'): tmp = keras.models.load_model('.. /input/piotte/mpiotte-standard.model') model.set_weights(tmp.get_weights()) tic = time.time() h2ws = {} for p, w in tagged.items() : if w != new_whale: h = p2h[p] if h not in h2ws: h2ws[h] = [] if w not in...
ID_COLUMN = 'id'
Natural Language Processing with Disaster Tweets
7,207,018
score = 0.45*score1 + 0.55*score2<train_model>
TRAIN_BUDGET = 1000 model = None model_display_name = 'tweet_disaster_model_clean' try: model = tables_client.get_model(model_display_name=model_display_name) except: response = tables_client.create_model( model_display_name, dataset=dataset, train_budget_milli_node_hours=TRAIN_BUDGET, exclude_column_spec_names=[TARG...
Natural Language Processing with Disaster Tweets
7,207,018
prepare_submission(0.92, 'submission_0.45_standard_0.55_boostrap.csv') toc = time.time() print("Submission time: ",(toc - tic)/ 60.)<install_modules>
gcs_input_uris = 'gs://' + BUCKET_NAME + '/test.csv' gcs_output_uri_prefix = 'gs://' + BUCKET_NAME + '/predictions' batch_predict_response = tables_client.batch_predict( model=model, gcs_input_uris=gcs_input_uris, gcs_output_uri_prefix=gcs_output_uri_prefix, ) print('Batch prediction operation: {}'.format(batch_pred...
Natural Language Processing with Disaster Tweets
7,207,018
!pip -q install aiohttp faiss-prebuilt pyxtools pymltools !apt -qq install -y libopenblas-base libomp-dev tensorflow.__version__<import_modules>
gcs_output_folder = batch_predict_response.metadata.batch_predict_details.output_info.gcs_output_directory.replace('gs://' + BUCKET_NAME + '/','') download_to_kaggle(BUCKET_NAME,'/kaggle/working','submissions.csv', prefix=gcs_output_folder )
Natural Language Processing with Disaster Tweets
7,207,018
MaxPooling2D show_embedding, keras_convert_model_to_estimator_ckpt, InitFromPretrainedCheckpointHook, \ AbstractEstimator, estimator_iter_process, colab_save_file_func, OptimizerType, tf_model_fn, \ get_wsl_path, map_per_set, LossStepHookForTrain, ProcessMode, load_data_from_h5file, \ store_data_in_h5file, get_triplet_...
preds_df = pd.read_csv("/kaggle/working/submissions.csv") preds_df = preds_df.sort_values(by=['id']) preds_df['target'] =(preds_df['target_1_score'] >= 0.5 ).astype(int )
Natural Language Processing with Disaster Tweets
7,207,018
def combine_csv(file_weight: dict, out_file: str): sub_files = [] sub_weight = [] for csv_file, weight in file_weight.items() : sub_files.append(csv_file) sub_weight.append(weight) place_weights = {} for i in range(5): place_weights[i] = 10 - i * 2 h_label = 'Image' h_target = 'Id' sub = [None] * len(sub_files) for ...
preds_df[['id','target']].to_csv("submission.csv", index=False )
Natural Language Processing with Disaster Tweets
7,207,018
class WhaleRankingUtils(object): def __init__(self, data_utils: WhaleDataUtils, top_k: int = 5): self.logger = logging.getLogger(self.__class__.__name__) self.top_k = top_k self.data_utils = data_utils def simple_rank(self, result_list: list, distance_cutoff: float = None, only_distance_fit: bool = False)-> list: _c...
tfidf_vectorizer = feature_extraction.text.TfidfVectorizer(ngram_range =(1,2), stop_words='english',strip_accents='unicode' )
Natural Language Processing with Disaster Tweets
7,207,018
class TripletLossModelCNN(AbstractEstimator): def __init__(self, train_ckpt_dir, data_utils: WhaleDataUtils, timeout: int = int(3600 * 5), pretrained_ckpt_file: str = None): super(TripletLossModelCNN, self ).__init__( model_name="TripletLoss", train_ckpt_dir=train_ckpt_dir, pretrained_ckpt_file=pretrained_ckpt_file )...
train_vectors = tfidf_vectorizer.fit_transform(train_df["text"]) test_vectors = tfidf_vectorizer.transform(test_df["text"] )
Natural Language Processing with Disaster Tweets
7,207,018
!mkdir -p./keras !cp.. /input/piotte/mpiotte-standard.model./keras/ !cp.. /input/whale-triplet-pretrained-model/tripletk/tripletK triplet -R init_logger() path_manager = PathManager("kaggle") data_utils = WhaleDataUtils(path_manager=path_manager, gen_data_setting={ "x_train_num": 4, "ignore_blank_prob": 0.9, "ignore_s...
feature_cols = ['keyword', 'location'] X = train_df[feature_cols] y = train_df.target one_hot_encoded_training_predictors = pd.get_dummies(X) clf = RandomForestClassifier(n_estimators = 100) scores = model_selection.cross_val_score(clf, one_hot_encoded_training_predictors, y, cv=5, scoring="f1") scores
Natural Language Processing with Disaster Tweets
7,207,018
estimator.show_predict_result(count=10, top_k=5) estimator.show_predict_result(count=20, top_k=3) <install_modules>
clf.fit(one_hot_encoded_training_predictors, y )
Natural Language Processing with Disaster Tweets
7,207,018
!rm *.pkl !rm./keras/ -R !pip uninstall aiohttp faiss-prebuilt pyxtools pymltools -y !apt remove -y libopenblas-base libomp-dev <import_modules>
clf = linear_model.RidgeClassifier()
Natural Language Processing with Disaster Tweets
7,207,018
from keras.layers import Dense, Flatten, Dropout, Lambda, Input, Concatenate, concatenate from keras.models import Model from keras.applications import * from keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split ...
scores = model_selection.cross_val_score(clf, train_vectors, train_df["target"], cv=10, scoring="f1") scores
Natural Language Processing with Disaster Tweets
7,207,018
filenames = os.listdir(".. /input/train/train") labels = [] for file in filenames: category = file.split('.')[0] if category == 'cat': labels.append('cat') else: labels.append('dog' )<split>
clf.fit(train_vectors, train_df["target"] )
Natural Language Processing with Disaster Tweets
7,207,018
df = pd.DataFrame({ 'filename': filenames, 'label': labels }) train_df, validation_df = train_test_split(df, test_size=0.1, random_state = 42) train_df = train_df.reset_index(drop=True) validation_df = validation_df.reset_index(drop=True) <define_variables>
parameters = { 'gamma': [0.7, 1, 'auto', 'scale'] } clf = GridSearchCV(SVC(kernel='rbf'), parameters, cv=5, n_jobs=-1, scoring="f1" ).fit(train_vectors, train_df["target"] )
Natural Language Processing with Disaster Tweets
7,207,018
batch_size = 64 train_num = len(train_df) validation_num = len(validation_df )<create_dataframe>
clf.best_estimator_
Natural Language Processing with Disaster Tweets
7,207,018
def two_image_generator(generator, df, directory, batch_size, x_col = 'filename', y_col = None, model = None, shuffle = False, img_size1 =(224, 224), img_size2 =(299,299)) : gen1 = generator.flow_from_dataframe( df, directory, x_col = x_col, y_col = y_col, target_size = img_size1, class_mode = model, batch_size = batc...
clf.best_score_
Natural Language Processing with Disaster Tweets
7,207,018
<load_pretrained>
sample_submission = pd.read_csv("/kaggle/input/nlp-getting-started/sample_submission.csv") sample_submission["target"] = clf.predict(test_vectors) df = pd.DataFrame({'text' : test_df['text'], 'prediction' : sample_submission["target"]} )
Natural Language Processing with Disaster Tweets
7,207,018
train_aug_datagen = ImageDataGenerator( rotation_range = 20, shear_range = 0.1, zoom_range = 0.2, width_shift_range = 0.1, height_shift_range = 0.1, horizontal_flip = True ) train_generator = two_image_generator(train_aug_datagen, train_df, '.. /input/train/train/', batch_size = batch_size, y_col = 'label', model = ...
sample_submission.to_csv("submission1.csv", index=False )
Natural Language Processing with Disaster Tweets
7,207,018
validation_datagen = ImageDataGenerator() validation_generator = two_image_generator(validation_datagen, validation_df, '.. /input/train/train/', batch_size = batch_size, y_col = 'label',model = 'binary', shuffle = True )<choose_model_class>
print(tf.__version__)
Natural Language Processing with Disaster Tweets
7,207,018
def create_base_model(MODEL, img_size, lambda_fun = None): inp = Input(shape =(img_size[0], img_size[1], 3)) x = inp if lambda_fun: x = Lambda(lambda_fun )(x) base_model = MODEL(input_tensor = x, weights = 'imagenet', include_top = False, pooling = 'avg') model = Model(inp, base_model.output) return model<choose_mod...
X = train_df["text"] y = train_df["target"] X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.3, random_state=42 )
Natural Language Processing with Disaster Tweets
7,207,018
model1 = create_base_model(vgg16.VGG16,(224, 224), vgg16.preprocess_input) model2 = create_base_model(resnet50.ResNet50,(224, 224), resnet50.preprocess_input) model3 = create_base_model(inception_v3.InceptionV3,(299, 299), inception_v3.preprocess_input) model1.trainable = False model2.trainable = False model3.traina...
vocab_size = 10000 embedding_dim = 16 max_length = 30 trunc_type='post' padding_type='post' oov_tok = "<OOV>"
Natural Language Processing with Disaster Tweets
7,207,018
checkpointer = ModelCheckpoint(filepath='dogcat.weights.best.hdf5', verbose=1, save_best_only=True, save_weights_only=True )<train_model>
tokenizer = Tokenizer(num_words = vocab_size, oov_token=oov_tok) tokenizer.fit_on_texts(X_train) word_index = tokenizer.word_index sequences = tokenizer.texts_to_sequences(X_train) padded = pad_sequences(sequences,maxlen=max_length, padding=padding_type, truncating=trunc_type) testing_sequences = tokenizer.texts_to...
Natural Language Processing with Disaster Tweets
7,207,018
multiple_pretained_model.fit_generator( train_generator, epochs = 5, steps_per_epoch = train_num // batch_size, validation_data = validation_generator, validation_steps = validation_num // batch_size, verbose = 1, callbacks = [checkpointer] )<load_pretrained>
reverse_word_index = dict([(value, key)for(key, value)in word_index.items() ]) def decode_sentence(text): return ' '.join([reverse_word_index.get(i, '?')for i in text]) print(decode_sentence(padded[0]))
Natural Language Processing with Disaster Tweets
7,207,018
multiple_pretained_model.load_weights('dogcat.weights.best.hdf5' )<define_variables>
!wget --no-check-certificate \ https://storage.googleapis.com/laurencemoroney-blog.appspot.com/glove.6B.100d.txt \ -O /tmp/glove.6B.100d.txt embeddings_index = {}; vocab_size=len(word_index) embedding_dim = 100 with open('/tmp/glove.6B.100d.txt')as f: for line in f: values = line.split() ; word = values[0]; coefs = np...
Natural Language Processing with Disaster Tweets
7,207,018
test_filenames = os.listdir(".. /input/test/test") test_df = pd.DataFrame({ 'filename': test_filenames }) num_test = len(test_df) test_datagen = ImageDataGenerator() test_generator = two_image_generator(test_datagen, test_df, '.. /input/test/test/', batch_size = batch_size )<predict_on_test>
model = tf.keras.Sequential([ tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_length), tf.keras.layers.GlobalAveragePooling1D() , tf.keras.layers.Dense(24, activation='relu'), tf.keras.layers.Dense(1, activation='sigmoid') ]) model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['ac...
Natural Language Processing with Disaster Tweets
7,207,018
prediction = multiple_pretained_model.predict_generator(test_generator, steps=np.ceil(num_test/batch_size)) prediction = prediction.clip(min = 0.005, max = 0.995 )<save_to_csv>
num_epochs = 3 history = model.fit(padded, y_train, epochs=num_epochs, validation_data=(testing_padded, y_val))
Natural Language Processing with Disaster Tweets
7,207,018
submission_df = pd.read_csv('.. /input/sample_submission.csv') for i, fname in enumerate(test_filenames): index = int(fname[fname.rfind('/')+1:fname.rfind('.')]) submission_df.at[index-1, 'label'] = prediction[i] submission_df.to_csv('submission.csv', index=False )<import_modules>
model_loss = pd.DataFrame(model.history.history) model_loss.head()
Natural Language Processing with Disaster Tweets
7,207,018
import numpy as np import pandas as pd import os from fastai.vision import *<define_variables>
testing_sequences2 = tokenizer.texts_to_sequences(test_df.text) testing_padded2 = pad_sequences(testing_sequences2, maxlen=max_length, padding=padding_type, truncating=trunc_type )
Natural Language Processing with Disaster Tweets
7,207,018
path = Path('.. /input' )<set_options>
probabilities = model.predict(testing_padded2 )
Natural Language Processing with Disaster Tweets
7,207,018
path.ls()<define_variables>
predictions =(probabilities > 0.5 ).astype(int) predictions = np.ndarray.flatten(predictions) pd.value_counts(predictions )
Natural Language Processing with Disaster Tweets
7,207,018
path_img = path/'train'<features_selection>
original_test_df = pd.read_csv("/kaggle/input/nlp-getting-started/test.csv") df = pd.DataFrame({'text' : original_test_df['text'],'cleaned_text' : test_df['text'], 'prediction' : predictions,'probabilities' : np.ndarray.flatten(probabilities)}) df.to_csv("test_df.csv", index=False )
Natural Language Processing with Disaster Tweets
7,207,018
get_image_files(path_img)[:5]<define_variables>
sample_submission = pd.read_csv("/kaggle/input/nlp-getting-started/sample_submission.csv") sample_submission["target"] = predictions sample_submission.to_csv("submission.csv", index=False )
Natural Language Processing with Disaster Tweets
7,207,018
np.random.seed(42) size = 224 bs = 64 num_workers = 0 pat = r'/([^/.]+ ).\d+.jpg$'<categorify>
import tensorflow_hub as hub import lightgbm as lgb from lightgbm import LGBMClassifier
Natural Language Processing with Disaster Tweets
7,207,018
tfms = get_transforms() data =(ImageItemList.from_folder(path_img) .random_split_by_pct() .label_from_re(pat) .add_test_folder('.. /test') .transform(tfms, size=size) .databunch(bs=bs, num_workers=num_workers) .normalize(imagenet_stats))<define_variables>
module_url = "https://tfhub.dev/google/nnlm-en-dim128/2" embed = hub.KerasLayer(module_url) embeddings = embed(["A long sentence.", "single-word", "http://example.com"]) print(embeddings.shape )
Natural Language Processing with Disaster Tweets
7,207,018
data.show_batch(rows=3, figsize=(7,6))<choose_model_class>
embed = hub.load("https://tfhub.dev/google/universal-sentence-encoder/3" )
Natural Language Processing with Disaster Tweets
7,207,018
learn = create_cnn(data, models.resnet50, metrics=accuracy, model_dir='/tmp/models' )<train_model>
X_train_embeddings = embed(train_df.text.values) X_test_embeddings = embed(test_df.text.values )
Natural Language Processing with Disaster Tweets
7,207,018
learn.fit_one_cycle(4 )<save_model>
params = { 'learning_rate': 0.04, 'n_estimators': 1500, 'colsample_bytree': 0.4, 'metric':'auc' }
Natural Language Processing with Disaster Tweets
7,207,018
learn.save('stage-1' )<train_model>
text_clf = LGBMClassifier(**params )
Natural Language Processing with Disaster Tweets
7,207,018
learn.fit_one_cycle(2, max_lr=slice(1e-6,1e-4))<save_model>
text_clf.fit(X_train_embeddings['outputs'][:5000,:], train_df.target.values[:5000], eval_set=[(X_train_embeddings['outputs'][:5000,:], train_df.target.values[:5000]), (X_train_embeddings['outputs'][5000:,:], train_df.target.values[5000:])], verbose=200, early_stopping_rounds=20, )
Natural Language Processing with Disaster Tweets
7,207,018
learn.save('stage-2' )<find_best_params>
text_clf.fit(X_train_embeddings['outputs'][:5000,:], train_df.target.values[:5000]) Y_pred = text_clf.predict(X_train_embeddings['outputs'][5000:] )
Natural Language Processing with Disaster Tweets
7,207,018
interp = ClassificationInterpretation.from_learner(learn) losses,idxs = interp.top_losses() len(data.valid_ds)==len(losses)==len(idxs )<predict_on_test>
print(metrics.classification_report(train_df.target[5000:], Y_pred, digits=3),) print(metrics.confusion_matrix(train_df.target[5000:], Y_pred))
Natural Language Processing with Disaster Tweets
7,207,018
preds, y = learn.get_preds(ds_type=DatasetType.Test )<prepare_output>
text_clf.fit(X_train_embeddings['outputs'], train_df.target.values) pred_test = text_clf.predict(X_test_embeddings['outputs'] )
Natural Language Processing with Disaster Tweets
7,207,018
dog_preds = preds[:,1]<create_dataframe>
df = pd.DataFrame({'cleaned_text' : test_df['text'], 'prediction' : pred_test}) df.head(20 )
Natural Language Processing with Disaster Tweets
7,207,018
<feature_engineering><EOS>
sample_submission = pd.read_csv("/kaggle/input/nlp-getting-started/sample_submission.csv") sample_submission["target"] = pred_test sample_submission.to_csv("submission.csv", index=False )
Natural Language Processing with Disaster Tweets
7,384,080
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<data_type_conversions>
!wget --quiet https://raw.githubusercontent.com/tensorflow/models/master/official/nlp/bert/tokenization.py
Natural Language Processing with Disaster Tweets
7,384,080
submission['id'] = submission['id'].astype(int )<sort_values>
BASE_PATH = "/kaggle/input/nlp-getting-started/"
Natural Language Processing with Disaster Tweets
7,384,080
submission = submission.sort_values('id' )<save_to_csv>
train =pd.read_csv(BASE_PATH + "train.csv") train.head()
Natural Language Processing with Disaster Tweets
7,384,080
submission.to_csv('submission.csv', index=False )<save_to_csv>
test =pd.read_csv(BASE_PATH + "test.csv") test.head()
Natural Language Processing with Disaster Tweets
7,384,080
submission.to_csv('submission.csv', index=False )<define_variables>
%%time module_url = "https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/1" bert_layer = hub.KerasLayer(module_url, trainable=True )
Natural Language Processing with Disaster Tweets
7,384,080
labels=['dog','cat']<define_variables>
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