kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
17,120,655 | data_post = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH,padding='post', truncating='post')
print('Shape of data tensor:', data_post.shape)
print('Shape of label tensor:', y.shape)
test_data_post = pad_sequences(test_sequences, maxlen=MAX_SEQUENCE_LENGTH, padding='post', truncating='post')
print('Shape of te... | X_test = pd.read_csv(".. /input/nlp-getting-started/test.csv")["text"]
X_test_tokens = []
for text in X_test:
encoded_dict = tokenizer.encode_plus(text,
add_special_tokens=True,
max_length=sequence_length,
padding="max_length",
return_tensors='pt',
truncation=True)
X_test_tokens.append(encoded_dict['input_ids'])
X_te... | Natural Language Processing with Disaster Tweets |
17,120,655 | print('Preparing embedding matrix')
nb_words = min(MAX_NB_WORDS, len(word_index))
embedding_matrix = np.zeros(( nb_words, EMBEDDING_DIM))
for word, i in word_index.items() :
if i >= MAX_NB_WORDS:
continue
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
embedding_matrix[i] = embedding_ve... | X_test = pd.read_csv(".. /input/nlp-getting-started/test.csv")["text"]
X_test_tokens = []
for text in X_test:
encoded_dict = tokenizer.encode_plus(text,
add_special_tokens=True,
max_length=sequence_length,
padding="max_length",
return_tensors='pt',
truncation=True)
X_test_tokens.append(encoded_dict['input_ids'])
X_te... | Natural Language Processing with Disaster Tweets |
17,120,655 | max_features=100000
maxlen=150
embed_size=300<compute_train_metric> | all_preds = []
for batch in test_dataloader:
x_batch = batch[0].to(device)
with torch.no_grad() :
probas = baseline_bert_clf(tokens=x_batch)
preds = np.round(probas.cpu().detach().numpy() ).astype(int ).flatten()
all_preds.extend(preds ) | Natural Language Processing with Disaster Tweets |
17,120,655 | <init_hyperparams><EOS> | challenge_pred = pd.concat([pd.read_csv(".. /input/nlp-getting-started/sample_submission.csv")["id"], pd.Series(all_preds)], axis=1)
challenge_pred.columns = ['id', 'target']
challenge_pred.to_csv("submission.csv", index=False ) | Natural Language Processing with Disaster Tweets |
16,515,934 | <SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<choose_model_class> | import numpy as np
import pandas as pd
from fastai.text.all import *
import re | Natural Language Processing with Disaster Tweets |
16,515,934 | def get_model() :
input1_pre = Input(shape=(maxlen,))
embed_layer1_pre = Embedding(max_features,
embed_size,
input_length=maxlen,
weights=[embedding_matrix],
trainable=False )(input1_pre)
embed_layer1_pre = SpatialDropout1D(0.4 )(embed_layer1_pre)
x_pre = Bidirectional(CuDNNGRU(128, return_sequences=True))(embed_laye... | dir_path = "/kaggle/input/nlp-getting-started/"
train_df = pd.read_csv(dir_path + "train.csv")
test_df = pd.read_csv(dir_path + "test.csv" ) | Natural Language Processing with Disaster Tweets |
16,515,934 | file_path = "capsule_val0.05.h5"
model = get_model()
checkpoint = ModelCheckpoint(file_path, monitor='val_loss', verbose=1, save_best_only=True, mode='min')
early = EarlyStopping(monitor="val_loss", mode="min", patience=3)
callbacks_list = [checkpoint, early]
hist = model.fit([data, data_post], y, epochs=10, batch_si... | train_df = train_df.drop(columns=["id", "keyword", "location"] ) | Natural Language Processing with Disaster Tweets |
16,515,934 | test_predicts_list = []
def train_folds(data,data_post, y,fold_count=10):
print("Starting to train models...")
fold_size = len(data)// fold_count
models = []
for fold_id in range(0, fold_count):
fold_start = fold_size * fold_id
fold_end = fold_start + fold_size
if fold_id == fold_size - 1:
fold_end = len(data)
print(... | train_df["target"].value_counts() | Natural Language Processing with Disaster Tweets |
16,515,934 | train_folds(data, data_post, y )<save_to_csv> | def remove_URL(text):
url = re.compile(r'https?://\S+|www\.\S+')
return url.sub(r'',text)
train_df["text"] = train_df["text"].apply(remove_URL)
test_df["text"] = test_df["text"].apply(remove_URL ) | Natural Language Processing with Disaster Tweets |
16,515,934 | CLASSES = ['toxic', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate']
test_predicts_am = np.zeros(test_predicts_list[0].shape)
for fold_predict in test_predicts_list:
test_predicts_am += fold_predict
test_predicts_am =(test_predicts_am / len(test_predicts_list))
test_ids = test_df["id"].values
test_ids =... | def remove_html(text):
html=re.compile(r'<.*?>')
return html.sub(r'',text)
train_df["text"] = train_df["text"].apply(remove_html)
test_df["text"] = test_df["text"].apply(remove_html ) | Natural Language Processing with Disaster Tweets |
16,515,934 | import os
import warnings
import logging
from typing import Mapping, List, Union, Optional, Tuple
from pprint import pprint
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from transformers im... | 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)
train_df["text"] = train_df["text"].apply(remove_emoj... | Natural Language Processing with Disaster Tweets |
16,515,934 | catalyst.__version__<define_variables> | train_df["text"].apply(lambda x:len(x.split())).plot(kind="hist"); | Natural Language Processing with Disaster Tweets |
16,515,934 | MODEL_NAME = 'distilbert-base-uncased'
LOG_DIR = "./logdir"
NUM_EPOCHS = 3
BATCH_SIZE = 96
MAX_SEQ_LENGTH = 256
LEARN_RATE = 3e-5
ACCUM_STEPS = 4
SEED = 17<define_variables> | from transformers import AutoTokenizer, AutoModelForSequenceClassification | Natural Language Processing with Disaster Tweets |
16,515,934 | PATH_TO_DATA = '.. /input/jigsaw-toxic-comment-classification-challenge/'
TEXT_FIELD = 'comment_text'
TARGET_FIELDS = ['toxic','severe_toxic','obscene','threat','insult', 'identity_hate']
NUM_CLASSES = len(TARGET_FIELDS)
PRED_THRES = 0.4<load_from_csv> | tokenizer = AutoTokenizer.from_pretrained("roberta-large" ) | Natural Language Processing with Disaster Tweets |
16,515,934 | train_df = pd.read_csv(PATH_TO_DATA + 'train.csv.zip', index_col='id')
test_df = pd.read_csv(PATH_TO_DATA + 'test.csv.zip', index_col='id' )<split> | train_tensor = tokenizer(list(train_df["text"]), padding="max_length",
truncation=True, max_length=30,
return_tensors="pt")["input_ids"] | Natural Language Processing with Disaster Tweets |
16,515,934 | X_train, X_valid, y_train, y_valid = train_test_split(train_df[TEXT_FIELD],
train_df[TARGET_FIELDS],
test_size=0.1,
random_state=17)
X_test = test_df[TEXT_FIELD]<import_modules> | class TweetDataset:
def __init__(self, tensors, targ, ids):
self.text = tensors[ids, :]
self.targ = targ[ids].reset_index(drop=True)
def __len__(self):
return len(self.text)
def __getitem__(self, idx):
t = self.text[idx]
y = self.targ[idx]
return t, tensor(y ) | Natural Language Processing with Disaster Tweets |
16,515,934 | class TextClassificationDataset(Dataset):
def __init__(self,
texts: List[str],
labels: np.ndarray = None,
max_seq_length: int = 512,
model_name: str = 'distilbert-base-uncased'):
self.texts = texts
self.labels = labels
self.max_seq_length = max_seq_length
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
... | train_ids, valid_ids = RandomSplitter()(train_df)
target = train_df["target"]
train_ds = TweetDataset(train_tensor, target, train_ids)
valid_ds = TweetDataset(train_tensor, target, valid_ids)
train_dl = DataLoader(train_ds, bs=64)
valid_dl = DataLoader(valid_ds, bs=512)
dls = DataLoaders(train_dl, valid_dl ).to("c... | Natural Language Processing with Disaster Tweets |
16,515,934 | train_dataset = TextClassificationDataset(
texts=X_train.values.tolist() ,
labels=y_train.values,
max_seq_length=MAX_SEQ_LENGTH,
model_name=MODEL_NAME
)
valid_dataset = TextClassificationDataset(
texts=X_valid.values.tolist() ,
labels=y_valid.values,
max_seq_length=MAX_SEQ_LENGTH,
model_name=MODEL_NAME
)
test_dat... | bert = AutoModelForSequenceClassification.from_pretrained("roberta-large", num_labels=2 ).train().to("cuda")
class BertClassifier(Module):
def __init__(self, bert):
self.bert = bert
def forward(self, x):
return self.bert(x ).logits
model = BertClassifier(bert ) | Natural Language Processing with Disaster Tweets |
16,515,934 | train_val_loaders = {
"train": DataLoader(dataset=train_dataset,
batch_size=BATCH_SIZE,
shuffle=True),
"valid": DataLoader(dataset=valid_dataset,
batch_size=BATCH_SIZE,
shuffle=False)
}<load_pretrained> | learn = Learner(dls, model, metrics=[accuracy, F1Score() ] ).to_fp16()
learn.lr_find() | Natural Language Processing with Disaster Tweets |
16,515,934 | class BertForSequenceClassification(nn.Module):
def __init__(self, pretrained_model_name: str, num_classes: int = None, dropout: float = 0.3):
super().__init__()
config = AutoConfig.from_pretrained(
pretrained_model_name, num_labels=num_classes)
self.model = AutoModel.from_pretrained(pretrained_model_name,
config... | learn.fit_one_cycle(3, lr_max=1e-5 ) | Natural Language Processing with Disaster Tweets |
16,515,934 | model = BertForSequenceClassification(pretrained_model_name=MODEL_NAME,
num_classes=NUM_CLASSES )<choose_model_class> | preds, targs = learn.get_preds()
min_threshold = None
max_f1 = -float("inf")
thresholds = np.linspace(0.3, 0.7, 50)
for threshold in thresholds:
f1 = f1_score(targs, F.softmax(preds, dim=1)[:, 1]>threshold)
if f1 > max_f1:
min_threshold = threshold
min_f1 = f1
print(f"threshold:{threshold:.4f} - f1:{f1:.4f}" ) | Natural Language Processing with Disaster Tweets |
16,515,934 | criterion = torch.nn.BCEWithLogitsLoss()
optimizer = torch.optim.Adam(model.parameters() , lr=LEARN_RATE)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer )<categorify> | test_tensor = tokenizer(list(test_df["text"]),
padding="max_length",
truncation=True,
max_length=30,
return_tensors="pt")["input_ids"] | Natural Language Processing with Disaster Tweets |
16,515,934 | def preprocess_multi_label_metrics(
outputs: torch.Tensor,
targets: torch.Tensor,
weights: Optional[torch.Tensor] = None,
)-> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
if not torch.is_tensor(outputs):
outputs = torch.from_numpy(outputs)
if not torch.is_tensor(targets):
targets = torch.from_numpy(targets)
i... | class TestDS:
def __init__(self, tensors):
self.tensors = tensors
def __len__(self):
return len(self.tensors)
def __getitem__(self, idx):
t = self.tensors[idx]
return t, tensor(0)
test_dl = DataLoader(TestDS(test_tensor), bs=128 ) | Natural Language Processing with Disaster Tweets |
16,515,934 | os.environ['CUDA_VISIBLE_DEVICES'] = "0"
set_global_seed(SEED)
prepare_cudnn(deterministic=True )<train_model> | test_preds = learn.get_preds(dl=test_dl ) | Natural Language Processing with Disaster Tweets |
16,515,934 | <set_options><EOS> | sub = pd.read_csv(dir_path + "sample_submission.csv")
prediction =(F.softmax(test_preds[0], dim=1)[:, 1]>min_threshold ).int()
sub = pd.read_csv(dir_path + "sample_submission.csv")
sub["target"] = prediction
sub.to_csv("submission.csv", index=False ) | Natural Language Processing with Disaster Tweets |
17,012,020 | <SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<set_options> | import numpy as np
import pandas as pd | Natural Language Processing with Disaster Tweets |
17,012,020 | torch.cuda.empty_cache()<set_options> | 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 |
17,012,020 | !nvidia-smi<load_pretrained> | nltk.download('punkt')
nltk.download('stopwords')
!pip install contractions
nltk.download('wordnet')
!pip install pyspellchecker
| Natural Language Processing with Disaster Tweets |
17,012,020 | test_loaders = {
"test": DataLoader(dataset=test_dataset,
batch_size=BATCH_SIZE,
shuffle=False)
}<find_best_params> | stop_words=nltk.corpus.stopwords.words('english')
i=0
wnl=WordNetLemmatizer()
stemmer=SnowballStemmer('english')
for doc in train.text:
doc=re.sub(r'https?://\S+|www\.\S+','',doc)
doc=re.sub(r'<.*?>','',doc)
doc=re.sub(r'[^a-zA-Z\s]','',doc,re.I|re.A)
doc=' '.join([wnl.lemmatize(i)for i in doc.lower().split() ])
... | Natural Language Processing with Disaster Tweets |
17,012,020 | %%time
runner.infer(
model=model,
loaders=test_loaders,
callbacks=[
CheckpointCallback(
resume=f"{LOG_DIR}/checkpoints/best.pth"
),
InferCallback() ,
],
verbose=True
)<predict_on_test> | !pip install tensorflow_text
| Natural Language Processing with Disaster Tweets |
17,012,020 | predicted_probs = runner.callbacks[0].predictions['logits']<load_from_csv> | bert_model_name = 'bert_en_uncased_L-12_H-768_A-12'
map_name_to_handle = {
'bert_en_uncased_L-12_H-768_A-12':
'https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/3',
'bert_en_cased_L-12_H-768_A-12':
'https://tfhub.dev/tensorflow/bert_en_cased_L-12_H-768_A-12/3',
'bert_multi_cased_L-12_H-768_A-12':
'https://tf... | Natural Language Processing with Disaster Tweets |
17,012,020 | sample_sub_df = pd.read_csv(PATH_TO_DATA + 'sample_submission.csv.zip',
index_col='id' )<prepare_output> | bert_preprocess_model = hub.KerasLayer(tfhub_handle_preprocess)
text_test = ['this is such an amazing movie!']
text_preprocessed = bert_preprocess_model(text_test)
print(f'Keys : {list(text_preprocessed.keys())}')
print(f'Shape : {text_preprocessed["input_word_ids"].shape}')
print(f'Word Ids : {text_preprocessed["i... | Natural Language Processing with Disaster Tweets |
17,012,020 | sample_sub_df[TARGET_FIELDS] = predicted_probs<save_to_csv> | bert_model = hub.KerasLayer(tfhub_handle_encoder)
bert_results = bert_model(text_preprocessed)
print(f'Loaded BERT: {tfhub_handle_encoder}')
print(f'Pooled Outputs Shape:{bert_results["pooled_output"].shape}')
print(f'Pooled Outputs Values:{bert_results["pooled_output"][0, :12]}')
print(f'Sequence Outputs Shape:{b... | Natural Language Processing with Disaster Tweets |
17,012,020 | sample_sub_df.to_csv('submissions.csv' )<set_options> | def build_classifier_model() :
text_input = tf.keras.layers.Input(shape=() , dtype=tf.string, name='text')
preprocessing_layer = hub.KerasLayer(tfhub_handle_preprocess, name='preprocessing')
encoder_inputs = preprocessing_layer(text_input)
encoder = hub.KerasLayer(tfhub_handle_encoder, trainable=True, name='BERT_enc... | Natural Language Processing with Disaster Tweets |
17,012,020 | %matplotlib inline
print(os.listdir(".. /input"))
warnings.filterwarnings('ignore' )<load_from_csv> | classifier_model.load_weights('./model.h5')
pred=classifier_model.predict(test.text ) | Natural Language Processing with Disaster Tweets |
17,012,020 | train = pd.read_csv(".. /input/jigsawtraintest/train_jigsaw.csv")
test= pd.read_csv(".. /input/jigsawtraintest/test_jigsaw.csv")
EMBEDDING_FILE = '.. /input/glove840b300dtxt/glove.840B.300d.txt'<prepare_x_and_y> | pd.DataFrame(np.where(pred>0.5,1,0)).value_counts() | Natural Language Processing with Disaster Tweets |
17,012,020 | train["comment_text"].fillna("fillna")
test["comment_text"].fillna("fillna")
X_train = train["comment_text"].str.lower()
y_train = train[["toxic", "severe_toxic", "obscene", "threat", "insult", "identity_hate"]].values
X_test = test["comment_text"].str.lower()<define_variables> | pd.DataFrame({
'id':test.id,
'target':np.where(pred>0.5,1,0)[:,0]
} ).to_csv('submission.csv',index=False ) | Natural Language Processing with Disaster Tweets |
16,993,033 | max_features=100000
maxlen=150
embed_size=300<compute_train_metric> | train_data = pd.read_csv(".. /input/nlp-getting-started/train.csv")
train_data.head(5 ) | Natural Language Processing with Disaster Tweets |
16,993,033 | class RocAucEvaluation(Callback):
def __init__(self, validation_data=() , interval=1):
super(Callback, self ).__init__()
self.interval = interval
self.X_val, self.y_val = validation_data
def on_epoch_end(self, epoch, logs={}):
if epoch % self.interval == 0:
y_pred = self.model.predict(self.X_val, verbose=0)
score = ro... | test_data = pd.read_csv(".. /input/nlp-getting-started/test.csv")
test_data.head(5 ) | Natural Language Processing with Disaster Tweets |
16,993,033 | tok=text.Tokenizer(num_words=max_features,lower=True)
tok.fit_on_texts(list(X_train)+list(X_test))
X_train=tok.texts_to_sequences(X_train)
X_test=tok.texts_to_sequences(X_test)
x_train=sequence.pad_sequences(X_train,maxlen=maxlen)
x_test=sequence.pad_sequences(X_test,maxlen=maxlen )<categorify> | !pip install BeautifulSoup4 | Natural Language Processing with Disaster Tweets |
16,993,033 | embeddings_index = {}
with open(EMBEDDING_FILE,encoding='utf8')as f:
for line in f:
values = line.rstrip().rsplit(' ')
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
embeddings_index[word] = coefs<feature_engineering> | stop = set(stopwords.words('english'))
stop.update(list(string.punctuation))
def clean_tweets(text):
re1 = re.compile(r' +')
x1 = text.lower().replace('
'nbsp;', ' ' ).replace('
', "
" ).replace('quot;', "'" ).replace(
'<br />', "
" ).replace('\"', '"' ).replace('<unk>', 'u_n' ).replace(' @.@ ', '.' ).replace(
' @-@... | Natural Language Processing with Disaster Tweets |
16,993,033 | word_index = tok.word_index
num_words = min(max_features, len(word_index)+ 1)
embedding_matrix = np.zeros(( num_words, embed_size))
for word, i in word_index.items() :
if i >= max_features:
continue
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
embedding_matrix[i] = embedding_vector<c... | test_data['text'] = test_data['text'].apply(clean_tweets)
test_data['text'].head(5 ) | Natural Language Processing with Disaster Tweets |
16,993,033 | sequence_input = Input(shape=(maxlen,))
x = Embedding(max_features, embed_size, weights=[embedding_matrix],trainable = False )(sequence_input)
x = SpatialDropout1D(0.2 )(x)
x = Bidirectional(GRU(128, return_sequences=True,dropout=0.1,recurrent_dropout=0.1))(x)
x = Conv1D(64, kernel_size = 3, padding = "valid", kerne... | vocab_size = 1000
tokenizer = Tokenizer(num_words = vocab_size, oov_token = 'UNK')
tokenizer.fit_on_texts(list(train_data['prep_text'])+ list(test_data['text'])) | Natural Language Processing with Disaster Tweets |
16,993,033 | from keras.utils.vis_utils import plot_model<split> | X_train_ohe = tokenizer.texts_to_matrix(train_data['prep_text'], mode = 'binary')
X_test_ohe = tokenizer.texts_to_matrix(test_data['text'], mode = 'binary')
y_train = np.array(train_data['target'] ).astype(int)
print(f"X_train shape: {X_train_ohe.shape}")
print(f"X_test shape: {X_test_ohe.shape}")
print(f"y_train ... | Natural Language Processing with Disaster Tweets |
16,993,033 | batch_size = 128
epochs = 5
X_tra, X_val, y_tra, y_val = train_test_split(x_train, y_train, train_size=0.9, random_state=233 )<train_model> | X_train_ohe, X_val_ohe, y_train, y_val = train_test_split(X_train_ohe, y_train, random_state = 42, test_size = 0.2)
print(f"X_train shape: {X_train_ohe.shape}")
print(f"X_val shape: {X_val_ohe.shape}")
print(f"y_train shape: {y_train.shape}")
print(f"y_val shape: {y_val.shape}" ) | Natural Language Processing with Disaster Tweets |
16,993,033 | model.fit(X_tra, y_tra, batch_size=batch_size, epochs=epochs, validation_data=(X_val, y_val),callbacks = callbacks_list,verbose=1)
model.load_weights(filepath)
print('Predicting.... ')
y_pred = model.predict(x_test,batch_size=1024,verbose=1 )<compute_test_metric> | def setup_model() :
model = Sequential()
model.add(layers.Dense(1, activation='sigmoid', input_shape=(vocab_size,)))
model.compile(optimizer=optimizers.RMSprop(lr=0.001),
loss=losses.binary_crossentropy,
metrics=[metrics.binary_accuracy])
return model
model = setup_model()
model.summary() | Natural Language Processing with Disaster Tweets |
16,993,033 | y_df = np.where(y_pred > 0.5, 1, 0 )<data_type_conversions> | history = model.fit(X_train_ohe, y_train, epochs = 20, batch_size = 512, validation_data =(X_val_ohe, y_val)) | Natural Language Processing with Disaster Tweets |
16,993,033 | y_df = pd.DataFrame(y_df, columns=['toxic','severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate'])
y_df = y_df.astype('int' )<define_variables> | _, accuracy = model.evaluate(X_val_ohe, y_val ) | Natural Language Processing with Disaster Tweets |
16,993,033 | labels = ['toxic','severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate']<compute_test_metric> | X_train_wc = tokenizer.texts_to_matrix(train_data['prep_text'], mode = 'count')
X_test_wc = tokenizer.texts_to_matrix(test_data['text'], mode = 'count')
y_train = np.array(train_data['target'] ).astype(int)
print(f"X_train shape: {X_train_wc.shape}")
print(f"X_test shape: {X_test_wc.shape}")
print(f"y_train shape:... | Natural Language Processing with Disaster Tweets |
16,993,033 | def get_metri_scores(y_test, y_test_pred):
vals = precision_recall_fscore_support(y_test, y_test_pred, average='macro')
precision = vals[0]
recall = vals[1]
f1 = vals[2]
acc = accuracy_score(y_test, y_test_pred)
return precision, recall, f1, acc<feature_engineering> | X_train_wc, X_val_wc, y_train, y_val = train_test_split(X_train_wc, y_train, random_state = 42, test_size = 0.2)
print(f"X_train shape: {X_train_wc.shape}")
print(f"X_val shape: {X_val_wc.shape}")
print(f"y_train shape: {y_train.shape}")
print(f"y_val shape: {y_val.shape}" ) | Natural Language Processing with Disaster Tweets |
16,993,033 | results_cv = pd.DataFrame({'labels': labels})
results_cv['acc'] = 0
results_cv['f1'] = 0
results_cv['precision'] = 0
results_cv['recall'] = 0
for col in labels:
print(col)
precision, recall, f1, acc = get_metri_scores(test[col], y_df[col])
results_cv['acc'][results_cv['labels']==col] = acc
results_cv['f1'][results_c... | history = model.fit(X_train_wc, y_train, epochs = 20, batch_size = 512, validation_data =(X_val_wc, y_val)) | Natural Language Processing with Disaster Tweets |
16,993,033 | sequence_input = Input(shape=(maxlen,))
x = Embedding(max_features, embed_size, weights=[embedding_matrix],trainable = False )(sequence_input)
x = SpatialDropout1D(0.2 )(x)
x = LSTM(256, return_sequences=True,dropout=0.1,recurrent_dropout=0.1 )(x)
x = Conv1D(64, kernel_size = 3, padding = "valid", kernel_initializer... | _, accuracy = model.evaluate(X_val_wc, y_val ) | Natural Language Processing with Disaster Tweets |
16,993,033 | filepath="weights_novice_model.hdf5"
checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
early = EarlyStopping(monitor="val_acc", mode="max", patience=5)
ra_val = RocAucEvaluation(validation_data=(X_val, y_val), interval = 1)
callbacks_list = [ra_val,checkpoint, earl... | X_train_freq = tokenizer.texts_to_matrix(train_data['prep_text'], mode = 'freq')
X_test_freq = tokenizer.texts_to_matrix(test_data['text'], mode = 'freq')
y_train = np.array(train_data['target'] ).astype(int)
print(f"X_train shape: {X_train_freq.shape}")
print(f"X_test shape: {X_test_freq.shape}")
print(f"y_train ... | Natural Language Processing with Disaster Tweets |
16,993,033 | y_df = np.where(y_pred > 0.5, 1, 0)
y_df = pd.DataFrame(y_df, columns=['toxic','severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate'])
y_df = y_df.astype('int' )<compute_train_metric> | X_train_freq, X_val_freq, y_train, y_val = train_test_split(X_train_freq, y_train, test_size = 0.2, random_state = 42)
print(f"X_train shape: {X_train_freq.shape}")
print(f"X_val shape: {X_val_freq.shape}")
print(f"y_train shape: {y_train.shape}")
print(f"y_val shape: {y_val.shape}" ) | Natural Language Processing with Disaster Tweets |
16,993,033 | def get_metri_scores(y_test, y_test_pred):
vals = precision_recall_fscore_support(y_test, y_test_pred, average='macro')
precision = vals[0]
recall = vals[1]
f1 = vals[2]
acc = accuracy_score(y_test, y_test_pred)
return precision, recall, f1, acc
results_cv = pd.DataFrame({'labels': labels})
results_cv['acc'] = 0
res... | history = model.fit(X_train_freq, y_train, epochs = 20, batch_size = 512, validation_data =(X_val_freq, y_val)) | Natural Language Processing with Disaster Tweets |
16,993,033 | !pip install fastai2 --quiet<import_modules> | vectorizer = TfidfVectorizer(max_features = vocab_size)
vectorizer.fit(list(train_data['prep_text'])+ list(test_data['text']))
X_train_tfidf = vectorizer.transform(list(train_data['prep_text'])).toarray()
X_test_tfidf = vectorizer.transform(list(test_data['text'])).toarray()
y_train = np.array(train_data['target'] ).a... | Natural Language Processing with Disaster Tweets |
16,993,033 | from fastai2.text.all import *<define_variables> | X_train_tfidf, X_val_tfidf, y_train, y_val = train_test_split(X_train_tfidf, y_train, test_size = 0.2, random_state = 42)
print(f"X_train shape: {X_train_tfidf.shape}")
print(f"X_val shape: {X_val_tfidf.shape}")
print(f"y_train shape: {y_train.shape}")
print(f"y_val shape: {y_val.shape}" ) | Natural Language Processing with Disaster Tweets |
16,993,033 | path = Path('.. /input/jigsaw-toxic-comment-classification-challenge' )<load_pretrained> | history = model.fit(X_train_tfidf, y_train, epochs = 20, batch_size = 512, validation_data =(X_val_tfidf, y_val)) | Natural Language Processing with Disaster Tweets |
16,993,033 | with ZipFile(path/'train.csv.zip', 'r')as zip_ref:
zip_ref.extractall('.. /output/kaggle/working')
with ZipFile(path/'test.csv.zip', 'r')as zip_ref:
zip_ref.extractall('.. /output/kaggle/working')
with ZipFile(path/'test_labels.csv.zip', 'r')as zip_ref:
zip_ref.extractall('.. /output/kaggle/working')
with ZipFile(pa... | embedding_dict={}
with open('.. /input/glovetwitter27b100dtxt/glove.twitter.27B.100d.txt','r')as f:
for line in f:
values=line.split()
word = values[0]
vectors=np.asarray(values[1:],'float32')
embedding_dict[word]=vectors
f.close() | Natural Language Processing with Disaster Tweets |
16,993,033 | path_w = Path('.. /output/kaggle/working' )<load_from_csv> | vocab_size = 10000
tokenizer = Tokenizer(num_words = vocab_size, oov_token = 'UNK')
tokenizer.fit_on_texts(list(train_data['prep_text'])+ list(test_data['text']))
max_len = 15
X_train_seq = tokenizer.texts_to_sequences(train_data['prep_text'])
X_test_seq = tokenizer.texts_to_sequences(test_data['text'])
X_train_seq ... | Natural Language Processing with Disaster Tweets |
16,993,033 | df = pd.read_csv(path_w/'train.csv' )<create_dataframe> | X_train_seq, X_val_seq, y_train, y_val = train_test_split(X_train_seq, y_train, test_size = 0.2, random_state = 42)
print(f"X_train shape: {X_train_seq.shape}")
print(f"X_val shape: {X_val_seq.shape}")
print(f"y_train shape: {y_train.shape}")
print(f"y_val shape: {y_val.shape}" ) | Natural Language Processing with Disaster Tweets |
16,993,033 | blocks =(TextBlock.from_df(text_cols='comment_text', is_lm=True, res_col_name='text'))<load_from_csv> | num_words = len(tokenizer.word_index)
print(f"Number of unique words: {num_words}" ) | Natural Language Processing with Disaster Tweets |
16,993,033 | test_df = pd.read_csv(path_w/'test.csv' )<concatenate> | embedding_matrix=np.zeros(( num_words,100))
for word,i in tokenizer.word_index.items() :
if i < num_words:
emb_vec = embedding_dict.get(word)
if emb_vec is not None:
embedding_matrix[i] = emb_vec | Natural Language Processing with Disaster Tweets |
16,993,033 | text_df = pd.Series.append(df['comment_text'], test_df['comment_text'] )<create_dataframe> | n_latent_factors = 100
model_glove = Sequential()
model_glove.add(layers.Embedding(num_words, n_latent_factors, weights = [embedding_matrix],
input_length = max_len, trainable=True))
model_glove.add(layers.Flatten())
model_glove.add(layers.Dropout(0.5))
model_glove.add(layers.Dense(1, activation='sigmoid'))
model_glov... | Natural Language Processing with Disaster Tweets |
16,993,033 | text_df = pd.DataFrame(text_df )<load_from_csv> | model_glove.compile(optimizer = optimizers.RMSprop(lr=0.001),
loss = losses.binary_crossentropy,
metrics = [metrics.binary_accuracy])
history = model_glove.fit(X_train_seq,
y_train,
epochs=20,
batch_size=512,
validation_data=(X_val_seq, y_val)) | Natural Language Processing with Disaster Tweets |
16,993,033 | get_x = ColReader('text')
splitter = RandomSplitter(0.1, seed=42 )<create_dataframe> | max_len = 15
X_train_seq = tokenizer.texts_to_sequences(train_data['prep_text'])
X_test_seq = tokenizer.texts_to_sequences(test_data['text'])
X_train_seq = pad_sequences(X_train_seq, maxlen = max_len, truncating = 'post', padding = 'post')
X_test_seq = pad_sequences(X_test_seq, maxlen = max_len, truncating = 'post',... | Natural Language Processing with Disaster Tweets |
16,993,033 | lm_dblock = DataBlock(blocks=blocks,
get_x=get_x,
splitter=splitter )<load_pretrained> | vocab_size = 1000
tokenizer = Tokenizer(num_words = vocab_size, oov_token = 'UNK')
tokenizer.fit_on_texts(list(train_data['text'])+ list(test_data['text']))
X_train_wc = tokenizer.texts_to_matrix(train_data['text'], mode = 'count')
X_test_wc = tokenizer.texts_to_matrix(test_data['text'], mode = 'count')
y_train = np... | Natural Language Processing with Disaster Tweets |
16,993,033 | <find_best_params><EOS> | submission = pd.read_csv(".. /input/nlp-getting-started/sample_submission.csv")
test_pred = model_glove.predict(X_test_seq)
test_pred_int = test_pred.round().astype('int')
submission['target'] = test_pred_int
submission.to_csv('submission.csv', index=False ) | Natural Language Processing with Disaster Tweets |
16,578,543 | <SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<categorify> | import pandas as pd
import numpy as np
from sklearn.metrics import f1_score | Natural Language Processing with Disaster Tweets |
16,578,543 | lm_learn.save_encoder('fine_tuned' )<define_variables> | train=pd.read_csv('.. /input/nlp-getting-started/train.csv')
test=pd.read_csv('.. /input/nlp-getting-started/test.csv' ) | Natural Language Processing with Disaster Tweets |
16,578,543 | ys = ['toxic', 'severe_toxic', 'obscene', 'threat', 'insult',
'identity_hate']<create_dataframe> | train.target.value_counts() | Natural Language Processing with Disaster Tweets |
16,578,543 | blocks =(TextBlock.from_df('comment_text', seq_len=lm_dls.seq_len, vocab=lm_dls.vocab),
MultiCategoryBlock(encoded=True, vocab=ys))<load_pretrained> | nltk.download('punkt')
nltk.download('stopwords')
!pip install contractions
nltk.download('wordnet')
!pip install pyspellchecker
| Natural Language Processing with Disaster Tweets |
16,578,543 | dls = toxic_clas.dataloaders(df )<choose_model_class> | stop_words=nltk.corpus.stopwords.words('english')
i=0
wnl=WordNetLemmatizer()
stemmer=SnowballStemmer('english')
for doc in train.text:
doc=re.sub(r'https?://\S+|www\.\S+','',doc)
doc=re.sub(r'<.*?>','',doc)
doc=re.sub(r'[^a-zA-Z\s]','',doc,re.I|re.A)
doc=' '.join([wnl.lemmatize(i)for i in doc.lower().split() ])
... | Natural Language Processing with Disaster Tweets |
16,578,543 | loss_func = BCEWithLogitsLossFlat(thresh=0.8)
metrics = [partial(accuracy_multi, thresh=0.8)]<choose_model_class> | tfidf=TfidfVectorizer(ngram_range=(1,1),use_idf=True)
mat=tfidf.fit_transform(train.text ).toarray()
train_df=pd.DataFrame(mat,columns=tfidf.get_feature_names())
test_df=pd.DataFrame(tfidf.transform(test.text ).toarray() ,columns=tfidf.get_feature_names())
train_df.head() | Natural Language Processing with Disaster Tweets |
16,578,543 | learn = text_classifier_learner(dls, AWD_LSTM, metrics=metrics, loss_func=loss_func )<find_best_params> | model=LogisticRegression()
model.fit(train_df,train.target)
print(f1_score(model.predict(train_df),train.target))
pred=model.predict(test_df ) | Natural Language Processing with Disaster Tweets |
16,578,543 | <categorify><EOS> | pd.DataFrame({
'id':test.id,
'target':pred
} ).to_csv('submission.csv',index=False ) | Natural Language Processing with Disaster Tweets |
16,302,634 | <SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<train_model> | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from nltk.corpus import stopwords
from nltk.util import ngrams
from nltk.stem import WordNetLemmatizer
import re
from textblob import TextBlob
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction... | Natural Language Processing with Disaster Tweets |
16,302,634 | learn.to_fp16()
lr = 1e-2
moms =(0.8,0.7, 0.8)
lr *= learn.dls.bs/128
learn.fit_one_cycle(1, lr, moms=moms, wd=0.1 )<train_model> | train_data = pd.read_csv('/kaggle/input/nlp-getting-started/train.csv')
submit_data = pd.read_csv('/kaggle/input/nlp-getting-started/test.csv' ) | Natural Language Processing with Disaster Tweets |
16,302,634 | learn.freeze_to(-2)
lr/=2
learn.fit_one_cycle(1, slice(lr/(2.6**4), lr), moms=moms, wd=0.1 )<train_model> | train_data[train_data['text'].isna() ] | Natural Language Processing with Disaster Tweets |
16,302,634 | learn.freeze_to(-3)
lr /=2
learn.fit_one_cycle(1, slice(lr/(2.6**4), lr), moms=moms, wd=0.1 )<train_model> | train_data.groupby('target' ).count() | Natural Language Processing with Disaster Tweets |
16,302,634 | learn.unfreeze()
lr /= 5
learn.fit_one_cycle(2, slice(lr/(2.6**4),lr), moms=(0.8,0.7,0.8), wd=0.1 )<train_model> | %matplotlib inline | Natural Language Processing with Disaster Tweets |
16,302,634 | dl = learn.dls.test_dl(test_df['comment_text'] )<predict_on_test> | data = pd.concat([train_data, submit_data])
data.shape | Natural Language Processing with Disaster Tweets |
16,302,634 | preds = learn.get_preds(dl=dl )<load_from_csv> | data['text'] = data['text'].apply(lambda x: re.sub(re.compile(r'https?\S+'), '', x))
data['text'] = data['text'].apply(lambda x: re.sub(re.compile(r'[\//:,.!?@&\-'\`"\_
\
data['text'] = data['text'].apply(lambda x: re.sub(re.compile(r'<.*?>'), '', x))
data['text'] = data['text'].apply(lambda x: re.sub(re.compile("["
u"... | Natural Language Processing with Disaster Tweets |
16,302,634 | sub = pd.read_csv(path_w/'sample_submission.csv' )<data_type_conversions> | clean_train = data[0:train_data.shape[0]]
clean_submit = data[train_data.shape[0]:-1]
X_train, X_test, y_train, y_test = train_test_split(clean_train['text'], clean_train['target'],
test_size = 0.2, random_state = 4 ) | Natural Language Processing with Disaster Tweets |
16,302,634 | preds[0][0].cpu().numpy()<prepare_output> | def tfidf(words):
tfidf_vectorizer = TfidfVectorizer()
data_feature = tfidf_vectorizer.fit_transform(words)
return data_feature, tfidf_vectorizer
X_train_tfidf, tfidf_vectorizer = tfidf(X_train.tolist())
X_test_tfidf = tfidf_vectorizer.transform(X_test.tolist() ) | Natural Language Processing with Disaster Tweets |
16,302,634 | sub[ys] = preds[0]<save_to_csv> | lr_tfidf = LogisticRegression(class_weight = 'balanced', solver = 'lbfgs', n_jobs = -1)
lr_tfidf.fit(X_train_tfidf, y_train)
y_predicted_lr = lr_tfidf.predict(X_test_tfidf ) | Natural Language Processing with Disaster Tweets |
16,302,634 | sub.to_csv('submission.csv', index=False )<save_to_csv> | def score_metrics(y_test, y_predicted):
accuracy = accuracy_score(y_test, y_predicted)
precision = precision_score(y_test, y_predicted)
recall = recall_score(y_test, y_predicted)
print("accuracy = %0.3f, precision = %0.3f, recall = %0.3f" %(accuracy, precision, recall)) | Natural Language Processing with Disaster Tweets |
16,302,634 | sub.to_csv('submission.csv', index=False )<load_from_csv> | score_metrics(y_test, y_predicted_lr ) | Natural Language Processing with Disaster Tweets |
16,302,634 | df=pd.read_csv('/kaggle/input/tweet-sentiment-extraction/train.csv')
df.head()<count_missing_values> | pipeline = Pipeline([
('clf', DecisionTreeClassifier(splitter='random', class_weight='balanced'))
])
parameters = {
'clf__max_depth':(150,160,165),
'clf__min_samples_split':(18,20,23),
'clf__min_samples_leaf':(5,6,7)
}
df_tfidf = GridSearchCV(pipeline, parameters, n_jobs=-1, verbose=-1, scoring='f1')
df_tfidf.fit(X... | Natural Language Processing with Disaster Tweets |
16,302,634 | def missing_value_of_data(data):
total = data.isnull().sum().sort_values(ascending=False)
precent=round(total/data.shape[0]*100,2)
return pd.concat([total,precent],axis=1,keys=['Total','Percent'] )<count_missing_values> | y_predicted_dt = df_tfidf.predict(X_test_tfidf ) | Natural Language Processing with Disaster Tweets |
16,302,634 | missing_value_of_data(df )<correct_missing_values> | score_metrics(y_test, y_predicted_dt ) | Natural Language Processing with Disaster Tweets |
16,302,634 | df.dropna(inplace=True )<count_values> | !pip install gensim -i http://pypi.douban.com/simple --trusted-host pypi.douban.com | Natural Language Processing with Disaster Tweets |
16,302,634 | def count_values_in_columns(data,feature):
total=data.loc[:,feature].value_counts()
percentage = round(data.loc[:,feature].value_counts(normalize=True)*100,2)
return pd.concat([total,percentage],axis=1,keys=['Total','Percentage'] )<count_values> | stop_words = stopwords.words('english')
for word in ['us','no','yet']:
stop_words.append(word)
data_list = []
text_series = data['text']
for i in range(len(text_series)) :
content = text_series.iloc[i]
cutwords = [word for word in content.split(' ')if word not in stop_words if len(word)!= 0]
data_list.append(cutwords... | Natural Language Processing with Disaster Tweets |
16,302,634 | count_values_in_columns(df,'sentiment' )<count_duplicates> | for i in range(len(data_list)) :
content = data_list[i]
if len(content)<1:
print(i ) | Natural Language Processing with Disaster Tweets |
16,302,634 | def duplicated_values_data(data):
dup=[]
columns=data.columns
for i in columns:
dup.append(sum(data[i].duplicated()))
return pd.concat([pd.Series(columns),pd.Series(dup)],axis=1,keys=['Columns','Duplicate count'] )<count_duplicates> | word2vec_path='./GoogleNews-vectors-negative300.bin.gz'
word2vec_model = gensim.models.KeyedVectors.load_word2vec_format(word2vec_path, binary=True ) | Natural Language Processing with Disaster Tweets |
16,302,634 | duplicated_values_data(df )<define_variables> | def get_textVector(data_list, word2vec, textsVectors_list):
for i in range(len(data_list)) :
words_perText = data_list[i]
if len(words_perText)< 1:
words_vector = [np.zeros(300)]
else:
words_vector = [word2vec.wv[k] if k in word2vec_model else np.zeros(300)for k in words_perText]
text_vector = np.array(words_vector ).m... | Natural Language Processing with Disaster Tweets |
16,302,634 | def find_url(string):
try:
text = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F])) +',string)
except:
text=[]
return "".join(text )<feature_engineering> | textsVectors_list = []
get_textVector(data_list, word2vec_model, textsVectors_list)
X = np.array(textsVectors_list ) | Natural Language Processing with Disaster Tweets |
16,302,634 | df['url'] = df['text'].apply(lambda x : find_url(x))<categorify> | pd.isnull(X ).any() | Natural Language Processing with Disaster Tweets |
16,302,634 | def find_emoji(text):
emo_text=emoji.demojize(text)
line=re.findall(r'\: (.*?)\:',emo_text)
return line<feature_engineering> | word2vec_X = X[0:train_data.shape[0]]
y = data['target'][0:train_data.shape[0]]
word2vec_submit = X[train_data.shape[0]:-1]
X_train_word2vec, X_test_word2vec, y_train_word2vec, y_test_word2vec = train_test_split(word2vec_X, y,
test_size = 0.2, random_state = 4 ) | Natural Language Processing with Disaster Tweets |
16,302,634 | sentence="I love ⚽ very much 😁"
find_emoji(sentence )<feature_engineering> | word2vec_lr = LogisticRegression(class_weight = 'balanced', solver = 'lbfgs', n_jobs = -1)
word2vec_lr.fit(X_train_word2vec, y_train_word2vec)
y_predicted_word2vec_lr = word2vec_lr.predict(X_test_word2vec ) | Natural Language Processing with Disaster Tweets |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.