kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
10,981,838
def custom_loss(y_true, y_pred): loss = tf.keras.losses.categorical_crossentropy(y_true, y_pred, from_logits = False, label_smoothing = 0.20) loss = tf.reduce_mean(loss) return loss<load_pretrained>
SEED = 42 NUM_SPLITS = 10 NUM_TRIALS = 100
Natural Language Processing with Disaster Tweets
10,981,838
def build_model() : ids = tf.keras.layers.Input(( max_len,), dtype=tf.int32) att = tf.keras.layers.Input(( max_len,), dtype=tf.int32) tok = tf.keras.layers.Input(( max_len,), dtype=tf.int32) config_path = RobertaConfig.from_pretrained('/kaggle/input/tf-roberta/config-roberta-base.json') roberta_model = TFRobertaMod...
os.environ['PYTHONHASHSEED']=str(SEED) random.seed(SEED) np.random.seed(SEED )
Natural Language Processing with Disaster Tweets
10,981,838
tot_test_tw = test_data.shape[0] input_ids_t = np.ones(( tot_test_tw,max_len), dtype='int32') attention_mask_t = np.zeros(( tot_test_tw,max_len), dtype='int32') token_type_ids_t = np.zeros(( tot_test_tw,max_len), dtype='int32') for i in range(tot_test_tw): set1 = " "+" ".join(test_data.loc[i,'text'].split()) enc_se...
train = pd.read_csv(".. /input/nlp-getting-started/train.csv") test = pd.read_csv(".. /input/nlp-getting-started/test.csv" )
Natural Language Processing with Disaster Tweets
10,981,838
pred_start= np.zeros(( input_ids_t.shape[0],max_len)) pred_end= np.zeros(( input_ids_t.shape[0],max_len)) for i in range(2): print('--'*20) print('-- MODEL %i --'%(i+1)) print('--'*20) K.clear_session() model = build_model() model.load_weights('/kaggle/input/model4/v4-roberta-%i.h5'%(i+3)) pred = model.predict([input...
test["target"] = -1 df = pd.concat([train, test] )
Natural Language Processing with Disaster Tweets
10,981,838
all = [] for k in range(input_ids_t.shape[0]): a = np.argmax(pred_start[k,]) b = np.argmax(pred_end[k,]) if a>b: st = test_data.loc[k,'text'] else: text1 = " "+" ".join(test_data.loc[k,'text'].split()) enc = tokenizer.encode(text1) st = tokenizer.decode(enc.ids[a-1:b]) all.append(st) test_data['selected_text']=al...
print("NaN Distribution ") for col in df.columns: print(f"{col}: {(( df[col].isna().sum() /df.shape[0])*100):.2f}" )
Natural Language Processing with Disaster Tweets
10,981,838
test_data[['textID','selected_text']].to_csv('submission.csv', index=False) print("Submission successful" )<load_from_csv>
df["text"] = df["text"].str.lower()
Natural Language Processing with Disaster Tweets
10,981,838
train_data = pd.read_csv('/kaggle/input/tweet-sentiment-extraction/train.csv') test_data = pd.read_csv('/kaggle/input/tweet-sentiment-extraction/test.csv') print('Train Dataset') print(train_data.head()) print('Test Dataset') print(test_data.head() )<feature_engineering>
PUNCT_TO_REMOVE = string.punctuation def remove_punctuation(text): return text.translate(str.maketrans('', '', PUNCT_TO_REMOVE)) df["text"] = df["text"].apply(lambda text: remove_punctuation(text))
Natural Language Processing with Disaster Tweets
10,981,838
train_data.dropna(axis = 0,inplace=True) def remove_punctuation(text): no_punct = "".join([c for c in text if c not in string.punctuation]) return no_punct train_data['s_text_clean'] = train_data['selected_text'].apply(str ).apply(lambda x: remove_punctuation(x.lower())) tokenizer = RegexpTokenizer(r'\w+') train_dat...
def remove_emoji(text): emoji_pattern = re.compile("[" u"\U0001F600-\U0001F64F" u"\U0001F300-\U0001F5FF" u"\U0001F680-\U0001F6FF" u"\U0001F1E0-\U0001F1FF" u"\U00002702-\U000027B0" u"\U000024C2-\U0001F251" "]+", flags=re.UNICODE) return emoji_pattern.sub(r'', text) df["text"] = df["text"].apply(lambda text: remove_emo...
Natural Language Processing with Disaster Tweets
10,981,838
max_len = 150 tokenizer = tokenizers.ByteLevelBPETokenizer( vocab_file = '/kaggle/input/roberta/vocab-roberta-base.json', merges_file = '/kaggle/input/roberta/merges-roberta-base.txt', lowercase =True, add_prefix_space=True ) sentiment_id = {'positive':tokenizer.encode('positive' ).ids[0], 'negative':tokenizer.encod...
def remove_urls(text): url_pattern = re.compile(r'https?://\S+|www\.\S+') try: return url_pattern.sub(r'', text) except: print(text) df["text"] = df["text"].apply(lambda text: remove_urls(text))
Natural Language Processing with Disaster Tweets
10,981,838
def custom_loss(y_true, y_pred): loss = tf.keras.losses.categorical_crossentropy(y_true, y_pred, from_logits = False, label_smoothing = 0.2) loss = tf.reduce_mean(loss) return loss<load_pretrained>
def remove_html(text): html_pattern = re.compile('<.*?>') return html_pattern.sub(r'', text) df["text"] = df["text"].apply(lambda text: remove_html(text))
Natural Language Processing with Disaster Tweets
10,981,838
os.environ['WANDB_MODE'] = 'dryrun' def build_model() : ids = tf.keras.layers.Input(( max_len,), dtype=tf.int32) att = tf.keras.layers.Input(( max_len,), dtype=tf.int32) tok = tf.keras.layers.Input(( max_len,), dtype=tf.int32) config_path = RobertaConfig.from_pretrained('/kaggle/input/roberta/config-roberta-base.jso...
with open(".. /input/slangtext/slang.txt", "r")as file: chat_words_str = file.read() chat_words_map_dict = {} chat_words_list = [] for line in chat_words_str.split(" "): if line != "" and "=" in line: cw = line.split("=")[0] cw_expanded = line.split("=")[1] chat_words_list.append(cw) chat_words_map_dict[cw] = cw_expan...
Natural Language Processing with Disaster Tweets
10,981,838
test_shape = test_data.shape[0] input_ids_t = np.ones(( test_shape,max_len), dtype='int32') attention_mask_t = np.zeros(( test_shape,max_len), dtype='int32') token_type_ids_t = np.zeros(( test_shape,max_len), dtype='int32') for i in range(test_shape): set1 = " "+" ".join(test_data.loc[i,'text'].split()) enc_set1 = ...
def chat_words_conversion(text): new_text = [] for w in text.split() : if w.upper() in chat_words_list: new_text.append(chat_words_map_dict[w.upper() ]) else: new_text.append(w) return " ".join(new_text) df["text"] = df["text"].apply(lambda text: chat_words_conversion(text))
Natural Language Processing with Disaster Tweets
10,981,838
preds_start= np.zeros(( input_ids_t.shape[0],max_len)) preds_end= np.zeros(( input_ids_t.shape[0],max_len)) model = build_model() model.load_weights('/kaggle/input/roberta/v4-roberta-4.h5') pred = model.predict([input_ids_t,attention_mask_t,token_type_ids_t],verbose=1) pred_start = pred[0] pred_end = pred[1] all = []...
spell = SpellChecker() def correct_spellings(text): corrected_text = [] misspelled_words = spell.unknown(text.split()) for word in text.split() : if word in misspelled_words: corrected_text.append(spell.correction(word)) else: corrected_text.append(word) return " ".join(corrected_text) df["text"] = df["text"].apply(...
Natural Language Processing with Disaster Tweets
10,981,838
test_data[['textID','selected_text']].to_csv('submission.csv', index=False )<import_modules>
class NBSVMClassifier(BaseEstimator, ClassifierMixin): def __init__(self, C=1.0, max_iter=100, dual=False, n_jobs=1): self.C = C self.dual = dual self.n_jobs = n_jobs self.max_iter = max_iter def predict(self, x): check_is_fitted(self, ['_r', '_clf']) return self._clf.predict(x.multiply(self._r)) def fit(self, x, y): ...
Natural Language Processing with Disaster Tweets
10,981,838
from transformers import AutoModelForQuestionAnswering, AutoModel, AutoConfig, get_linear_schedule_with_warmup from transformers.optimization import AdamW import torch import torch.nn as nn import torch.nn.functional as F import pandas as pd import numpy as np from pathlib import Path import os from itertools import co...
X_train, X_valid, y_train, y_valid = train_test_split(train["text"], train["target"], test_size=0.2, random_state=SEED, stratify=train["target"] )
Natural Language Processing with Disaster Tweets
10,981,838
from torch.utils.data import DataLoader from functools import partial from tokenizers import BertWordPieceTokenizer from sklearn.model_selection import train_test_split from tqdm import tqdm from fastai.core import * from fastai.text import *<load_from_csv>
vec = TfidfVectorizer(ngram_range=(1,2), min_df=3, max_df=0.9, strip_accents='unicode', use_idf=1, smooth_idf=1, sublinear_tf=1 )
Natural Language Processing with Disaster Tweets
10,981,838
file_dir, electra_dir = [Path(f'/kaggle/input/{i}')for i in ['tweet-sentiment-extraction', 'electrabase']] train_df = pd.read_csv(file_dir/'train.csv') train_df['text'] = train_df['text'].apply(lambda x: str(x)) train_df['sentiment'] = train_df['sentiment'].apply(lambda x: str(x)) train_df['selected_text'] = train_df[...
def objective(trial): C = trial.suggest_float(name="C", low=1e-3, high=1e3, log=True) max_iter = trial.suggest_discrete_uniform(name="max_iter", low=50, high=500, q=50) nbsvm = NBSVMClassifier(C=C, max_iter=max_iter) train_term_doc = vec.fit_transform(X_train) valid_term_doc = vec.transform(X_valid) nbsvm.fit(trai...
Natural Language Processing with Disaster Tweets
10,981,838
max_len = 128 bs = 64 tokenizer = BertWordPieceTokenizer(str(electra_dir/'vocab.txt'), lowercase=True )<categorify>
study = optuna.create_study(direction="maximize") study.optimize(objective, n_trials=NUM_TRIALS, show_progress_bar=True )
Natural Language Processing with Disaster Tweets
10,981,838
def preprocess(sentiment, tweet, selected, tokenizer, max_len): _input = tokenizer.encode(sentiment, tweet) _span = tokenizer.encode(selected, add_special_tokens=False) len_span = len(_span.ids) start_idx = None end_idx = None for ind in(i for i, e in enumerate(_input.ids)if e == _span.ids[0]): if _input.ids[ind: in...
print(f"Best Value: {study.best_trial.value}") print(f"Best Params: {study.best_params}" )
Natural Language Processing with Disaster Tweets
10,981,838
def reduce_loss(loss, reduction='mean'): return loss.mean() if reduction=='mean' else loss.sum() if reduction=='sum' else loss class LabelSmoothingCrossEntropy(nn.Module): def __init__(self, ε:float=0.1, reduction='mean'): super().__init__() self.ε,self.reduction = ε,reduction def forward(self, output, target): c = out...
kwargs = study.best_params
Natural Language Processing with Disaster Tweets
10,981,838
class TweetDataset(Dataset): def __init__(self, dataset, test = None): self.df = dataset self.test = test def __getitem__(self, idx): if not self.test: sentiment, tweet, selected =(self.df[col][idx] for col in ['sentiment', 'text', 'selected_text']) _input = preprocess(sentiment, tweet, selected, tokenizer, max_len) ...
train = df[df['target']!=-1] test = df[df['target']==-1]
Natural Language Processing with Disaster Tweets
10,981,838
pt_model = AutoModel.from_pretrained(electra_dir )<init_hyperparams>
def print_metrics(y_true, y_pred): print(f"Accuracy: {accuracy_score(y_true, y_pred)}") print(f"MCC: {matthews_corrcoef(y_true, y_pred)}") print(f"F1: {f1_score(y_true, y_pred)} " )
Natural Language Processing with Disaster Tweets
10,981,838
class SpanModel(nn.Module): def __init__(self,pt_model): super().__init__() self.model = pt_model self.drop_out = nn.Dropout(0.5) self.qa_outputs1c = torch.nn.Conv1d(768*2, 128, 2) self.qa_outputs2c = torch.nn.Conv1d(768*2, 128, 2) self.qa_outputs1 = nn.Linear(128, 1) self.qa_outputs2 = nn.Linear(128, 1) def forwa...
final_preds = np.zeros(( len(test))) kfold = StratifiedKFold(n_splits=NUM_SPLITS, shuffle=True, random_state=SEED) for fold,(train_index, valid_index)in enumerate(kfold.split(train["text"], train["target"])) : print("*"*60) print("*"+" "*26+f"FOLD {fold+1}"+" "*26+"*") print("*"*60, end=" ") X_train = train.iloc[t...
Natural Language Processing with Disaster Tweets
10,981,838
class CELoss(Module): def __init__(self, loss_fn = nn.CrossEntropyLoss()): self.loss_fn = loss_fn def forward(self, inputs, start_targets, end_targets): start_logits, end_logits = inputs logits = torch.cat([start_logits, end_logits] ).contiguous() targets = torch.cat([start_targets, end_targets] ).contiguous() return s...
submission = pd.read_csv(".. /input/nlp-getting-started/sample_submission.csv" )
Natural Language Processing with Disaster Tweets
10,981,838
def jaccard(str1, str2): a = set(str1.lower().split()) b = set(str2.lower().split()) c = a.intersection(b) return float(len(c)) /(len(a)+ len(b)- len(c))<init_hyperparams>
submission["target"] = final_preds/NUM_SPLITS submission["target"] = submission["target"].apply(lambda x: 1 if x>=0.5 else 0 )
Natural Language Processing with Disaster Tweets
10,981,838
class JaccardScore(Callback): "Stores predictions and targets to perform calculations on epoch end." def __init__(self, valid_ds): self.valid_ds = valid_ds self.context_text = valid_ds.df.text self.answer_text = valid_ds.df.selected_text def on_epoch_begin(self, **kwargs): self.jaccard_scores = [] self.valid_ds_idx = 0...
submission.to_csv("submission.csv", index=False )
Natural Language Processing with Disaster Tweets
10,981,838
<categorify><EOS>
submission.to_csv("submission.csv", index=False )
Natural Language Processing with Disaster Tweets
10,879,039
<save_to_csv><EOS>
!pip install --upgrade transformers simpletransformers train_data = pd.read_csv('.. /input/nlp-with-disaster-tweets-cleaning-data/train_data_cleaning.csv')[['text', 'target']] test_data = pd.read_csv('.. /input/nlp-with-disaster-tweets-cleaning-data/test_data_cleaning.csv')[['id','text']] model = ClassificationModel('d...
Natural Language Processing with Disaster Tweets
10,637,925
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<set_options>
!pip install tweet-preprocessor
Natural Language Processing with Disaster Tweets
10,637,925
warnings.filterwarnings('ignore' )<set_options>
for dirname, _, filenames in os.walk('/kaggle/input'): for filename in filenames: print(os.path.join(dirname, filename))
Natural Language Processing with Disaster Tweets
10,637,925
def seed_everything(seed_value): random.seed(seed_value) np.random.seed(seed_value) torch.manual_seed(seed_value) os.environ['PYTHONHASHSEED'] = str(seed_value) if torch.cuda.is_available() : torch.cuda.manual_seed(seed_value) torch.cuda.manual_seed_all(seed_value) torch.backends.cudnn.deterministic = True torch....
tf.random.set_seed(123) np.random.seed(123 )
Natural Language Processing with Disaster Tweets
10,637,925
class TweetDataset(torch.utils.data.Dataset): def __init__(self, df, max_len=96): self.df = df self.max_len = max_len self.labeled = 'selected_text' in df self.tokenizer = tokenizers.ByteLevelBPETokenizer( vocab_file='.. /input/roberta-base/vocab.json', merges_file='.. /input/roberta-base/merges.txt', lowercase=True, ...
start_time = time.time()
Natural Language Processing with Disaster Tweets
10,637,925
class TweetModel(nn.Module): def __init__(self): super(TweetModel, self ).__init__() config = RobertaConfig.from_pretrained( '.. /input/roberta-base/config.json', output_hidden_states=True) self.roberta = RobertaModel.from_pretrained( '.. /input/roberta-base/pytorch_model.bin', config=config) self.dropout = nn.Drop...
train = pd.read_csv('/kaggle/input/nlp-getting-started/train.csv') test = pd.read_csv('/kaggle/input/nlp-getting-started/test.csv' )
Natural Language Processing with Disaster Tweets
10,637,925
def loss_fn(start_logits, end_logits, start_positions, end_positions): ce_loss = nn.CrossEntropyLoss() start_loss = ce_loss(start_logits, start_positions) end_loss = ce_loss(end_logits, end_positions) total_loss = start_loss + end_loss return total_loss<statistical_test>
def jaccard(str1, str2): a = set(str(str1 ).lower().split()) b = set(str(str2 ).lower().split()) c = a.intersection(b) return round(float(len(c)) /(len(a)+ len(b)- len(c)) , 4 )
Natural Language Processing with Disaster Tweets
10,637,925
def get_selected_text(text, start_idx, end_idx, offsets): selected_text = "" for ix in range(start_idx, end_idx + 1): selected_text += text[offsets[ix][0]: offsets[ix][1]] if(ix + 1)< len(offsets)and offsets[ix][1] < offsets[ix + 1][0]: selected_text += " " return selected_text def jaccard(str1, str2): a = set(str1.low...
results_jaccard = [] for index, row in train.iterrows() : sentence1 = row.keyword sentence2 = row.text jaccard_score = jaccard(sentence1, sentence2) results_jaccard.append([sentence1, sentence2, jaccard_score] )
Natural Language Processing with Disaster Tweets
10,637,925
def train_model(model, dataloaders_dict, criterion, optimizer, num_epochs, filename): model.cuda() for epoch in range(num_epochs): for phase in ['train', 'val']: if phase == 'train': model.train() else: model.eval() epoch_loss = 0.0 epoch_jaccard = 0.0 for data in(dataloaders_dict[phase]): ids = data['ids'].cuda() mask...
jaccard_score = pd.DataFrame(results_jaccard, columns=['keyword', 'text', 'jaccard_score'] )
Natural Language Processing with Disaster Tweets
10,637,925
num_epochs = 3 batch_size = 32 skf = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed )<load_from_csv>
stopwords_en = stopwords.words('english' )
Natural Language Processing with Disaster Tweets
10,637,925
%%time train_df = pd.read_csv('.. /input/tweet-sentiment-extraction/train.csv') train_df['text'] = train_df['text'].astype(str) train_df['selected_text'] = train_df['selected_text'].astype(str) for fold,(train_idx, val_idx)in enumerate(skf.split(train_df, train_df.sentiment), start=1): print(f'Fold: {fold}') model ...
def unicode_to_ascii(s): return ''.join(c for c in unicodedata.normalize('NFD', s)if unicodedata.category(c)!= 'Mn' )
Natural Language Processing with Disaster Tweets
10,637,925
%%time test_df = pd.read_csv('.. /input/tweet-sentiment-extraction/test.csv') test_df['text'] = test_df['text'].astype(str) test_loader = get_test_loader(test_df) predictions = [] models = [] for fold in range(skf.n_splits): model = TweetModel() model.cuda() model.load_state_dict(torch.load(f'roberta_fold{fold+1}.pt...
twitter_p.set_options(twitter_p.OPT.URL) def preprocess_sentence(w): w = twitter_p.clean(w) w = unicode_to_ascii(w.lower().strip()) w = re.sub(r"([@ w = re.sub(r'[" "]+', " ", w) w = re.sub(r"[^a-zA-Z@ w = ' '.join([word for word in w.split(' ')if word not in stopwords_en]) w = w.rstrip().strip() return w
Natural Language Processing with Disaster Tweets
10,637,925
sub_df = pd.read_csv('.. /input/tweet-sentiment-extraction/sample_submission.csv') sub_df['selected_text'] = predictions sub_df['selected_text'] = sub_df['selected_text'].apply(lambda x: x.replace('!!!!', '!')if len(x.split())==1 else x) sub_df['selected_text'] = sub_df['selected_text'].apply(lambda x: x.replace('.. ...
train['text'] = train['text'].apply(func=preprocess_sentence) train['keyword'] = train['keyword'].apply(func=preprocess_sentence) print(train.head(10))
Natural Language Processing with Disaster Tweets
10,637,925
warnings.filterwarnings('ignore' )<set_options>
test['text'] = test['text'].apply(func=preprocess_sentence) test['keyword'] = test['keyword'].apply(func=preprocess_sentence) print(test.head(10))
Natural Language Processing with Disaster Tweets
10,637,925
cuda_yes = torch.cuda.is_available() print('Cuda is available?', cuda_yes) device = torch.device("cuda:0" if cuda_yes else "cpu") print('Device:', device) <set_options>
text_list = np.stack([*train['text'], *train['keyword'], *test['text'], *test['keyword']]) tokenizer = tf.keras.preprocessing.text.Tokenizer(filters='') tokenizer.fit_on_texts(text_list) print(len(tokenizer.word_index))
Natural Language Processing with Disaster Tweets
10,637,925
def seed_everything(seed_value): random.seed(seed_value) np.random.seed(seed_value) torch.manual_seed(seed_value) os.environ['PYTHONHASHSEED'] = str(seed_value) if torch.cuda.is_available() : torch.cuda.manual_seed(seed_value) torch.cuda.manual_seed_all(seed_value) torch.backends.cudnn.deterministic = True torch....
glove = np.load('/kaggle/input/pickled-glove840b300d-for-10sec-loading/glove.840B.300d.pkl', allow_pickle=True)
Natural Language Processing with Disaster Tweets
10,637,925
class TweetDataset(torch.utils.data.Dataset): def __init__(self, df, max_len=96): self.df = df self.max_len = max_len self.labeled = 'selected_text' in df self.tokenizer = tokenizers.ByteLevelBPETokenizer( vocab_file='.. /input/roberta-base/vocab.json', merges_file='.. /input/roberta-base/merges.txt', lowercase=True, ...
input_vocab_size = len(tokenizer.word_index)+ 3 d_model = 300
Natural Language Processing with Disaster Tweets
10,637,925
class TweetModel(nn.Module): def __init__(self): super(TweetModel, self ).__init__() config = RobertaConfig.from_pretrained( '.. /input/roberta-base/config.json', output_hidden_states=True,num_labels=NUM_LABELS) self.roberta = RobertaModel.from_pretrained( '.. /input/roberta-base/pytorch_model.bin', config=config) ...
ps = PorterStemmer() lc = LancasterStemmer() sb = SnowballStemmer("english" )
Natural Language Processing with Disaster Tweets
10,637,925
def loss_fn(start_logits, end_logits, start_positions, end_positions): ce_loss = nn.CrossEntropyLoss() start_loss = ce_loss(start_logits, start_positions) end_loss = ce_loss(end_logits, end_positions) total_loss = start_loss + end_loss return total_loss<statistical_test>
words = glove.keys() w_rank = {} for i,word in enumerate(words): w_rank[word] = i WORDS = w_rank def words(text): return re.findall(r'\w+', text.lower()) def P(word): "Probability of `word`." return - WORDS.get(word, 0) def correction(word): "Most probable spelling correction for word." return max(candidates(word), k...
Natural Language Processing with Disaster Tweets
10,637,925
def get_selected_text(text, start_idx, end_idx, offsets): selected_text = "" for ix in range(start_idx, end_idx + 1): selected_text += text[offsets[ix][0]: offsets[ix][1]] if(ix + 1)< len(offsets)and offsets[ix][1] < offsets[ix + 1][0]: selected_text += " " return selected_text def jaccard(str1, str2): a = set(str1.low...
def create_embedding_matrix(vectors, to_word_it, inp_vocab_size, d_m, lemma_dict): no_in_vocab = [] matrix = np.random.uniform(low=-1, high=1, size=(inp_vocab_size, d_m)) unknown_vector = np.zeros(( d_m,), dtype=np.float32)- 1 for key, index in to_word_it: word = key try: matrix[index] = vectors[word] continue except K...
Natural Language Processing with Disaster Tweets
10,637,925
def train_model(model, dataloaders_dict, criterion, optimizer, num_epochs, filename): model.to(device) for epoch in range(num_epochs): for phase in ['train', 'val']: if phase == 'train': model.train() else: model.eval() epoch_loss = 0.0 epoch_approx_jaccard = 0.0 epoch_true_jaccard = 0.0 epoch_start_end_loss=0.0 epoch...
print("Spacy NLP...") text_list = pd.concat([train['text'], test['text']]) print(len(tokenizer.word_index)) nlp = spacy.load('en_core_web_lg', disable=['parser','ner','tagger']) nlp.vocab.add_flag(lambda s: s.lower() in spacy.lang.en.stop_words.STOP_WORDS, spacy.attrs.IS_STOP) word_dict = {} word_index = 1 lemma_di...
Natural Language Processing with Disaster Tweets
10,637,925
num_epochs = 3 batch_size = 32 gradient_accumulation_steps = 1 warmup_proportion=0.1 NUM_LABELS=4 skf = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed )<load_from_csv>
embedding_matrix, no_in_vocab = create_embedding_matrix(glove, tokenizer.word_index.items() , input_vocab_size, d_model, lemma_dict) del glove
Natural Language Processing with Disaster Tweets
10,637,925
<feature_engineering>
def inter_section(texts, keywords, niv): niv = set(niv) text_tokenizer = tf.keras.preprocessing.text.Tokenizer(filters='') text_tokenizer.fit_on_texts(np.stack([*texts, *keywords])) vocab = set(text_tokenizer.word_index.keys()) text_in_niv = vocab.intersection(niv) print("vocab:", len(vocab), len(text_in_niv), len(...
Natural Language Processing with Disaster Tweets
10,637,925
%%time test_df = pd.read_csv('.. /input/tweet-sentiment-extraction/test.csv') test_df['text'] = test_df['text'].astype(str) test_loader = get_test_loader(test_df) predictions = [] models = [] model_dir = ".. /input/tweet-sentiment-roberta-pytorch/" for fold in range(skf.n_splits): model = TweetModel() model.to(devic...
inter_section(test['text'], test['keyword'], no_in_vocab )
Natural Language Processing with Disaster Tweets
10,637,925
sub_df = pd.read_csv('.. /input/tweet-sentiment-extraction/sample_submission.csv') sub_df['selected_text'] = predictions sub_df['selected_text'] = sub_df['selected_text'].apply(lambda x: x.replace('!!!!', '!')if len(x.split())==1 else x) sub_df['selected_text'] = sub_df['selected_text'].apply(lambda x: x.replace('.. ...
def incorrect_count(train_texts, test_texts, vocab): vocab = set(vocab) wrong_words = [] for text in train_texts: intersection = set(text.split() ).intersection(vocab) if len(intersection)>0: wrong_words.extend(intersection) train_ww_count = np.asarray(Counter(wrong_words ).most_common()) train_ww_count = np.concat...
Natural Language Processing with Disaster Tweets
10,637,925
%load_ext wurlitzer !ls '.. /input/ashrae-energy-prediction/' !ls '.'<install_modules>
incorrect_count(train['text'], test['text'], no_in_vocab )
Natural Language Processing with Disaster Tweets
10,637,925
!pip install -i https://test.pypi.org/simple/ litemort==0.1.18 print(litemort.__version__) <define_variables>
num_texts =len_sentence(train, 'text' )
Natural Language Processing with Disaster Tweets
10,637,925
isMORT = True isImplicitMerge = True gbm='MORT' if isMORT else 'LGB' use_ucf=True nTargetMeter=4 data_root = '.. /input/ashrae-energy-prediction/' print(f"====== ImplicitMerge={isImplicitMerge} gbm={gbm} ====== " )<categorify>
num_keyword = len_sentence(train, 'keyword' )
Natural Language Processing with Disaster Tweets
10,637,925
def LoadUCF(data_root): ucf_root = '.. /input/ashrae-ucf-spider-and-eda-full-test-labels' ucf_leak_df = pd.read_pickle(f'{ucf_root}/site0.pkl') ucf_leak_df['meter_reading'] = ucf_leak_df.meter_reading_scraped ucf_leak_df.drop(['meter_reading_original', 'meter_reading_scraped'], axis=1, inplace=True) ucf_leak_df.filln...
def texts_to_sequences(byte): char = str(byte, encoding='utf-8') sequences = tokenizer.texts_to_sequences([char]) return np.reshape(sequences,(-1))
Natural Language Processing with Disaster Tweets
10,637,925
class Whether(object): def __init__(self, source, data_root,params=None): self.source = source self.data_root = data_root self.lag_day=[3,72] self.lag_feat_list=[] def TimeAlignment(self,weather_df): print(f"TimeAlignment@{self.source}\tdf{weather_df.shape}...... ") weather_key = ['site_id', 'timestamp'] temp_skeleton...
def text_encode(keyword, lang, target): keyword = texts_to_sequences(keyword.numpy()) lang = [len(tokenizer.word_index), *keyword, len(tokenizer.word_index)+ 1, *texts_to_sequences(lang.numpy()), len(tokenizer.word_index)+2] return lang, target
Natural Language Processing with Disaster Tweets
10,637,925
class ASHRAE_data(object): def __init__(self, source,data_root,building_meta_df,weather_df): self.category_cols = ['building_id', 'site_id', 'primary_use'] self.source = source self.data_root = data_root self.building_meta_df = building_meta_df self.weather_df = weather_df feats_whether =[e for e in list(self.weather_d...
def tf_encode(id_num, keyword, lang, target): lang, target = tf.py_function( text_encode, [keyword, lang, target], [tf.int64, tf.int64]) id_num.set_shape(None) lang.set_shape([None]) target.set_shape([]) return id_num, lang, target
Natural Language Processing with Disaster Tweets
10,637,925
def LoadBuilding(data_root): building_meta_df = pd.read_csv(f'{data_root}/building_metadata.csv') primary_use_list = building_meta_df['primary_use'].unique() primary_use_dict = {key: value for value, key in enumerate(primary_use_list)} print('primary_use_dict: ', primary_use_dict) building_meta_df['primary_use'] = bu...
class EmbeddingLayer(object): def __init__(self): self.kernels = tf.Variable(initial_value=embedding_matrix, trainable=False, name='Embedding_kernels') def __call__(self, x): embeddings = tf.nn.embedding_lookup(params=self.kernels, ids=x) return embeddings
Natural Language Processing with Disaster Tweets
10,637,925
early_stop = 20 verbose_eval = 5 metric = 'l2' num_rounds = 1000; lr = 0.05; bf = 0.3 params = {'num_leaves': 31, 'n_estimators': num_rounds, 'objective': 'regression', 'max_bin': 256, 'learning_rate': lr, "boosting": "gbdt", "bagging_freq": 5, "bagging_fraction": bf, "feature_fraction": 0.9, "metric": metric, "verbose...
def get_angles(pos, i, d_model): angle_rates = 1 / np.power(10000,(2*(i//2)) /np.float32(d_model)) return pos * angle_rates
Natural Language Processing with Disaster Tweets
10,637,925
train_datas = ASHRAE_data("train",data_root,building_meta_df,weather_train_df) print(train_datas.building_mean.shape) print(train_datas.building_mean.head(5))<prepare_x_and_y>
def positional_encoding(postion, d_model): angle_rads = get_angles(np.arange(postion)[:,np.newaxis], np.arange(d_model)[np.newaxis,:], d_model) angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2]) angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2]) pos_encoding = angle_rads[np.newaxis,...] return tf.cast(pos_encoding, dt...
Natural Language Processing with Disaster Tweets
10,637,925
folds = 8 seed = 666 shuffle = False kf = KFold(n_splits=folds, shuffle=shuffle, random_state=seed) cat_features=None meter_models=[] losses=[] for target_meter in range(nTargetMeter): X_train, y_train = train_datas.data_X_y(target_meter) y_valid_pred_total = np.zeros(X_train.shape[0]) gc.collect() print(f'target_me...
def create_padding_mask(seq): seq = tf.cast(tf.math.equal(seq, 0), dtype=tf.float32) return seq[:, tf.newaxis, tf.newaxis, :]
Natural Language Processing with Disaster Tweets
10,637,925
test_datas = ASHRAE_data("test",data_root,building_meta_df,weather_test_df) del train_datas gc.collect() test_df = test_datas.df_base def pred(X_test, models, batch_size=1000000): if isMORT and isImplicitMerge: batch_size=batch_size*10 iterations =(X_test.shape[0] + batch_size -1)// batch_size nSamp = X_test.shape[0] ...
def create_look_ahead_mask(size): mask = 1 - tf.linalg.band_part(tf.ones(( size,size)) , -1, 0) return mask
Natural Language Processing with Disaster Tweets
10,637,925
warnings.filterwarnings('ignore') <load_from_csv>
def scaled_dot_product_attention(q, k, v, mask): matmul_qk = tf.matmul(q, k, transpose_b=True) dk = tf.cast(tf.shape(q)[-1], dtype=tf.float32) scaled_attention_logits = matmul_qk / tf.math.sqrt(dk) if mask is not None: scaled_attention_logits +=(mask * -1e9) attention_weights = tf.nn.softmax(scaled_attention_logits...
Natural Language Processing with Disaster Tweets
10,637,925
test = pd.read_csv('.. /input/ashrae-energy-prediction/test.csv', index_col=0, parse_dates = ['timestamp']) building = pd.read_csv('.. /input/ashrae-energy-prediction/building_metadata.csv', usecols=['site_id', 'building_id'] )<merge>
class MultiHeadAttention(tf.keras.layers.Layer): def __init__(self, num_heads, d_model): super(MultiHeadAttention, self ).__init__() self.num_heads = num_heads self.d_model = d_model assert d_model % num_heads == 0 self.depth = d_model // num_heads self.wq = tf.keras.layers.Dense(units=d_model) self.wk = tf.keras.laye...
Natural Language Processing with Disaster Tweets
10,637,925
test = test.merge(building, left_on = "building_id", right_on = "building_id", how = "left" )<load_from_csv>
def point_wise_feed_forward_network(d_model, dff): return tf.keras.Sequential([ tf.keras.layers.Dense(units=dff, activation='relu'), tf.keras.layers.Dense(units=d_model) ] )
Natural Language Processing with Disaster Tweets
10,637,925
submission_base = pd.read_csv('.. /input/ashrae-kfold-lightgbm-without-leak-1-08/submission.csv', index_col=0 )<create_dataframe>
class EncoderLayer(tf.keras.layers.Layer): def __init__(self, d_model, num_heads, dff, rate): super(EncoderLayer, self ).__init__() self.mha = MultiHeadAttention(num_heads=num_heads, d_model=d_model) self.ffn = point_wise_feed_forward_network(d_model=d_model, dff=dff) self.dropout1 = tf.keras.layers.Dropout(rate=rate...
Natural Language Processing with Disaster Tweets
10,637,925
submission = submission_base.copy()<load_from_csv>
class Encoder(tf.keras.layers.Layer): def __init__(self, num_layers, d_model, num_heads, dff, maximum_position_encoding, rate=0.1): super(Encoder, self ).__init__() self.num_layers = num_layers self.d_model = d_model self.pos_encoding = positional_encoding(maximum_position_encoding, d_model) self.enc_layers = [Encoder...
Natural Language Processing with Disaster Tweets
10,637,925
site_0 = pd.read_csv('.. /input/new-ucf-starter-kernel/submission_ucf_replaced.csv', index_col=0) submission.loc[test[test['site_id']==0].index, 'meter_reading'] = site_0['meter_reading'] del site_0 gc.collect()<load_pretrained>
class OutputLayer(tf.keras.layers.Layer): def __init__(self, units, rate): super(OutputLayer, self ).__init__() self.gapool1d = tf.keras.layers.GlobalAveragePooling1D() self.dense = tf.keras.layers.Dense(units=units, activation='relu') self.final_layer = tf.keras.layers.Dense(units=2) self.dropout = tf.keras.layers.D...
Natural Language Processing with Disaster Tweets
10,637,925
with open('.. /usr/lib/ucl_data_leakage_episode_2/site1.pkl', 'rb')as f: site_1 = pickle.load(f) site_1 = site_1[site_1['timestamp'].dt.year > 2016]<merge>
class TransformerCategorical(tf.keras.Model): def __init__(self, num_layers, d_model, num_heads, dff, maximum_position_encoding, output_units, rate=0.1): super(TransformerCategorical, self ).__init__() self.embedding = EmbeddingLayer() self.encoder = Encoder(num_layers, d_model, num_heads, dff, maximum_position_encodin...
Natural Language Processing with Disaster Tweets
10,637,925
t = test[['building_id', 'meter', 'timestamp']] t['row_id'] = t.index site_1 = site_1.merge(t, left_on = ['building_id', 'meter', 'timestamp'], right_on = ['building_id', 'meter', 'timestamp'], how = "left") site_1 = site_1[['meter_reading_scraped', 'row_id']].set_index('row_id' ).dropna() submission.loc[site_1.index,...
num_layers = 6 d_model = d_model num_heads = 6 dff = 512 pe_input = input_vocab_size output_units = 64 rate = 0.1
Natural Language Processing with Disaster Tweets
10,637,925
site_2 = pd.read_csv('.. /input/asu-buildings-energy-consumption/asu_2016-2018.csv', parse_dates = ['timestamp']) site_2 = site_2[site_2['timestamp'].dt.year > 2016]<merge>
tsfr_categorical = TransformerCategorical(num_layers, d_model, num_heads, dff, pe_input, output_units, rate )
Natural Language Processing with Disaster Tweets
10,637,925
t = test[['building_id', 'meter', 'timestamp']] t['row_id'] = t.index site_2 = site_2.merge(t, left_on = ['building_id', 'meter', 'timestamp'], right_on = ['building_id', 'meter', 'timestamp'], how = "left") site_2 = site_2[['meter_reading', 'row_id']].set_index('row_id' ).dropna() submission.loc[site_2.index, 'meter_...
class CustomSchedule(tf.keras.optimizers.schedules.LearningRateSchedule): def __init__(self, d_model, warmup_steps=600): super(CustomSchedule, self ).__init__() self.d_model = tf.cast(d_model, dtype=tf.float32) self.warmup_steps = warmup_steps def __call__(self, step): step = step + 100 arg1 = step ** -0.8 arg2 = step...
Natural Language Processing with Disaster Tweets
10,637,925
site_4 = pd.read_csv('.. /input/ucb-data-leakage-site-4/site4.csv' )<save_to_csv>
learning_rate = CustomSchedule(d_model) optimizer = tf.keras.optimizers.Adam(learning_rate, beta_1=0.9, beta_2=0.98, epsilon=1e-9 )
Natural Language Processing with Disaster Tweets
10,637,925
submission.to_csv('submission.csv' )<set_options>
loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE) def loss_function(real, pred): loss_ = loss_object(real, pred) return tf.reduce_mean(loss_) def acc_function(real, pred): predictions = tf.math.argmax(pred, axis=1) predictions = tf.cast(predictio...
Natural Language Processing with Disaster Tweets
10,637,925
warnings.filterwarnings('ignore') <load_from_csv>
train_step_signature = [ tf.TensorSpec(shape=(None, None), dtype=tf.int64), tf.TensorSpec(shape=(None,), dtype=tf.int64) ]
Natural Language Processing with Disaster Tweets
10,637,925
test = pd.read_csv('.. /input/ashrae-energy-prediction/test.csv', index_col=0, parse_dates = ['timestamp']) building = pd.read_csv('.. /input/ashrae-energy-prediction/building_metadata.csv', usecols=['site_id', 'building_id'] )<merge>
@tf.function(input_signature=train_step_signature) def train_step(lang, targ): enc_padding_mask = create_padding_mask(lang) with tf.GradientTape() as tape: predictions = tsfr_categorical(lang, True, enc_padding_mask) loss = loss_function(targ, predictions) loss_regularization = [] for w in tsfr_categorical.trainabl...
Natural Language Processing with Disaster Tweets
10,637,925
test = test.merge(building, left_on = "building_id", right_on = "building_id", how = "left") t = test[['building_id', 'meter', 'timestamp']] t['row_id'] = t.index<load_from_csv>
@tf.function(input_signature=train_step_signature) def valid_step(lang, targ): enc_padding_mask = create_padding_mask(lang) predictions = tsfr_categorical(lang, False, enc_padding_mask) loss = loss_function(targ, predictions) accuracy = acc_function(targ, predictions) return loss, accuracy
Natural Language Processing with Disaster Tweets
10,637,925
submission_base = pd.read_csv('.. /input/ashrae-half-and-half/submission.csv', index_col=0 )<create_dataframe>
BATCH_SIZE = 2048 BUFFLE_SIZE = 8000 def data_generator(data): dataset = tf.data.Dataset.from_tensor_slices(( data['id'], data['keyword'], data['text'], data['target'])) dataset = dataset.map(tf_encode) dataset = dataset.cache().shuffle(BUFFLE_SIZE ).padded_batch(BATCH_SIZE) dataset = dataset.prefetch(tf.data.experim...
Natural Language Processing with Disaster Tweets
10,637,925
submission = submission_base.copy()<load_from_csv>
Epochs = 100
Natural Language Processing with Disaster Tweets
10,637,925
site_0 = pd.read_csv('.. /input/new-ucf-starter-kernel/submission_ucf_replaced.csv', index_col=0) submission.loc[test[test['site_id']==0].index, 'meter_reading'] = site_0['meter_reading'] del site_0 gc.collect()<load_pretrained>
tensorboard = {'Train_loss':[],'Train_acc':[],'Val_loss':[],'Val_acc':[]} for epoch in range(Epochs): train_loss = [] train_accuracy = [] val_loss = [] val_accuracy = [] for _, lang, targ in train_dataset: loss, acc = train_step(lang, targ) train_loss.append(loss) train_accuracy.append(acc) for _, lang, targ in val_...
Natural Language Processing with Disaster Tweets
10,637,925
with open('.. /usr/lib/ucl_data_leakage_episode_2/site1.pkl', 'rb')as f: site_1 = pickle.load(f) site_1 = site_1[site_1['timestamp'].dt.year > 2016]<merge>
for index in range(len(tensorboard['Train_loss'])) : print(f"\033[0;34mEpoch\033[0m:{index}, Loss:{tensorboard['Train_loss'][index]}, Accuracy:{tensorboard['Train_acc'][index]}", f"Valid_Loss:{tensorboard['Val_loss'][index]}, Valid_Accuracy:{tensorboard['Val_acc'][index]}" )
Natural Language Processing with Disaster Tweets
10,637,925
site_1 = site_1.merge(t, left_on = ['building_id', 'meter', 'timestamp'], right_on = ['building_id', 'meter', 'timestamp'], how = "left") site_1 = site_1[['meter_reading_scraped', 'row_id']].set_index('row_id' ).dropna() submission.loc[site_1.index, 'meter_reading'] = site_1['meter_reading_scraped'] del site_1 gc.coll...
venv_target = np.array([0]*len(test['text'])) test_target = pd.read_csv('/kaggle/input/test-twitter/perfect_submission.csv') test_dataset = tf.data.Dataset.from_tensor_slices(( test['id'], test['keyword'], test['text'], test_target['target'])) test_dataset = test_dataset.map(tf_encode) test_dataset = test_dataset.pad...
Natural Language Processing with Disaster Tweets
10,637,925
site_2 = pd.read_csv('.. /input/asu-buildings-energy-consumption/asu_2016-2018.csv', parse_dates = ['timestamp']) site_2 = site_2[site_2['timestamp'].dt.year > 2016]<merge>
evaluate = TransformerCategorical(num_layers, d_model, num_heads, dff, pe_input, output_units, rate) evaluate.load_weights('/kaggle/working/checkpoint/best_val' )
Natural Language Processing with Disaster Tweets
10,637,925
site_2 = site_2.merge(t, left_on = ['building_id', 'meter', 'timestamp'], right_on = ['building_id', 'meter', 'timestamp'], how = "left") site_2 = site_2[['meter_reading', 'row_id']].set_index('row_id' ).dropna() submission.loc[site_2.index, 'meter_reading'] = site_2['meter_reading'] del site_2 gc.collect()<feature_en...
results = [] for id_num, lang, _ in test_dataset: enc_padding_mask = create_padding_mask(lang) predictions = evaluate(lang, False, enc_padding_mask) predictions = tf.math.argmax(predictions, axis=1) predictions = tf.cast(predictions, dtype=tf.int32) predictions = tf.reshape(predictions,(-1)) results.extend(zip(id_n...
Natural Language Processing with Disaster Tweets
10,637,925
site_4 = pd.read_csv('.. /input/ucb-data-leakage-site-4/site4.csv', parse_dates = ['timestamp']) site_4.columns = ['building_id', 'timestamp', 'meter_reading'] site_4['meter'] = 0 site_4['timestamp'] = pd.DatetimeIndex(site_4['timestamp'])+ timedelta(hours=-8) site_4 = site_4[site_4['timestamp'].dt.year > 2016]<merge...
label_equal = 0 for index, value in enumerate(results): if value[1] == test_target['target'][index]: label_equal +=1 print('result_score:', label_equal/len(results))
Natural Language Processing with Disaster Tweets
10,637,925
site_4 = site_4.merge(t, left_on = ['building_id', 'meter', 'timestamp'], right_on = ['building_id', 'meter', 'timestamp'], how = "left") site_4 = site_4[['meter_reading', 'row_id']].dropna().set_index('row_id') submission.loc[site_4.index, 'meter_reading'] = site_4['meter_reading'] del site_4 gc.collect()<save_to_cs...
submission.to_csv('/kaggle/working/submission.csv', index=False )
Natural Language Processing with Disaster Tweets
10,637,925
<define_variables><EOS>
print(time.time() - start_time) gc.collect()
Natural Language Processing with Disaster Tweets
10,857,169
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<set_options>
import pandas as pd import numpy as np import torch
Natural Language Processing with Disaster Tweets
10,857,169
py.init_notebook_mode(connected=True) <set_options>
df_train = pd.read_csv('.. /input/nlp-getting-started/train.csv') df_train.head()
Natural Language Processing with Disaster Tweets
10,857,169
def reduce_mem_usage(df, use_float16=False): start_mem = df.memory_usage().sum() / 1024**2 print('Memory usage of dataframe is {:.2f} MB'.format(start_mem)) for col in df.columns: if is_datetime(df[col])or is_categorical_dtype(df[col]): continue col_type = df[col].dtype if col_type != object: c_min = df[col].min() c_...
df_test = pd.read_csv('.. /input/nlp-getting-started/test.csv') df_test.head()
Natural Language Processing with Disaster Tweets
10,857,169
%%time root = Path('.. /input/ashrae-feather-format-for-fast-loading') train_df = pd.read_feather(root/'train.feather') weather_train_df = pd.read_feather(root/'weather_train.feather') weather_test_df = pd.read_feather(root/'weather_test.feather') building_meta_df = pd.read_feather(root/'building_metadata.feather' ...
df_train.target.value_counts()
Natural Language Processing with Disaster Tweets
10,857,169
ucf_root = Path('.. /input/ashrae-ucf-spider-and-eda-full-test-labels') leak0_df = pd.read_pickle(ucf_root/'site0.pkl') leak0_df['meter_reading'] = leak0_df.meter_reading_scraped leak0_df.drop(['meter_reading_original','meter_reading_scraped'], axis=1, inplace=True) leak0_df.fillna(0, inplace=True) leak0_df.loc[lea...
xtrain,xval,ytrain,yval = train_test_split(df_train.index.values, df_train.target.values, test_size = 0.2, random_state=15, stratify = df_train.target.values) print(len(xtrain),len(xval))
Natural Language Processing with Disaster Tweets
10,857,169
ucl_root = Path('.. /usr/lib/ucl_data_leakage_episode_2') leak1_df = pd.read_pickle(ucl_root/'site1.pkl') leak1_df['meter_reading'] = leak1_df.meter_reading_scraped leak1_df.drop(['meter_reading_scraped'], axis=1, inplace=True) leak1_df.fillna(0, inplace=True) leak1_df.loc[leak1_df.meter_reading < 0, 'meter_reading...
df_train['set_type'] = 'nil'*df_train.shape[0] df_train.loc[xtrain, 'set_type'] = 'train' df_train.loc[xval, 'set_type'] = 'val' df_train.head(10 )
Natural Language Processing with Disaster Tweets
10,857,169
if use_ucf: if del_2016: print('delete all buildings site0 in 2016') bids = leak_df.building_id.unique() train_df = train_df[train_df.building_id.isin(bids)== False] leak0_df = leak0_df[leak0_df.timestamp.dt.year.isin(ucf_year)] leak1_df = leak1_df[leak1_df.timestamp.dt.year.isin(ucf_year)] train_df = pd.concat([train...
df_train.groupby(['target', 'set_type'] ).count()
Natural Language Processing with Disaster Tweets
10,857,169
del weather_test_df, leak0_df, leak1_df gc.collect()<feature_engineering>
tokenizer= BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True )
Natural Language Processing with Disaster Tweets
10,857,169
train_df['date'] = train_df['timestamp'].dt.date train_df['meter_reading_log1p'] = np.log1p(train_df['meter_reading'] )<filter>
encoded_train = tokenizer.batch_encode_plus( df_train[df_train.set_type=='train'].text.values, add_special_tokens=True, return_attention_masks=True, pad_to_max_length=True, max_length=256, return_tensors='pt' ) encoded_val = tokenizer.batch_encode_plus( df_train[df_train.set_type=='val'].text.values, add_special_to...
Natural Language Processing with Disaster Tweets
10,857,169
building_meta_df[building_meta_df.site_id == 0]<filter>
dataset_train = TensorDataset(input_ids_train, attention_masks_train, labels_train) dataset_val = TensorDataset(input_ids_val, attention_masks_val, labels_val) dataset_test = TensorDataset(input_ids_test, attention_masks_test )
Natural Language Processing with Disaster Tweets
10,857,169
train_df = train_df.query('not(building_id <= 104 & meter == 0 & timestamp <= "2016-05-20")' )<feature_engineering>
model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels = 2, output_attentions = False, output_hidden_states = False )
Natural Language Processing with Disaster Tweets
10,857,169
zone_dict={0:4,1:0,2:7,3:4,4:7,5:0,6:4,7:4,8:4,9:5,10:7,11:4,12:0,13:5,14:4,15:4} def set_localtime(df): for sid, zone in zone_dict.items() : sids = df.site_id == sid df.loc[sids, 'timestamp'] = df[sids].timestamp - pd.offsets.Hour(zone )<feature_engineering>
dataloader_train = DataLoader( dataset_train, sampler= RandomSampler(dataset_train), batch_size=32 ) dataloader_val = DataLoader( dataset_val, sampler = SequentialSampler(dataset_val), batch_size=32 ) dataloader_test = DataLoader( dataset_test, sampler = SequentialSampler(dataset_test), batch_size=32 )
Natural Language Processing with Disaster Tweets