kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
21,301,029 | 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 )<feature_engineering> | train_cleaned_df = train.copy() | Natural Language Processing with Disaster Tweets |
21,301,029 | train['text'] = train['text'].apply(lambda s : remove_emoji(s))
test ['text'] = test ['text'].apply(lambda s : remove_emoji(s))
<string_transform> | tokenizer = AutoTokenizer.from_pretrained('bert-large-uncased')
bert = TFBertModel.from_pretrained('bert-large-uncased' ) | Natural Language Processing with Disaster Tweets |
21,301,029 | def create_vocab(df):
vocab = Counter()
for i in range(df.shape[0]):
vocab.update(df.text[i].split())
return(vocab)
<categorify> | tokenizer('Shine on you crazy diamond.' ) | Natural Language Processing with Disaster Tweets |
21,301,029 | master=pd.concat(( train,test)).reset_index(drop=True)
vocab = create_vocab(master)
len(vocab )<set_options> | print("max len of tweets",max([len(x.split())for x in train.text])) | Natural Language Processing with Disaster Tweets |
21,301,029 | vocab.most_common(50)
<define_variables> | x_train = tokenizer(
text=train.text.tolist() ,
add_special_tokens=True,
max_length=73,
truncation=True,
padding=True,
return_tensors='tf',
return_token_type_ids = False,
return_attention_mask = True,
verbose = True)
| Natural Language Processing with Disaster Tweets |
21,301,029 | final_vocab = []
min_occur = 2
for k,v in vocab.items() :
if v >= min_occur:
final_vocab.append(k )<string_transform> | train.target.value_counts() | Natural Language Processing with Disaster Tweets |
21,301,029 | def filter(tweet):
sentence = ""
for word in tweet.split() :
if word in final_vocab:
sentence = sentence + word + ' '
return(sentence )<feature_engineering> | max_len = 73
input_ids = Input(shape=(max_len,), dtype=tf.int32, name="input_ids")
input_mask = Input(shape=(max_len,), dtype=tf.int32, name="attention_mask")
embeddings = bert(input_ids,attention_mask = input_mask)[1]
out = tf.keras.layers.Dropout(0.1 )(embeddings)
out = Dense(128, activation='relu' )(out)
out = t... | Natural Language Processing with Disaster Tweets |
21,301,029 | train['text'] = train['text'].apply(lambda s : filter(s))
test ['text'] = test ['text'].apply(lambda s : filter(s))<define_variables> | optimizer = Adam(
learning_rate=5e-05,
epsilon=1e-08,
decay=0.01,
clipnorm=1.0)
loss = BinaryCrossentropy(from_logits = True)
metric = BinaryAccuracy('accuracy'),
model.compile(
optimizer = optimizer,
loss = loss,
metrics = metric ) | Natural Language Processing with Disaster Tweets |
21,301,029 | real = train[train.target==1].reset_index()
fake = train[train.target==0].reset_index()<statistical_test> | train_history = model.fit(
x ={'input_ids':x_train['input_ids'],'attention_mask':x_train['attention_mask']} ,
y = y_train, epochs=12, batch_size=32
) | Natural Language Processing with Disaster Tweets |
21,301,029 | def get_ngrams(data,n):
all_words = []
for i in range(len(data)) :
temp = data["text"][i].split()
for word in temp:
all_words.append(word)
tokenized = all_words
esBigrams = ngrams(tokenized, n)
esBigram_wordlist = nltk.FreqDist(esBigrams)
top100 = esBigram_wordlist.most_common(100)
top100 = dict(top100)
df_ngrams ... | x_test = tokenizer(
text=test.text.tolist() ,
add_special_tokens=True,
max_length=73,
truncation=True,
padding=True,
return_tensors='tf',
return_token_type_ids = False,
return_attention_mask = True,
verbose = True)
| Natural Language Processing with Disaster Tweets |
21,301,029 | real_unigrams = get_ngrams(real,1)
fake_unigrams = get_ngrams(fake,1 )<categorify> | predicted = model.predict({'input_ids':x_test['input_ids'],'attention_mask':x_test['attention_mask']} ) | Natural Language Processing with Disaster Tweets |
21,301,029 | real_bigrams = get_ngrams(real,2)
fake_bigrams = get_ngrams(fake,2 )<categorify> | y_predicted = np.where(predicted>0.5,1,0 ) | Natural Language Processing with Disaster Tweets |
21,301,029 | real_trigrams = get_ngrams(real,3)
fake_trigrams = get_ngrams(fake,3 )<string_transform> | y_predictedd = y_predicted.reshape(( 1,3263)) [0] | Natural Language Processing with Disaster Tweets |
21,301,029 | def word_cloud(df):
comment_words = ''
stopwords = set(STOPWORDS)
for val in df.text:
val = str(val)
tokens = val.split()
for i in range(len(tokens)) :
tokens[i] = tokens[i].lower()
comment_words += " ".join(tokens)+" "
wordcloud = WordCloud(width = 800, height = 800,
background_color ='white',
stopwords = stopwords,... | sample['id'] = test.id
sample['target'] = y_predictedd | Natural Language Processing with Disaster Tweets |
21,301,029 | def get_f1(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
precision = true_positives /(predicted_positives + K.epsilon())
recall = true_positives /(possible_positives... | sample.to_csv('submission_a.csv',index = False ) | Natural Language Processing with Disaster Tweets |
21,018,653 | def create_tokenizer(lines):
tokenizer = Tokenizer()
tokenizer.fit_on_texts(lines)
return tokenizer<prepare_x_and_y> | df = pd.read_csv("/kaggle/input/nlp-getting-started/train.csv", na_filter=False)
df.head() | Natural Language Processing with Disaster Tweets |
21,018,653 | X = train.text
y = train.target
test_id = test.id
test.drop(["id","location","keyword"],1,inplace = True )<split> | nlp = spacy.load("en_core_web_sm")
def preprocess(text):
doc = nlp(text)
token_semstop = [word for word in doc if not word.is_stop if not word.text == '
text = ' '.join(token.lower_ for token in token_semstop)
text = re.sub(r'(@\w+|https?:\S+)', '', text)
text = text.replace(r'&?', r'and')
text = re.sub(r'(>... | Natural Language Processing with Disaster Tweets |
21,018,653 | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42 )<string_transform> | train_df['text'] = train_df['text'].apply(preprocess)
train_df.head() | Natural Language Processing with Disaster Tweets |
21,018,653 | tokenizer = create_tokenizer(X_train)
X_train_set = tokenizer.texts_to_matrix(X_train, mode = 'freq')
<choose_model_class> | second_df = pd.read_csv("/kaggle/input/nlp-getting-started/test.csv", na_filter=False)
second_df.head()
test_df = second_df[['text']].copy()
test_df['text'] = test_df['text'].apply(preprocess)
| Natural Language Processing with Disaster Tweets |
21,018,653 | def define_model(n_words):
model = Sequential()
model.add(Dense(128, input_shape=(n_words,), activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics = [get_f1])
model.summary()
plot_model(model, to_file='model.png', show_shapes=True)
return mod... | vectorizer = TfidfVectorizer(use_idf=True, ngram_range=(1,2), preprocessor=preprocess)
tfidf_data = vectorizer.fit_transform(train_df['text'])
| Natural Language Processing with Disaster Tweets |
21,018,653 | model.fit(X_train_set,y_train,epochs=10,verbose=2 )<predict_on_test> | labels = train_df['target'].values
mnb = MultinomialNB()
mnb.fit(tfidf_data, labels)
X_train, X_test, y_train, y_test = train_test_split(tfidf_data, labels, random_state=42, test_size=0.2)
print(classification_report(y_test, mnb.predict(X_test), digits=4)) | Natural Language Processing with Disaster Tweets |
21,018,653 | X_test_set = tokenizer.texts_to_matrix(X_test, mode = 'freq')
y_pred = model.predict_classes(X_test_set )<compute_test_metric> | submission = pd.read_csv("/kaggle/input/nlp-getting-started/sample_submission.csv")
tfidf_test = vectorizer.transform(test_df['text'])
test_df['target'] = mnb.predict(tfidf_test)
test_df.head() | Natural Language Processing with Disaster Tweets |
21,018,653 | <prepare_x_and_y><EOS> | submission['target'] = test_df['target']
submission.to_csv("sample_submission.csv", index=False)
submission.head() | Natural Language Processing with Disaster Tweets |
17,733,566 | <SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<predict_on_test> | for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
print(os.path.join(dirname, filename))
| Natural Language Processing with Disaster Tweets |
17,733,566 | y_test_pred = model.predict_classes(test_set )<save_to_csv> | df_train = pd.read_csv("/kaggle/input/nlp-getting-started/train.csv")
df_test = pd.read_csv("/kaggle/input/nlp-getting-started/test.csv" ) | Natural Language Processing with Disaster Tweets |
17,733,566 | sub = pd.DataFrame()
sub['Id'] = test_id
sub['target'] = y_test_pred
sub.to_csv('submission_1.csv',index=False )<train_model> | def format_keyword(df):
df["keyword"] = df["keyword"].fillna(".")
df["keyword"] = df.keyword.str.replace("%20"," " ) | Natural Language Processing with Disaster Tweets |
17,733,566 | t = Tokenizer()
t.fit_on_texts(X_train.tolist() )<define_variables> | df_train.loc[df_train.target==0]["keyword"].value_counts() | Natural Language Processing with Disaster Tweets |
17,733,566 | vocab_size = len(t.word_index)+ 1<load_from_csv> | df_count = df_train.text.str.split().str.len()
max(df_count ) | Natural Language Processing with Disaster Tweets |
17,733,566 | embeddings_index = dict()
f = open('.. /input/glove6b100dtxt/glove.6B.100d.txt', mode='rt', encoding='utf-8')
for line in f:
values = line.split()
word = values[0]
coefs = asarray(values[1:], dtype='float32')
embeddings_index[word] = coefs
f.close()
print('Loaded %s word vectors.' % len(embeddings_index))<categorify> | def process_text(text):
text=text.replace("
","")
text = re.sub(r'@\S+','',text)
text = re.sub(r'
text = re.sub(r'https?://\S+|www\.\S+|http?://\S+','',text)
text = re.sub('[%s]' % re.escape ( | Natural Language Processing with Disaster Tweets |
17,733,566 | encoded_docs = t.texts_to_sequences(X_train.tolist())
max_length = 100
padded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post')
print(padded_docs )<define_variables> | df_train["text"] = df_train.text.transform(lambda x: process_text(x))
df_test["text"] = df_test.text.transform(lambda x: process_text(x)) | Natural Language Processing with Disaster Tweets |
17,733,566 | mis_spelled = []
embedding_matrix = zeros(( vocab_size, 100))
for word, i in t.word_index.items() :
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
embedding_matrix[i] = embedding_vector
else:
mis_spelled.append(word )<train_on_grid> | df_train["appears"]=df_train.groupby("text" ).text.transform("count" ) | Natural Language Processing with Disaster Tweets |
17,733,566 | model = Sequential()
e = Embedding(vocab_size, 100, weights=[embedding_matrix], input_length=100, trainable=False)
model.add(e)
model.add(Flatten())
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=[get_f1])
model.summary()
model.fit(padded_docs, y_train,... | df_train["target_std"]=df_train.groupby("text" ).target.transform(np.std)
df_train["target_mean"]=df_train.groupby("text" ).target.transform(np.mean ) | Natural Language Processing with Disaster Tweets |
17,733,566 | loss, accuracy = model.evaluate(padded_docs, y_train, verbose=0 )<categorify> | duplicate_ids = df_train.loc[df_train.target_std>0].sort_values(by=["appears","text"],ascending=False ).index | Natural Language Processing with Disaster Tweets |
17,733,566 | encoded_docs = t.texts_to_sequences(X_test.tolist())
padded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post' )<predict_on_test> | df_train = df_train.drop(index = duplicate_ids ) | Natural Language Processing with Disaster Tweets |
17,733,566 | y_pred = model.predict_classes(padded_docs )<categorify> | df_train = df_train.drop_duplicates(subset=["text"] ) | Natural Language Processing with Disaster Tweets |
17,733,566 | encoded_docs = t.texts_to_sequences(test.text.tolist())
padded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post' )<predict_on_test> | df_train.reset_index(drop=True,inplace=True)
df_train | Natural Language Processing with Disaster Tweets |
17,733,566 | y_test_pred = model.predict_classes(padded_docs )<save_to_csv> | nlp = spacy.load("en_core_web_lg")
keyword_train = np.array([nlp(text ).vector for text in df_train.keyword])
keyword_test = np.array([nlp(text ).vector for text in df_test.keyword] ) | Natural Language Processing with Disaster Tweets |
17,733,566 | sub = pd.DataFrame()
sub['Id'] = test_id
sub['target'] = y_test_pred
sub.to_csv('submission_2.csv',index=False )<train_model> | def nlp_vectors(text):
res = []
doc = nlp(text)
for token in doc:
if not token.is_space:
res.append(token.vector)
return res
def build_nlp_vectors(df_text):
spacy_vectors =([nlp_vectors(text)for text in df_text])
max_length = 0;
for vector in spacy_vectors:
max_length = max(max_length, len(vector))
print(f"Maximum L... | Natural Language Processing with Disaster Tweets |
17,733,566 |
<categorify> | nlp_train = build_nlp_vectors(df_train.text ) | Natural Language Processing with Disaster Tweets |
17,733,566 | encoded_docs = t.texts_to_sequences(X_train.tolist())
padded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post')
print(padded_docs )<define_variables> | tokenizer = ppb.DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
bert_model = ppb.DistilBertModel.from_pretrained("distilbert-base-uncased" ) | Natural Language Processing with Disaster Tweets |
17,733,566 | vocab_size<choose_model_class> | def process_data(df_text):
tokens = df_text.apply(lambda text: tokenizer.encode(text,add_special_tokens=True))
max_len = 0;
i = 0;
for token in tokens.values:
max_len = max(max_len,len(token))
print(f"Max Length: {max_len}")
padded = np.array([i+[0]*(max_len-len(i)) for i in tokens.values])
attention_mask = np.where(... | Natural Language Processing with Disaster Tweets |
17,733,566 | def define_model(vocab_size, max_length):
model = Sequential()
model.add(Embedding(vocab_size, 100, input_length=max_length))
model.add(Conv1D(filters=32, kernel_size=8, activation='relu'))
model.add(MaxPooling1D(pool_size=2))
model.add(Flatten())
model.add(Dense(10, activation='relu'))
model.add(Dense(1, activation='... | X_train = process_data(df_train.text ) | Natural Language Processing with Disaster Tweets |
17,733,566 | model = define_model(vocab_size, max_length)
model.fit(padded_docs, y_train, epochs=10, verbose=2 )<compute_test_metric> | y_train = df_train.target | Natural Language Processing with Disaster Tweets |
17,733,566 | loss, accuracy = model.evaluate(padded_docs, y_train, verbose=0 )<categorify> | X_tr, X_val, nlp_tr, nlp_val, kw_tr, kw_val, y_tr, y_val = train_test_split(X_train,nlp_train, keyword_train, y_train, test_size=0.25, train_size=0.75,shuffle=True ) | Natural Language Processing with Disaster Tweets |
17,733,566 | encoded_docs = t.texts_to_sequences(X_test.tolist())
padded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post' )<predict_on_test> | def build_nn() :
model = tf.keras.Sequential()
model.add(layers.Input(shape=(768,)))
model.add(layers.Dense(128,activation='tanh'))
model.add(layers.Dropout(0.6))
model.add(layers.Dense(32,activation='tanh'))
model.add(layers.Dropout(0.6))
model.add(layers.Dense(8,activation='tanh'))
model.add(layers.Dense(1,activatio... | Natural Language Processing with Disaster Tweets |
17,733,566 | y_pred = model.predict_classes(padded_docs )<categorify> | kfold = KFold(n_splits=4, shuffle=True, random_state=1 ) | Natural Language Processing with Disaster Tweets |
17,733,566 | encoded_docs = t.texts_to_sequences(test.text.tolist())
padded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post' )<predict_on_test> | def eval_f1_score(X_val, y_val, model):
pred_val =(model.predict(X_val)>0.5)
f1 = f1_score(y_val,pred_val)
return f1 | Natural Language Processing with Disaster Tweets |
17,733,566 | y_test_pred = model.predict_classes(padded_docs )<save_to_csv> | EPOCHS = 100
BATCH_SIZE = 64 | Natural Language Processing with Disaster Tweets |
17,733,566 | sub = pd.DataFrame()
sub['Id'] = test_id
sub['target'] = y_test_pred
sub.to_csv('submission_cnn.csv',index=False )<save_model> | fold = 0
history_by_fold = []
cv_results = []
for train,val in kfold.split(X_train,y_train):
nn_model = build_nn()
history = nn_model.fit(X_train[train],y_train[train],
validation_data=(X_train[val],y_train[val]),
epochs=EPOCHS, batch_size=BATCH_SIZE, verbose=0)
scores = nn_model.evaluate(X_train[val],y_train[val],ver... | Natural Language Processing with Disaster Tweets |
17,733,566 | model.save('model.h5' )<choose_model_class> | nn_model = build_nn()
history = nn_model.fit(X_tr,y_tr, validation_data=(X_val,y_val),
epochs=EPOCHS, batch_size=BATCH_SIZE,verbose=0)
scores= nn_model.evaluate(X_val,y_val,verbose=0)
print(f"Accuracy: {scores[1]}")
print(f"F1 Score: {eval_f1_score(X_val,y_val,nn_model)}" ) | Natural Language Processing with Disaster Tweets |
17,733,566 | def define_model(length, vocab_size):
inputs1 = Input(shape=(length,))
embedding1 = Embedding(vocab_size, 100 )(inputs1)
conv1 = Conv1D(32, 4, activation='relu' )(embedding1)
drop1 = Dropout(0.5 )(conv1)
pool1 = MaxPooling1D()(drop1)
flat1 = Flatten()(pool1)
inputs2 = Input(shape=(length,))
embedding2 = Embedding(... | def build_LSTM() :
lstm_model = tf.keras.Sequential()
lstm_model.add(layers.Input(shape=(None,300)))
lstm_model.add(layers.LSTM(16))
lstm_model.add(layers.Dense(8, activation="tanh"))
lstm_model.add(layers.Dense(8, activation="tanh"))
lstm_model.add(layers.Dense(1,activation="sigmoid"))
lstm_model.compile(loss=tf.kera... | Natural Language Processing with Disaster Tweets |
17,733,566 | encoded_docs = t.texts_to_sequences(X_train.tolist())
padded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post')
<train_model> | EPOCHS = 30;
BATCH_SIZE = 64; | Natural Language Processing with Disaster Tweets |
17,733,566 | model = define_model(max_length,vocab_size)
model.fit([padded_docs,padded_docs,padded_docs], array(y_train), epochs=7, batch_size=16 )<compute_test_metric> | kfold = KFold(n_splits=4, shuffle=True, random_state=1 ) | Natural Language Processing with Disaster Tweets |
17,733,566 | loss, accuracy = model.evaluate([padded_docs,padded_docs,padded_docs], y_train, verbose=0 )<categorify> | fold = 0
history_by_fold = []
cv_results = []
for train, val in kfold.split(nlp_train,y_train):
lstm_model = build_LSTM()
history = lstm_model.fit(nlp_train[train],y_train[train],
validation_data=(nlp_train[val],y_train[val]),
epochs=EPOCHS,batch_size=BATCH_SIZE,verbose=0)
scores = lstm_model.evaluate(nlp_train[val],y... | Natural Language Processing with Disaster Tweets |
17,733,566 | encoded_docs = t.texts_to_sequences(X_test.tolist())
padded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post' )<predict_on_test> | lstm_model = build_LSTM()
history = lstm_model.fit(nlp_tr,y_tr,validation_data=(nlp_val,y_val), epochs=EPOCHS, batch_size=BATCH_SIZE ) | Natural Language Processing with Disaster Tweets |
17,733,566 | _, acc = model.evaluate([padded_docs,padded_docs,padded_docs], array(y_test), verbose=0)
print('Train Accuracy: %.2f' %(acc*100))<categorify> | valid_predict =(lstm_model.predict(nlp_val)> 0.5)
f1 = f1_score(y_val, valid_predict)
print(f" F1 Score: {f1}" ) | Natural Language Processing with Disaster Tweets |
17,733,566 | encoded_docs = t.texts_to_sequences(test.text.tolist())
padded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post' )<predict_on_test> | lr_keywords = LogisticRegression(max_iter=500)
lr_keywords.fit(kw_tr,y_tr)
val_pred = lr_keywords.predict(kw_val)
print(f"Accurcay: {accuracy_score(y_val, val_pred)}")
print(f"F1 score: {f1_score(y_val,val_pred)}" ) | Natural Language Processing with Disaster Tweets |
17,733,566 | y_test_pred = model.predict([padded_docs,padded_docs,padded_docs] )<save_to_csv> | nn_tr_predict = nn_model.predict(X_tr)
kw_tr_predict = lr_keywords.predict_proba(kw_tr)[:,1]
lstm_tr_predict = lstm_model.predict(nlp_tr)
nn_val_predict = nn_model.predict(X_val)
kw_val_predict = lr_keywords.predict_proba(kw_val)[:,1]
lstm_val_predict = lstm_model.predict(nlp_val)
kw_tr_predict = kw_tr_predict.resh... | Natural Language Processing with Disaster Tweets |
17,733,566 | sub = pd.DataFrame()
sub['Id'] = test_id
sub['target'] = y_test_pred
sub.to_csv('submission_multi-cnn.csv',index=False )<load_from_url> | lr = LogisticRegression()
lr.fit(concat_tr,y_tr)
val_pred = lr.predict(concat_val)
print(f"Accurcay: {accuracy_score(y_val, val_pred)}")
print(f"F1 score: {f1_score(y_val,val_pred)}" ) | Natural Language Processing with Disaster Tweets |
17,733,566 | !wget --quiet https://raw.githubusercontent.com/tensorflow/models/master/official/nlp/bert/tokenization.py<import_modules> | X_test = process_data(df_test.text ) | Natural Language Processing with Disaster Tweets |
17,733,566 | from tensorflow.keras.layers import Dense, Input
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.models import Model
from tensorflow.keras.callbacks import ModelCheckpoint
import tensorflow_hub as hub
import tokenization<load_from_csv> | nlp_test = build_nlp_vectors(df_test.text ) | Natural Language Processing with Disaster Tweets |
17,733,566 | train= pd.read_csv('.. /input/nlp-getting-started/train.csv')
test=pd.read_csv('.. /input/nlp-getting-started/test.csv' )<categorify> | df_test["nn_predict"]= nn_model.predict(X_test)
df_test["lstm_predict"]= lstm_model.predict(nlp_test)
df_test["keyword_predict"] = lr_keywords.predict_proba(keyword_test)[:,1]
features = ["nn_predict","keyword_predict","lstm_predict"]
test_features = df_test[features]
predict = lr.predict(test_features ) | Natural Language Processing with Disaster Tweets |
17,733,566 | <choose_model_class><EOS> | output = pd.DataFrame({"id":df_test.id, "target":predict})
output.to_csv("submission.csv",index=False)
output | Natural Language Processing with Disaster Tweets |
17,691,511 | <SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<choose_model_class> | %matplotlib inline
InteractiveShell.ast_node_interactivity = 'all'
!pip install chart_studio
plotly.offline.init_notebook_mode(connected=True)
cufflinks.go_offline()
cufflinks.set_config_file(world_readable=True, theme='pearl')
warnings.filterwarnings('ignore' ) | Natural Language Processing with Disaster Tweets |
17,691,511 | %%time
module_url = "https://tfhub.dev/tensorflow/bert_en_uncased_L-24_H-1024_A-16/1"
bert_layer = hub.KerasLayer(module_url, trainable=True )<data_type_conversions> | data = pd.read_csv('.. /input/nlp-getting-started/train.csv' ) | Natural Language Processing with Disaster Tweets |
17,691,511 | vocab_file = bert_layer.resolved_object.vocab_file.asset_path.numpy()
do_lower_case = bert_layer.resolved_object.do_lower_case.numpy()<choose_model_class> | def create_corpus(target):
corpus = []
for i in data[data['target']==target]['text'].str.split() :
for x in i:
corpus.append(x)
return corpus | Natural Language Processing with Disaster Tweets |
17,691,511 | tokenizer = tokenization.FullTokenizer(vocab_file, do_lower_case)
<categorify> | lemmatizer = WordNetLemmatizer()
def preprocess_data(data):
text = re.sub(r'https?://\S+|www\.\S+|http?://\S+',' ',data)
text = re.sub(r"won't", " will not", text)
text = re.sub(r"won't've", " will not have", text)
text = re.sub(r"can't", " can not", text)
text = re.sub(r"don't", " do not", text)
text = re.sub(r"c... | Natural Language Processing with Disaster Tweets |
17,691,511 | train_input = bert_encode(train.text.values, tokenizer, max_len=160)
test_input = bert_encode(test.text.values, tokenizer, max_len=160)
train_labels = train.target.values<train_model> | common_words = ['via','like','build','get','would','one','two','feel',
'lol','fuck','take','way','may','first','latest','want',
'make','back','see','know','let','look','come','got',
'still','say','think','great','pleas','amp']
def text_cleaning(data):
return ' '.join(i for i in data.split() if i not in common_words)
d... | Natural Language Processing with Disaster Tweets |
17,691,511 | train_history = model.fit(
train_input, train_labels,
validation_split=0.2,
epochs=3,
batch_size=16
)<predict_on_test> | def top_ngrams(data,n,grams):
count_vec = CountVectorizer(ngram_range=(grams,grams)).fit(data)
bow = count_vec.transform(data)
add_words = bow.sum(axis=0)
word_freq = [(word, add_words[0, idx])for word, idx in count_vec.vocabulary_.items() ]
word_freq = sorted(word_freq, key = lambda x: x[1], reverse=True)
return w... | Natural Language Processing with Disaster Tweets |
17,691,511 | test_pred = model.predict(test_input )<save_to_csv> | common_uni = top_ngrams(data["Cleaned_text"],10,1)
common_bi = top_ngrams(data["Cleaned_text"],10,2)
common_tri = top_ngrams(data["Cleaned_text"],10,3)
common_uni_df = pd.DataFrame(common_uni,columns=['word','freq'])
common_bi_df = pd.DataFrame(common_bi,columns=['word','freq'])
common_tri_df = pd.DataFrame(common... | Natural Language Processing with Disaster Tweets |
17,691,511 | submission=pd.DataFrame()
submission['Id']=test_id
submission['target'] = test_pred.round().astype(int)
submission.to_csv('submission_3.csv', index=False)
<set_options> | X_inp_clean = data['Cleaned_text']
X_inp_original = data['text']
y_inp = data['target'] | Natural Language Processing with Disaster Tweets |
17,691,511 | np.random.seed(1)
nltk.download('stopwords')
tf.random.set_seed(1)
pd.set_option('display.max_colwidth', 500)
warnings.filterwarnings('ignore' )<load_from_csv> | word_tokenizer = Tokenizer()
word_tokenizer.fit_on_texts(X_inp_clean.values)
vocab_length = len(word_tokenizer.word_index)+ 1 | Natural Language Processing with Disaster Tweets |
17,691,511 | train = pd.read_csv(".. /input/nlp-getting-started/train.csv")
test = pd.read_csv(".. /input/nlp-getting-started/test.csv")
print("Train Shape :", train.shape)
print("Test Shape :", test.shape )<count_missing_values> | def embed(corpus):
return word_tokenizer.texts_to_sequences(corpus)
longest_train = max(X_inp_clean.values, key=lambda sentence: len(word_tokenize(sentence)))
length_long_sentence = len(word_tokenize(longest_train))
padded_sentences = pad_sequences(embed(X_inp_clean.values),
length_long_sentence, padding='post' ) | Natural Language Processing with Disaster Tweets |
17,691,511 | train.isnull().sum()<count_missing_values> | embeddings_dictionary = dict()
embedding_dim = 100
glove_file = open('.. /input/glove6b100dtxt/glove.6B.100d.txt')
for line in glove_file:
records = line.split()
word = records[0]
vector_dimensions = np.asarray(records[1:], dtype='float32')
embeddings_dictionary [word] = vector_dimensions
glove_file.close() | Natural Language Processing with Disaster Tweets |
17,691,511 | train.isnull().sum()<count_values> | embedding_matrix = np.zeros(( vocab_length, embedding_dim))
for word, index in word_tokenizer.word_index.items() :
embedding_vector = embeddings_dictionary.get(word)
if embedding_vector is not None:
embedding_matrix[index] = embedding_vector | Natural Language Processing with Disaster Tweets |
17,691,511 | train['target'].value_counts(normalize = True )<count_values> | X_train, X_val, y_train, y_val = train_test_split(padded_sentences,
y_inp.values,test_size=0.2,random_state=1 ) | Natural Language Processing with Disaster Tweets |
17,691,511 | train.keyword.value_counts()<count_values> | def CNN(hp):
model = keras.Sequential()
hp_learning_rate = hp.Choice('learning_rate', values=[3e-2, 3e-3, 3e-4, 3e-5])
model.add(Embedding(vocab_length, 100, weights=[embedding_matrix],
input_length=length_long_sentence,trainable=False))
model.add(Conv1D(filters=hp.Int('conv_1_filter',min_value=21,max_value=200,step=1... | Natural Language Processing with Disaster Tweets |
17,691,511 | train.location.value_counts()<filter> | tuner_CNN = kt.Hyperband(CNN,objective='val_accuracy',
max_epochs=15,factor=5,
directory='my_dir',
project_name='DisasterTweets_kt',
overwrite=True ) | Natural Language Processing with Disaster Tweets |
17,691,511 | real_tweets = train[train['target']==1]['text']
real_tweets.values[0:5]<define_variables> | stop_early = EarlyStopping(monitor='val_loss', mode='min',
verbose=1, patience=10)
tuner_CNN.search(X_train, y_train, epochs=15,
validation_data=(X_val,y_val),callbacks=[stop_early])
best_hps_CNN=tuner_CNN.get_best_hyperparameters(num_trials=1)[0] | Natural Language Processing with Disaster Tweets |
17,691,511 | fake_tweets = train[train['target']==0]['text']
fake_tweets.values[0:5]<string_transform> | model_CNN = tuner_CNN.hypermodel.build(best_hps_CNN)
checkpoint = ModelCheckpoint(
'model_CNN.h5',
monitor = 'val_loss',
verbose = 1,
save_best_only = True
)
history_CNN = model_CNN.fit(X_train, y_train,epochs=50,
validation_data=(X_val,y_val),
callbacks=[checkpoint,stop_early] ) | Natural Language Processing with Disaster Tweets |
17,691,511 | def clean_text(text):
text = text.lower()
text = re.sub('\[.*?\]', '', text)
text = re.sub('https?://\S+|www\.\S+', '', text)
text = re.sub('<.*?>+', '', text)
text = re.sub('[%s]' % re.escape(string.punctuation), '', text)
text = re.sub('
', '', text)
text = re.sub('\w*\d\w*', '', text)
return text<feature_engin... | def MultichannelCNN(hp):
inputs1 = Input(shape=(length_long_sentence,))
embedding1 = Embedding(vocab_length, 100, weights=[embedding_matrix],
input_length=length_long_sentence, trainable=False )(inputs1)
conv1 = Conv1D(filters=hp.Int('conv_1_filter',min_value=21,max_value=150,step=14),
kernel_size=hp.Choice('conv_1_ke... | Natural Language Processing with Disaster Tweets |
17,691,511 | train['cleaned_text'] = train['text'].apply(lambda x: clean_text(x))
test['cleaned_text'] = test['text'].apply(lambda x: clean_text(x))
train['cleaned_text'].head()<feature_engineering> | tuner_MCNN = kt.Hyperband(MultichannelCNN,objective='val_accuracy',
max_epochs=15,factor=5,
directory='my_dir',
project_name='DisasterTweetsMCNN_kt',
overwrite=True)
stop_early = EarlyStopping(monitor='val_loss', mode='min',
verbose=1, patience=10)
tuner_MCNN.search([X_train,X_train], y_train, epochs=15,
validation_d... | Natural Language Processing with Disaster Tweets |
17,691,511 | !pip install nlppreprocess
nlp = NLP()
train['stopwords_cleaned'] = train['cleaned_text'].apply(nlp.process)
test['stopwords_cleaned'] = test['cleaned_text'].apply(nlp.process )<categorify> | model_MCNN = tuner_MCNN.hypermodel.build(best_hps_MCNN)
checkpoint = ModelCheckpoint(
'model_MCNN.h5',
monitor = 'val_loss',
verbose = 1,
save_best_only = True
)
history_MCNN = model_MCNN.fit([X_train,X_train], y_train,epochs=50,
validation_data=([X_val,X_val], y_val),
callbacks=[checkpoint,stop_early] ) | Natural Language Processing with Disaster Tweets |
17,691,511 | en_model = spacy.load('en', disable=['parser', 'ner'])
def lemmatization(texts):
output = []
for i in texts:
s = [token.lemma_ for token in en_model(i)]
output.append(' '.join(s))
return output<categorify> | def BiLSTM(hp):
model = Sequential()
model.add(Embedding(input_dim=embedding_matrix.shape[0],
output_dim=embedding_matrix.shape[1],
weights = [embedding_matrix],
input_length=length_long_sentence,trainable = False))
model.add(Bidirectional(CuDNNLSTM(units = hp.Int('dense_1',
min_value=21,max_value=120,step=14)
,return... | Natural Language Processing with Disaster Tweets |
17,691,511 | train['lemmatized_text'] = lemmatization(train['stopwords_cleaned'])
test['lemmatized_text'] = lemmatization(test['stopwords_cleaned'] )<split> | tuner_BiLSTM = kt.Hyperband(BiLSTM,objective='val_accuracy',
max_epochs=15,factor=5,
directory='my_dir',
project_name='DisasterTweetsBiLSTM_kt',
overwrite=True)
stop_early = EarlyStopping(monitor='val_loss', mode='min',
verbose=1, patience=12)
tuner_BiLSTM.search(X_train, y_train, epochs=15,
validation_data=(X_val, y... | Natural Language Processing with Disaster Tweets |
17,691,511 | x_train, x_test, y_train, y_test = train_test_split(train['stopwords_cleaned'], train['target'],
test_size = 0.2, random_state = 1 )<choose_model_class> | model_BiLSTM = tuner_BiLSTM.hypermodel.build(best_hps_BiLSTM)
checkpoint = ModelCheckpoint(
'model_BiLSTM.h5',
monitor = 'val_loss',
verbose = 1,
save_best_only = True
)
history_BiLSTM = model_BiLSTM.fit(X_train, y_train, epochs=50,
validation_data=(X_val, y_val),
callbacks=[checkpoint,stop_early] ) | Natural Language Processing with Disaster Tweets |
17,691,511 | hub_layer = hub.KerasLayer('https://tfhub.dev/google/universal-sentence-encoder/4',
input_shape = [],
output_shape = [512],
dtype = tf.string,
trainable = True)
model = tf.keras.models.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(128, activation = 'relu'))
model.add(tf.keras.layers.Dense(32, acti... | onehot_encoder = OneHotEncoder(sparse=False)
y =(np.asarray(y_inp)).reshape(-1,1)
Y = onehot_encoder.fit_transform(y)
X_train, X_val, y_train, y_val = train_test_split(X_inp_clean,Y,
test_size=0.2, random_state=1 ) | Natural Language Processing with Disaster Tweets |
17,691,511 | model.compile(optimizer = 'adam',
loss = 'binary_crossentropy',
metrics = ['accuracy'] )<train_model> | model_checkpoint = "distilbert-base-uncased-finetuned-sst-2-english"
tokenizer = AutoTokenizer.from_pretrained(model_checkpoint, use_fast=True ) | Natural Language Processing with Disaster Tweets |
17,691,511 | model.fit(x_train,
y_train,
epochs = 1,
validation_data =(x_test, y_test))<predict_on_test> | tokenizer("Hello, this one sentence!", "And this sentence goes with it." ) | Natural Language Processing with Disaster Tweets |
17,691,511 | pred = model.predict_classes(test['stopwords_cleaned'] )<save_to_csv> | def regular_encode(texts, tokenizer, maxlen=512):
enc_di = tokenizer.batch_encode_plus(
texts,
return_token_type_ids=False,
pad_to_max_length=True,
max_length=maxlen,
add_special_tokens = True,
truncation=True
)
return np.array(enc_di['input_ids'])
X_train_t = regular_encode(list(X_train), tokenizer, maxlen=512)
X... | Natural Language Processing with Disaster Tweets |
17,691,511 | submission = pd.read_csv(".. /input/nlp-getting-started/sample_submission.csv")
submission['target'] = pred
submission.to_csv('submission.csv', index=False )<save_to_csv> | AUTO = tf.data.experimental.AUTOTUNE
batch_size = 16
train_dataset =(
tf.data.Dataset
.from_tensor_slices(( X_train_t, y_train))
.repeat()
.shuffle(1995)
.batch(batch_size)
.prefetch(AUTO)
)
valid_dataset =(
tf.data.Dataset
.from_tensor_slices(( X_val_t, y_val))
.batch(batch_size)
.cache()
.prefetch(AUTO)
) | Natural Language Processing with Disaster Tweets |
17,691,511 | submission.to_csv("submission.csv", index = False )<set_options> | def build_model(transformer, max_len=512):
input_word_ids = Input(shape=(max_len,), dtype=tf.int32,
name="input_word_ids")
sequence_output = transformer(input_word_ids)[0]
cls_token = sequence_output[:, 0, :]
out = Dense(2, activation='softmax' )(cls_token)
model = Model(inputs=input_word_ids, outputs=out)
model.com... | Natural Language Processing with Disaster Tweets |
17,691,511 | np.random.seed(0)
plt.style.use('ggplot')
stop=set(stopwords.words('english'))
np.random.seed(1)
for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
print(os.path.join(dirname, filename))
<load_from_csv> | transformer_layer = TFAutoModel.from_pretrained(model_checkpoint)
model_DistilBert = build_model(transformer_layer ) | Natural Language Processing with Disaster Tweets |
17,691,511 | train= pd.read_csv('.. /input/nlp-getting-started/train.csv')
test=pd.read_csv('.. /input/nlp-getting-started/test.csv')
train.head()<count_missing_values> | n_steps = X_train.shape[0] // batch_size
history_DistilBert = model_DistilBert.fit(train_dataset,
steps_per_epoch=n_steps,
validation_data=valid_dataset,
epochs=3 ) | Natural Language Processing with Disaster Tweets |
17,691,511 | train.isnull().sum(axis=0 )<count_missing_values> | test = pd.read_csv('.. /input/nlp-getting-started/test.csv')
test["Cleaned_text"] = test["text"].apply(preprocess_data)
test["Cleaned_text"] = test["Cleaned_text"].apply(text_cleaning)
test_sentences = pad_sequences(embed(test.Cleaned_text.values),
length_long_sentence, padding='post' ) | Natural Language Processing with Disaster Tweets |
17,691,511 | test.isnull().sum(axis=0 )<count_values> | predsCNN = model_CNN.predict_classes(test_sentences)
predictions_test = pd.DataFrame(predsCNN)
test_id = pd.DataFrame(test["id"])
submissionCNN = pd.concat([test_id,predictions_test],axis=1)
submissionCNN.columns = ["id","target"]
submissionCNN.to_csv("submissionCNN.csv",index=False ) | Natural Language Processing with Disaster Tweets |
17,691,511 | keyword_cnt = train.keyword.value_counts()
keyword_cnt<count_values> | predsMCNN = model_MCNN.predict([test_sentences,test_sentences])
predsMCNN =(predsMCNN[:,0] > 0.5 ).astype(np.int)
predictions_test = pd.DataFrame(predsMCNN)
submissionMCNN = pd.concat([test_id,predictions_test],axis=1)
submissionMCNN.columns = ["id","target"]
submissionMCNN.to_csv("submissionMCNN.csv",index=False ) | Natural Language Processing with Disaster Tweets |
17,691,511 | train_fake = train[train['target'] == 1]
keyword_cnt_fake = train_fake.keyword.value_counts()
keyword_cnt_fake<string_transform> | predsBiLSTM = model_BiLSTM.predict(test_sentences)
predsBiLSTM =(predsBiLSTM[:,0] > 0.5 ).astype(np.int)
predictions_test = pd.DataFrame(predsBiLSTM)
submissionBiLSTM = pd.concat([test_id,predictions_test],axis=1)
submissionBiLSTM.columns = ["id","target"]
submissionBiLSTM.to_csv("submissionBiLSTM.csv",index=False ... | Natural Language Processing with Disaster Tweets |
17,691,511 | n_corpus=[]
for text in tqdm(train['text']):
text = re.sub(r'https?://\S+|www\.\S+', '', text)
text = re.sub(r'<.*?>', '', text)
text = re.sub(r'[^a-zA-Z0-9]+', ' ', text)
text = re.sub(r'[0-9]', '', text)
text = text.lower()
text = nltk.word_tokenize(text)
ps = PorterStemmer()
text = [ps.stem(word)for word in tex... | X_test = regular_encode(list(test.Cleaned_text), tokenizer, maxlen=512)
test1 =(tf.data.Dataset.from_tensor_slices(X_test ).batch(batch_size))
pred = model_DistilBert.predict(test1,verbose = 0)
pred = np.argmax(pred,axis=-1)
pred = pred.astype('int32')
res=pd.read_csv('.. /input/nlp-getting-started/sample_submissio... | Natural Language Processing with Disaster Tweets |
10,225,902 | train['text_n']=n_corpus
train.drop('text',axis=1 )<string_transform> | import transformers
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.model_selection import train_test_split | 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.