kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
10,225,902
n_corpus=[] for text in tqdm(test['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 text...
train_df = pd.read_csv('/kaggle/input/nlp-getting-started/train.csv') test_df = pd.read_csv('/kaggle/input/nlp-getting-started/test.csv' )
Natural Language Processing with Disaster Tweets
10,225,902
test['text_n']=n_corpus test.drop('text',axis=1 )<load_from_url>
X = train_df.loc[:,'text'] y = train_df.loc[:,'target']
Natural Language Processing with Disaster Tweets
10,225,902
!wget --quiet https://raw.githubusercontent.com/tensorflow/models/master/official/nlp/bert/tokenization.py<import_modules>
max_len = 0 for text in X: max_len = max(max_len, len(text)) max_len
Natural Language Processing with Disaster Tweets
10,225,902
import tensorflow as tf 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<categorify>
class Dataset(torch.utils.data.Dataset): def __init__(self,df,y=None,max_len=164): self.df = df self.y = y self.max_len= max_len self.tokenizer = transformers.RobertaTokenizer.from_pretrained('roberta-base') def __getitem__(self,index): row = self.df.iloc[index] ids,masks = self.get_input_data(row) data = {} data['id...
Natural Language Processing with Disaster Tweets
10,225,902
def bert_encode(texts, tokenizer, max_len=512): all_tokens = [] all_masks = [] all_segments = [] for text in texts: text = tokenizer.tokenize(text) text = text[:max_len-2] input_sequence = ["[CLS]"] + text + ["[SEP]"] pad_len = max_len - len(input_sequence) tokens = tokenizer.convert_tokens_to_ids(input_sequence) to...
train_x,val_x,train_y,val_y = train_test_split(X,y,test_size=0.2,stratify=y) train_loader = torch.utils.data.DataLoader(Dataset(train_x,train_y),batch_size=16,shuffle=True,num_workers=2) val_loader = torch.utils.data.DataLoader(Dataset(val_x,val_y),batch_size=16,shuffle=False,num_workers=2 )
Natural Language Processing with Disaster Tweets
10,225,902
def build_model(bert_layer, max_len=512): input_word_ids = Input(shape=(max_len,), dtype=tf.int32, name="input_word_ids") input_mask = Input(shape=(max_len,), dtype=tf.int32, name="input_mask") segment_ids = Input(shape=(max_len,), dtype=tf.int32, name="segment_ids") _, sequence_output = bert_layer([input_word_ids, ...
class Model(nn.Module): def __init__(self): super(Model,self ).__init__() self.distilBert = transformers.RobertaModel.from_pretrained('roberta-base') self.l0 = nn.Linear(768,512) self.l1 = nn.Linear(512,256) self.l2 = nn.Linear(256,1) self.d0 = nn.Dropout(0.5) self.d1 = nn.Dropout(0.5) self.d2 = nn.Dropout(0.5) ...
Natural Language Processing with Disaster Tweets
10,225,902
module_url = "https://tfhub.dev/tensorflow/bert_en_uncased_L-24_H-1024_A-16/1" bert_layer = hub.KerasLayer(module_url, trainable=True )<feature_engineering>
model = Model().to('cuda') criterion = nn.BCEWithLogitsLoss(reduction='mean') optimizer = torch.optim.AdamW(model.parameters() ,lr=3e-5 )
Natural Language Processing with Disaster Tweets
10,225,902
vocab_file = bert_layer.resolved_object.vocab_file.asset_path.numpy() do_lower_case = bert_layer.resolved_object.do_lower_case.numpy() tokenizer = tokenization.FullTokenizer(vocab_file, do_lower_case )<categorify>
def accuracy_score(outputs,labels): outputs = torch.round(torch.sigmoid(outputs)) correct =(outputs == labels ).sum().float() return correct/labels.size(0 )
Natural Language Processing with Disaster Tweets
10,225,902
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>
from tqdm import tqdm
Natural Language Processing with Disaster Tweets
10,225,902
train_history = model.fit( train_input, train_labels, validation_split=0.2, epochs=3, batch_size=16 ) model.save('model.h5' )<save_to_csv>
epochs = 4 for epoch in range(epochs): epoch_loss = 0. model.train() for data in tqdm(train_loader): ids = data['ids'].cuda() masks = data['masks'].cuda() labels = data['out'].cuda() labels = labels.unsqueeze(1) optimizer.zero_grad() outputs = model(ids,masks) loss = criterion(outputs,labels) loss.backward() optimi...
Natural Language Processing with Disaster Tweets
10,225,902
test_pred = model.predict(test_input) submission=pd.read_csv('/kaggle/input/nlp-getting-started/sample_submission.csv') submission['target'] = test_pred.round().astype(int) submission.to_csv('submission.csv', index=False) <install_modules>
test_loader = torch.utils.data.DataLoader(Dataset(test_df['text'],y=None),batch_size=16,shuffle=False,num_workers=2 )
Natural Language Processing with Disaster Tweets
10,225,902
!pip install bert-for-tf2 !pip install sentencepiece<import_modules>
preds = [] for data in test_loader: ids = data['ids'].cuda() masks = data['masks'].cuda() model.eval() outputs = model(ids,masks) preds += outputs.cpu().detach().numpy().tolist()
Natural Language Processing with Disaster Tweets
10,225,902
try: %tensorflow_version 2.x except Exception: pass <compute_test_metric>
pred = np.round(1/(1 + np.exp(-np.array(preds))))
Natural Language Processing with Disaster Tweets
10,225,902
def recall_m(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))) recall = true_positives /(possible_positives + K.epsilon()) return recall def precision_m(y_true, y_pred): true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1...
pred = np.array(pred,dtype=np.uint8 )
Natural Language Processing with Disaster Tweets
10,225,902
train= pd.read_csv('.. /input/extensive-pre-processing-for-bert/processed train.csv') train.head(5 )<filter>
sub = pd.read_csv('/kaggle/input/nlp-getting-started/sample_submission.csv' )
Natural Language Processing with Disaster Tweets
10,225,902
train.loc[4,'processed_text']<load_from_csv>
sub['target'] = pred
Natural Language Processing with Disaster Tweets
10,225,902
test=pd.read_csv('.. /input/extensive-pre-processing-for-bert/processed test.csv') test = test.set_index(test['id']) test.head(5 )<load_from_csv>
sub.to_csv('submission.csv',index=False )
Natural Language Processing with Disaster Tweets
10,157,262
test_actual = pd.read_csv("https://raw.githubusercontent.com/sampath9dasari/GSU/master/true%20submission.csv") test_labels = test_actual.target.to_numpy()<choose_model_class>
SEED = 42 torch.manual_seed(SEED) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False
Natural Language Processing with Disaster Tweets
10,157,262
module_url = "https://tfhub.dev/tensorflow/bert_en_uncased_L-24_H-1024_A-16/1" bert_layer = hub.KerasLayer(module_url, trainable=True) <string_transform>
train_data = pd.read_csv(".. /input/nlp-getting-started/train.csv") train_data.info() train_data.sample(10 )
Natural Language Processing with Disaster Tweets
10,157,262
def bert_encode(texts, tokenizer, max_len=50): all_tokens = [] all_masks = [] all_segments = [] for text in texts: text = tokenizer.tokenize(text) text = text[:max_len-2] input_sequence = ["[CLS]"] + text + ["[SEP]"] pad_len = max_len - len(input_sequence) tokens = tokenizer.convert_tokens_to_ids(input_sequence) t...
test_data = pd.read_csv(".. /input/nlp-getting-started/test.csv") test_data.info() test_data.sample(10 )
Natural Language Processing with Disaster Tweets
10,157,262
BertTokenizer = bert.bert_tokenization.FullTokenizer vocab_file = bert_layer.resolved_object.vocab_file.asset_path.numpy() do_lower_case = bert_layer.resolved_object.do_lower_case.numpy() tokenizer = BertTokenizer(vocab_file, do_lower_case )<categorify>
print('Training Set Shape = {}'.format(train_data.shape)) print('Test Set Shape = {}'.format(test_data.shape))
Natural Language Processing with Disaster Tweets
10,157,262
full_input = bert_encode(train.processed_text.values, tokenizer, max_len=50) full_labels = train.target.values.copy()<split>
mislabeled_df = train_data.groupby(['text'] ).nunique().sort_values(by='target', ascending=False) mislabeled_df = mislabeled_df[mislabeled_df['target'] > 1]['target'] mislabeled_list = mislabeled_df.index.tolist() mislabeled_list
Natural Language Processing with Disaster Tweets
10,157,262
train_data, val_data, train_labels, val_labels = train_test_split(train.processed_text.values, train.target.values, test_size=0.15, random_state=10) train_input = bert_encode(train_data, tokenizer, max_len=50) val_input = bert_encode(val_data, tokenizer, max_len=50) test_input = bert_encode(test.processed_text.value...
train_data['target_relabeled'] = train_data['target'].copy() train_data.loc[train_data['text'] == 'like for the music video I want some real action shit like burning buildings and police chases not some weak ben winston shit', 'target_relabeled'] = 0 train_data.loc[train_data['text'] == 'Hellfire is surrounded by desir...
Natural Language Processing with Disaster Tweets
10,157,262
<define_search_space>
def clean(tweet): tweet = re.sub(r"\x89Û_", "", tweet) tweet = re.sub(r"\x89ÛÒ", "", tweet) tweet = re.sub(r"\x89ÛÓ", "", tweet) tweet = re.sub(r"\x89ÛÏWhen", "When", tweet) tweet = re.sub(r"\x89ÛÏ", "", tweet) tweet = re.sub(r"China\x89Ûªs", "China's", tweet) tweet = re.sub(r"let\x89Ûªs", "let's", tweet) tweet ...
Natural Language Processing with Disaster Tweets
10,157,262
learning_rate=1e-5 decay=5e-5 max_len=50 lr_schedule = [9e-7,1e-8,5e-8,9e-8,7e-9,1e-9] K.clear_session()<choose_model_class>
train_df, valid_df = train_test_split(train_data, test_size=0.20, random_state= random.seed(SEED))
Natural Language Processing with Disaster Tweets
10,157,262
input_word_ids = Input(shape=(max_len,), dtype=tf.int32, name="input_word_ids") input_mask = Input(shape=(max_len,), dtype=tf.int32, name="input_mask") segment_ids = Input(shape=(max_len,), dtype=tf.int32, name="segment_ids") pooled_output, sequence_output = bert_layer([input_word_ids, input_mask, segment_ids]) clf...
TEXT = data.Field(tokenize = 'spacy', batch_first=True, include_lengths = True) LABEL = data.LabelField(dtype = torch.float, batch_first=True )
Natural Language Processing with Disaster Tweets
10,157,262
sBERT = Model(inputs=[input_word_ids, input_mask, segment_ids], outputs=out) sBERT.compile(Adam(lr=learning_rate, decay=decay), loss='binary_crossentropy', metrics=['accuracy',f1_m]) sBERT.summary()<load_pretrained>
class DataFrameDataset(data.Dataset): def __init__(self, df, fields, is_test=False, **kwargs): examples = [] for i, row in df.iterrows() : label = row.target_relabeled if not is_test else None text = row.text examples.append(data.Example.fromlist([text, label], fields)) super().__init__(examples, fields, **kwargs) @st...
Natural Language Processing with Disaster Tweets
10,157,262
init_weights = sBERT.get_weights()<choose_model_class>
fields = [('text',TEXT),('label',LABEL)] train_ds, val_ds = DataFrameDataset.splits(fields, train_df=train_df, val_df=valid_df )
Natural Language Processing with Disaster Tweets
10,157,262
checkpoint1 = ModelCheckpoint('best_accuracy.h5', monitor='val_f1_m', save_best_only=True) train_history = sBERT.fit( full_input, full_labels, epochs = 1, batch_size = 16 ) test_pred = sBERT.predict(test_input) print(" - test_f1_score: {}".format(f1_score(test_labels,test_pred.round()))) print() sBERT.save_weight...
vectors = Vectors(name='.. /input/fasttext-crawl-300d-2m/crawl-300d-2M.vec', cache='./') MAX_VOCAB_SIZE = 100000 TEXT.build_vocab(train_ds, max_size = MAX_VOCAB_SIZE, vectors = vectors, unk_init = torch.Tensor.zero_) LABEL.build_vocab(train_ds )
Natural Language Processing with Disaster Tweets
10,157,262
K.set_value(sBERT.optimizer.lr, 1e-6) sBERT.fit( full_input, full_labels, epochs = 1, batch_size = 16 ) test_pred = sBERT.predict(test_input) epoch_test_accuracy = f1_score(test_labels,test_pred.round()) print(" - test_f1_score: {}".format(epoch_test_accuracy)) print() if epoch_test_accuracy >= test_accuracy: sBE...
print("Size of TEXT vocabulary:",len(TEXT.vocab)) print("Size of LABEL vocabulary:",len(LABEL.vocab)) print(TEXT.vocab.freqs.most_common(10))
Natural Language Processing with Disaster Tweets
10,157,262
K.set_value(sBERT.optimizer.lr, 1e-7) sBERT.fit( full_input, full_labels, epochs = 1, batch_size = 16 ) test_pred = sBERT.predict(test_input) epoch_test_accuracy = f1_score(test_labels,test_pred.round()) print(" - test_f1_score: {}".format(epoch_test_accuracy)) print() if epoch_test_accuracy >= test_accuracy: sBE...
BATCH_SIZE = 64 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') train_iterator, valid_iterator = data.BucketIterator.splits( (train_ds, val_ds), batch_size = BATCH_SIZE, sort_within_batch = True, device = device )
Natural Language Processing with Disaster Tweets
10,157,262
sBERT.layers[3].trainable = False sBERT.compile(Adam(lr=1e-6, decay=1e-6), loss='binary_crossentropy', metrics=['accuracy',f1_m] )<train_model>
num_epochs = 25 learning_rate = 0.001 INPUT_DIM = len(TEXT.vocab) EMBEDDING_DIM = 300 HIDDEN_DIM = 256 OUTPUT_DIM = 1 N_LAYERS = 2 BIDIRECTIONAL = True DROPOUT = 0.2 PAD_IDX = TEXT.vocab.stoi[TEXT.pad_token]
Natural Language Processing with Disaster Tweets
10,157,262
sBERT.fit( full_input, full_labels, validation_data=(test_input, test_labels), epochs = 10, batch_size = 16 ) test_pred = sBERT.predict(test_input) epoch_test_accuracy = f1_score(test_labels,test_pred.round()) print(" - test_f1_score: {}".format(epoch_test_accuracy)) print() if epoch_test_accuracy >= test_accuracy...
class LSTM_net(nn.Module): def __init__(self, vocab_size, embedding_dim, hidden_dim, output_dim, n_layers, bidirectional, dropout, pad_idx): super().__init__() self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx = pad_idx) self.rnn = nn.LSTM(embedding_dim, hidden_dim, num_layers=n_layers, bidirectiona...
Natural Language Processing with Disaster Tweets
10,157,262
<load_pretrained>
model = LSTM_net(INPUT_DIM, EMBEDDING_DIM, HIDDEN_DIM, OUTPUT_DIM, N_LAYERS, BIDIRECTIONAL, DROPOUT, PAD_IDX )
Natural Language Processing with Disaster Tweets
10,157,262
sBERT.load_weights('best_accuracy.h5' )<categorify>
print(model) def count_parameters(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) print(f'The model has {count_parameters(model):,} trainable parameters' )
Natural Language Processing with Disaster Tweets
10,157,262
bert_encoder = Model(sBERT.inputs, sBERT.layers[-5].output) bert_encoder.summary() <categorify>
pretrained_embeddings = TEXT.vocab.vectors model.embedding.weight.data.copy_(pretrained_embeddings) model.embedding.weight.data[PAD_IDX] = torch.zeros(EMBEDDING_DIM )
Natural Language Processing with Disaster Tweets
10,157,262
bert_encoder.layers[3].trainable<predict_on_test>
def binary_accuracy(preds, y): rounded_preds = torch.round(torch.sigmoid(preds)) correct =(rounded_preds == y ).float() acc = correct.sum() / len(correct) return acc
Natural Language Processing with Disaster Tweets
10,157,262
%%time train_embed = bert_encoder.predict(train_input) test_embed = bert_encoder.predict(test_input )<load_pretrained>
def train(model, iterator, optimizer, criterion): epoch_loss = 0 epoch_acc = 0 model.train() for batch in iterator: text, text_lengths = batch.text optimizer.zero_grad() predictions = model(text, text_lengths ).squeeze(1) loss = criterion(predictions, batch.label) acc = binary_accuracy(predictions, batch.label) loss...
Natural Language Processing with Disaster Tweets
10,157,262
with open('Train BERT 1024d Embed', 'ab')as fo: pickle.dump(train_embed, fo) with open('Test BERT 1024d Embed', 'ab')as fo: pickle.dump(test_embed, fo )<import_modules>
def evaluate(model, iterator, criterion): epoch_loss = 0 epoch_acc = 0 model.eval() with torch.no_grad() : for batch in iterator: text, text_lengths = batch.text predictions = model(text, text_lengths ).squeeze(1) loss = criterion(predictions, batch.label) acc = binary_accuracy(predictions, batch.label) epoch_loss +...
Natural Language Processing with Disaster Tweets
10,157,262
from sklearn.model_selection import StratifiedKFold, KFold, GridSearchCV from sklearn.svm import SVC<train_model>
t = time.time() best_valid_loss = float('inf') model.to(device) criterion = nn.BCEWithLogitsLoss() optimizer = torch.optim.Adam(model.parameters() , lr=learning_rate) for epoch in range(num_epochs): train_loss, train_acc = train(model, train_iterator, optimizer, criterion) valid_loss, valid_acc = evaluate(model, va...
Natural Language Processing with Disaster Tweets
10,157,262
%%time svc_model = SVC(gamma='scale', kernel='rbf', C=3) svc_model.fit(train_embed, train_labels )<import_modules>
nlp = spacy.load('en') def predict(model, sentence): tokenized = [tok.text for tok in nlp.tokenizer(sentence)] indexed = [TEXT.vocab.stoi[t] for t in tokenized] length = [len(indexed)] tensor = torch.LongTensor(indexed ).to(device) tensor = tensor.unsqueeze(1 ).T length_tensor = torch.LongTensor(length) prediction =...
Natural Language Processing with Disaster Tweets
10,157,262
import xgboost as xgb<train_model>
PATH = ".. /working/best_model.pt" model.load_state_dict(torch.load(PATH)) predicts = [] for i in range(len(test_data.text)) : predict_class = predict(model, test_data.text[i]) predicts.append(int(predict_class))
Natural Language Processing with Disaster Tweets
10,157,262
%%time clf = xgb.XGBClassifier(max_depth=200, n_estimators=400, subsample=1, learning_rate=0.07, reg_lambda=0.1, reg_alpha=0.1,\ gamma=1) clf.fit(train_embed, train_labels) predictions = clf.predict(train_embed) print("Training set f1_score :", np.round(f1_score(train_labels, predictions),5))<predict_on_test>
submission = pd.read_csv(".. /input/nlp-getting-started/sample_submission.csv") submission['target'] = predicts submission
Natural Language Processing with Disaster Tweets
10,157,262
test_pred1 = clf.predict(test_embed ).round().astype(int) test_pred2 = svc_model.predict(test_embed ).round().astype(int) test_pred3 = sBERT.predict(test_input ).round().astype(int) print("XGBOOST: ", accuracy_score(test_labels, test_pred1), f1_score(test_labels, test_pred1)) print("SVC: ",accuracy_score(test_labels...
submission.to_csv('submission.csv',index=False )
Natural Language Processing with Disaster Tweets
10,157,262
sub = pd.read_csv("/kaggle/input/nlp-getting-started/sample_submission.csv") sub['target'] = test_pred1 sub.to_csv('submission_xgboost.csv', index=False) sub['target'] = test_pred2 sub.to_csv('submission_svc.csv', index=False) sub['target'] = test_pred3 sub.to_csv('submission_bertnn.csv', index=False )<import_module...
gt_df = pd.read_csv(".. /input/disasters-on-social-media/socialmedia-disaster-tweets-DFE.csv", encoding='latin_1') gt_df = gt_df[['choose_one', 'text']] gt_df['target'] =(gt_df['choose_one']=='Relevant' ).astype(int) gt_df['id'] = gt_df.index merged_df = pd.merge(test_data, gt_df, on='id') merged_df
Natural Language Processing with Disaster Tweets
10,157,262
import nltk from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from sklearn.metrics import confusion_matrix from sklearn.model_selection import GridSearchCV from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.base import Base...
target_df = merged_df[['id', 'target']] target_df
Natural Language Processing with Disaster Tweets
10,157,262
rand_state = random.seed(12 )<load_from_csv>
target_df.to_csv('perfect_submission.csv', index=False )
Natural Language Processing with Disaster Tweets
10,157,262
<prepare_x_and_y><EOS>
target_df["predict"] = list(submission.target) print('\t\tCLASSIFICATIION METRICS ') print(metrics.classification_report(target_df.target, target_df.predict))
Natural Language Processing with Disaster Tweets
10,038,839
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<prepare_x_and_y>
plt.style.use('ggplot') warnings.filterwarnings('ignore')
Natural Language Processing with Disaster Tweets
10,038,839
y = train['target']<prepare_x_and_y>
def seed_everything(seed): os.environ['PYTHONHASHSEED']=str(seed) tf.random.set_seed(seed) np.random.seed(seed) random.seed(seed) seed_everything(34 )
Natural Language Processing with Disaster Tweets
10,038,839
test_x = test['text']<split>
train = pd.read_csv('.. /input/nlp-getting-started/train.csv') test = pd.read_csv('.. /input/nlp-getting-started/test.csv') train.head()
Natural Language Processing with Disaster Tweets
10,038,839
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = rand_state, shuffle = True )<feature_engineering>
test_id = test['id'] columns = {'id', 'location'} train = train.drop(columns = columns) test = test.drop(columns = columns) train['keyword'] = train['keyword'].fillna('unknown') test['keyword'] = test['keyword'].fillna('unknown') train['text'] = train['text'] + ' ' + train['keyword'] test['text'] = test['text'] + '...
Natural Language Processing with Disaster Tweets
10,038,839
count_vectorizer = CountVectorizer(stop_words='english') count_train = count_vectorizer.fit_transform(X_train) count_test = count_vectorizer.transform(X_test) count_train_sub = count_vectorizer.transform(X) count_sub = count_vectorizer.transform(test_x) <compute_train_metric>
total['unique word count'] = total['text'].apply(lambda x: len(set(x.split()))) total['stopword count'] = total['text'].apply(lambda x: len([i for i in x.lower().split() if i in wordcloud.STOPWORDS])) total['stopword ratio'] = total['stopword count'] / total['word count'] total['punctuation count'] = total['text'].app...
Natural Language Processing with Disaster Tweets
10,038,839
count_nb = MultinomialNB() count_nb.fit(count_train ,y_train) count_nb_pred = count_nb.predict(count_test) count_nb_score = accuracy_score(y_test,count_nb_pred) print('MultinomialNaiveBayes Count Score: ', count_nb_score) count_nb_cm = confusion_matrix(y_test, count_nb_pred) count_nb_cm<compute_train_metric>
def remove_punctuation(x): return x.translate(str.maketrans('', '', string.punctuation)) def remove_stopwords(x): return ' '.join([i for i in x.split() if i not in wordcloud.STOPWORDS]) def remove_less_than(x): return ' '.join([i for i in x.split() if len(i)> 3]) def remove_non_alphabet(x): return ' '.join([i for i i...
Natural Language Processing with Disaster Tweets
10,038,839
count_bnb = BernoulliNB() count_bnb.fit(count_train ,y_train) count_bnb_pred = count_bnb.predict(count_test) count_bnb_score = accuracy_score(y_test,count_bnb_pred) print('BernoulliNaiveBayes Count Score: ', count_bnb_score) count_bnb_cm = confusion_matrix(y_test, count_bnb_pred) count_bnb_cm<compute_train_metric>
strip_all_entities('@shawn Titanic Times: Telegraph.co.ukTitanic tragedy could have been preve...http://bet.ly/tuN2wx' )
Natural Language Processing with Disaster Tweets
10,038,839
count_lsvc = LinearSVC() count_lsvc.fit(count_train ,y_train) count_lsvc_pred = count_lsvc.predict(count_test) count_lsvc_score = accuracy_score(y_test,count_lsvc_pred) print('LinearSVC Count Score: ', count_lsvc_score) count_lsvc_cm = confusion_matrix(y_test, count_lsvc_pred) count_lsvc_cm<compute_train_metric>
!pip install autocorrect def spell_check(x): spell = Speller(lang='en') return " ".join([spell(i)for i in x.split() ]) mispelled = 'Pleaze spelcheck this sentince' spell_check(mispelled )
Natural Language Processing with Disaster Tweets
10,038,839
count_svc = SVC() count_svc.fit(count_train ,y_train) count_svc_pred = count_svc.predict(count_test) count_svc_score = accuracy_score(y_test,count_svc_pred) print('SVC Count Score: ', count_svc_score) count_svc_cm = confusion_matrix(y_test, count_svc_pred) count_svc_cm<compute_train_metric>
PROCESS_TWEETS = False if PROCESS_TWEETS: total['text'] = total['text'].apply(lambda x: x.lower()) total['text'] = total['text'].apply(lambda x: re.sub(r'https?://\S+|www\.\S+', '', x, flags = re.MULTILINE)) total['text'] = total['text'].apply(remove_punctuation) total['text'] = total['text'].apply(remove_stopwords) ...
Natural Language Processing with Disaster Tweets
10,038,839
count_nusvc = NuSVC(0.4) count_nusvc.fit(count_train ,y_train) count_nusvc_pred = count_nusvc.predict(count_test) count_nusvc_score = accuracy_score(y_test,count_nusvc_pred) print('NuSVC Count Score: ', count_nusvc_score) count_nusvc_cm = confusion_matrix(y_test, count_nusvc_pred) count_nusvc_cm<train_on_grid>
contractions = { "ain't": "am not / are not / is not / has not / have not", "aren't": "are not / am not", "can't": "cannot", "can't've": "cannot have", "'cause": "because", "could've": "could have", "couldn't": "could not", "couldn't've": "could not have", "didn't": "did not", "doesn't": "does not", "don't": "do not", ...
Natural Language Processing with Disaster Tweets
10,038,839
<compute_test_metric>
total['text'] = total['text'].apply(expand_contractions )
Natural Language Processing with Disaster Tweets
10,038,839
<compute_train_metric>
def clean(tweet): tweet = re.sub(r"tnwx", "Tennessee Weather", tweet) tweet = re.sub(r"azwx", "Arizona Weather", tweet) tweet = re.sub(r"alwx", "Alabama Weather", tweet) tweet = re.sub(r"wordpressdotcom", "wordpress", tweet) tweet = re.sub(r"gawx", "Georgia Weather", tweet) tweet = re.sub(r"scwx", "South Carolina ...
Natural Language Processing with Disaster Tweets
10,038,839
count_sgd = SGDClassifier() count_sgd.fit(count_train ,y_train) count_sgd_pred = count_sgd.predict(count_test) count_sgd_score = accuracy_score(y_test,count_sgd_pred) print('SGD Count Score: ', count_sgd_score) count_sgd_cm = confusion_matrix(y_test, count_sgd_pred) count_sgd_cm<compute_train_metric>
tweets = [tweet for tweet in total['text']] train = total[:len(train)] test = total[len(train):]
Natural Language Processing with Disaster Tweets
10,038,839
count_lr = LogisticRegression() count_lr.fit(count_train ,y_train) count_lr_pred = count_lr.predict(count_test) count_lr_score = accuracy_score(y_test,count_lr_pred) print('LogisticRegression Count Score: ', count_lr_score) count_lr_cm = confusion_matrix(y_test, count_lr_pred) count_lr_cm<feature_engineering>
def generate_ngrams(text, n_gram=1): token = [token for token in text.lower().split(' ')if token != '' if token not in wordcloud.STOPWORDS] ngrams = zip(*[token[i:] for i in range(n_gram)]) return [' '.join(ngram)for ngram in ngrams] disaster_unigrams = defaultdict(int) for word in total[train['target'] == 1]['text']...
Natural Language Processing with Disaster Tweets
10,038,839
tfidf_vectorizer = TfidfVectorizer(stop_words='english') tfidf_train = tfidf_vectorizer.fit_transform(X_train) tfidf_test = tfidf_vectorizer.transform(X_test) tfidf_train_sub = tfidf_vectorizer.transform(X) tfidf_sub = tfidf_vectorizer.transform(test_x )<compute_train_metric>
to_exclude = '*+-/() % [\\]{|}^_`~\t' to_tokenize = '!" tokenizer = Tokenizer(filters = to_exclude) text = 'Why are you so f% text = re.sub(r'(['+to_tokenize+'])', r' \1 ', text) tokenizer.fit_on_texts([text]) print(tokenizer.word_index )
Natural Language Processing with Disaster Tweets
10,038,839
tfidf_nb = MultinomialNB() tfidf_nb.fit(tfidf_train, y_train) tfidf_nb_pred = tfidf_nb.predict(tfidf_test) tfidf_nb_score = accuracy_score(y_test,tfidf_nb_pred) print('MultinomialNaiveBayes Tfidf Score: ', tfidf_nb_score) tfidf_nb_cm = confusion_matrix(y_test, tfidf_nb_pred) tfidf_nb_cm<compute_train_metric>
Natural Language Processing with Disaster Tweets
10,038,839
tfidf_svc = LinearSVC() tfidf_svc.fit(tfidf_train, y_train) tfidf_svc_pred = tfidf_svc.predict(tfidf_test) tfidf_svc_score = accuracy_score(y_test,tfidf_svc_pred) print("LinearSVC Score: %0.3f" % tfidf_svc_score) svc_cm = confusion_matrix(y_test, tfidf_svc_pred) svc_cm<compute_train_metric>
tokenizer = Tokenizer() tokenizer.fit_on_texts(tweets) sequences = tokenizer.texts_to_sequences(tweets) word_index = tokenizer.word_index print('Found %s unique tokens.' % len(word_index)) data = pad_sequences(sequences) labels = train['target'] print('Shape of data tensor:', data.shape) print('Shape of label tenso...
Natural Language Processing with Disaster Tweets
10,038,839
tfidf_svc0 = SVC() tfidf_svc0.fit(tfidf_train, y_train) tfidf_svc_pred0 = tfidf_svc.predict(tfidf_test) tfidf_svc_score0 = accuracy_score(y_test,tfidf_svc_pred0) print("SVC Score: %0.3f" % tfidf_svc_score0) svc_cm0 = confusion_matrix(y_test, tfidf_svc_pred0) classification_report(y_test, tfidf_svc_pred0) svc_cm0<...
embeddings_index = {} with open('.. /input/glove-global-vectors-for-word-representation/glove.6B.200d.txt','r')as f: for line in tqdm(f): values = line.split() word = values[0] coefs = np.asarray(values[1:], dtype='float32') embeddings_index[word] = coefs f.close() print('Found %s word vectors in the GloVe library' % ...
Natural Language Processing with Disaster Tweets
10,038,839
tfidf_nusvc = NuSVC() tfidf_nusvc.fit(tfidf_train, y_train) tfidf_nusvc_pred = tfidf_nusvc.predict(tfidf_test) tfidf_nusvc_score = accuracy_score(y_test,tfidf_nusvc_pred) print("NuSVC Score: %0.3f" % tfidf_nusvc_score) nusvc_cm = confusion_matrix(y_test, tfidf_nusvc_pred) classification_report(y_test, tfidf_nusvc_...
EMBEDDING_DIM = 200
Natural Language Processing with Disaster Tweets
10,038,839
tfidf_bnb = BernoulliNB() tfidf_bnb.fit(tfidf_train, y_train) tfidf_bnb_pred = tfidf_bnb.predict(tfidf_test) tfidf_bnb_score = accuracy_score(y_test,tfidf_bnb_pred) print('BernoulliNaiveBayes Tfidf Score: %0.3f' % tfidf_bnb_score) tfidf_bnb_cm = confusion_matrix(y_test, tfidf_bnb_pred) tfidf_bnb_cm<compute_train_m...
embedding_matrix = np.zeros(( len(word_index)+ 1, EMBEDDING_DIM)) for word, i in tqdm(word_index.items()): embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector print("Our embedded matrix is of dimension", embedding_matrix.shape )
Natural Language Processing with Disaster Tweets
10,038,839
tfidf_sgd = SGDClassifier() tfidf_sgd.fit(tfidf_train, y_train) tfidf_sgd_pred = tfidf_sgd.predict(tfidf_test) tfidf_sgd_score = accuracy_score(y_test,tfidf_sgd_pred) print("SGD Score: %0.3f" % tfidf_sgd_score) sgd_cm = confusion_matrix(y_test, tfidf_sgd_pred) sgd_cm<compute_train_metric>
embedding = Embedding(len(word_index)+ 1, EMBEDDING_DIM, weights = [embedding_matrix], input_length = MAX_SEQUENCE_LENGTH, trainable = False)
Natural Language Processing with Disaster Tweets
10,038,839
tfidf_lr = LogisticRegression() tfidf_lr.fit(tfidf_train, y_train) tfidf_lr_pred = tfidf_lr.predict(tfidf_test) tfidf_lr_score = accuracy_score(y_test,tfidf_lr_pred) print("LogisticRegression Score: %0.3f" % tfidf_lr_score) lr_cm = confusion_matrix(y_test, tfidf_lr_pred) lr_cm<load_from_csv>
def scale(df, scaler): return scaler.fit_transform(df.iloc[:, 2:]) meta_train = scale(train, StandardScaler()) meta_test = scale(test, StandardScaler() )
Natural Language Processing with Disaster Tweets
10,038,839
sample_sub=pd.read_csv('/kaggle/input/nlp-getting-started/sample_submission.csv') <predict_on_test>
def create_lstm(spatial_dropout, dropout, recurrent_dropout, learning_rate, bidirectional = False): activation = LeakyReLU(alpha = 0.01) nlp_input = Input(shape =(MAX_SEQUENCE_LENGTH,), name = 'nlp_input') meta_input_train = Input(shape =(7,), name = 'meta_train') emb = embedding(nlp_input) emb = SpatialDropout1D(d...
Natural Language Processing with Disaster Tweets
10,038,839
count_nusvc.fit(count_train_sub ,y) count_nusvc_sub = count_nusvc.predict(count_sub) <create_dataframe>
lstm = create_lstm(spatial_dropout =.2, dropout =.2, recurrent_dropout =.2, learning_rate = 3e-4, bidirectional = True) lstm.summary()
Natural Language Processing with Disaster Tweets
10,038,839
sub=pd.DataFrame({'id':sample_sub['id'].values.tolist() ,'target':count_nusvc_sub} )<save_to_csv>
history1 = lstm.fit([nlp_train, meta_train], labels, validation_split =.2, epochs = 5, batch_size = 21, verbose = 1 )
Natural Language Processing with Disaster Tweets
10,038,839
sub.to_csv('submission.csv',index=False )<import_modules>
callback = EarlyStopping(monitor = 'val_loss', patience = 4)
Natural Language Processing with Disaster Tweets
10,038,839
import nltk from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer from sklearn.metrics import confusion_matrix from sklearn.model_selection import GridSearchCV from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import train_test_split from sklearn.base import Base...
def create_lstm_2(spatial_dropout, dropout, recurrent_dropout, learning_rate, bidirectional = False): activation = LeakyReLU(alpha = 0.01) nlp_input = Input(shape =(MAX_SEQUENCE_LENGTH,), name = 'nlp_input') meta_input_train = Input(shape =(7,), name = 'meta_train') emb = embedding(nlp_input) emb = SpatialDropout1D...
Natural Language Processing with Disaster Tweets
10,038,839
rand_state = random.seed(12 )<load_from_csv>
lstm_2 = create_lstm_2(spatial_dropout =.4, dropout =.4, recurrent_dropout =.4, learning_rate = 3e-4, bidirectional = True) lstm_2.summary()
Natural Language Processing with Disaster Tweets
10,038,839
train = pd.read_csv('/kaggle/input/nlp-getting-started/train.csv') test = pd.read_csv('/kaggle/input/nlp-getting-started/test.csv' )<prepare_x_and_y>
history2 = lstm_2.fit([nlp_train, meta_train], labels, validation_split =.2, epochs = 30, batch_size = 21, verbose = 1 )
Natural Language Processing with Disaster Tweets
10,038,839
X = train['text']<prepare_x_and_y>
submission_lstm = pd.DataFrame() submission_lstm['id'] = test_id submission_lstm['prob'] = lstm_2.predict([nlp_test, meta_test]) submission_lstm['target'] = submission_lstm['prob'].apply(lambda x: 0 if x <.5 else 1) submission_lstm.head(10 )
Natural Language Processing with Disaster Tweets
10,038,839
y = train['target']<prepare_x_and_y>
def create_dual_lstm(spatial_dropout, dropout, recurrent_dropout, learning_rate, bidirectional = False): activation = LeakyReLU(alpha = 0.01) nlp_input = Input(shape =(MAX_SEQUENCE_LENGTH,), name = 'nlp_input') meta_input_train = Input(shape =(7,), name = 'meta_train') emb = embedding(nlp_input) emb = SpatialDropou...
Natural Language Processing with Disaster Tweets
10,038,839
test_x = test['text']<split>
history3 = dual_lstm.fit([nlp_train, meta_train], labels, validation_split =.2, epochs = 25, batch_size = 21, verbose = 1 )
Natural Language Processing with Disaster Tweets
10,038,839
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = rand_state, shuffle = True )<feature_engineering>
submission_lstm2 = pd.DataFrame() submission_lstm2['id'] = test_id submission_lstm2['prob'] = dual_lstm.predict([nlp_test, meta_test]) submission_lstm2['target'] = submission_lstm2['prob'].apply(lambda x: 0 if x <.5 else 1) submission_lstm2.head(10 )
Natural Language Processing with Disaster Tweets
10,038,839
count_vectorizer = CountVectorizer(stop_words='english') count_train = count_vectorizer.fit_transform(X_train) count_test = count_vectorizer.transform(X_test) count_train_sub = count_vectorizer.transform(X) count_sub = count_vectorizer.transform(test_x) <compute_train_metric>
BATCH_SIZE = 32 EPOCHS = 2 USE_META = True ADD_DENSE = False DENSE_DIM = 64 ADD_DROPOUT = False DROPOUT =.2
Natural Language Processing with Disaster Tweets
10,038,839
count_nb = MultinomialNB() count_nb.fit(count_train ,y_train) count_nb_pred = count_nb.predict(count_test) count_nb_score = accuracy_score(y_test,count_nb_pred) print('MultinomialNaiveBayes Count Score: ', count_nb_score) count_nb_cm = confusion_matrix(y_test, count_nb_pred) count_nb_cm<compute_train_metric>
!pip install --quiet transformers
Natural Language Processing with Disaster Tweets
10,038,839
count_bnb = BernoulliNB() count_bnb.fit(count_train ,y_train) count_bnb_pred = count_bnb.predict(count_test) count_bnb_score = accuracy_score(y_test,count_bnb_pred) print('BernoulliNaiveBayes Count Score: ', count_bnb_score) count_bnb_cm = confusion_matrix(y_test, count_bnb_pred) count_bnb_cm<compute_train_metric>
TOKENIZER = AutoTokenizer.from_pretrained("bert-large-uncased") enc = TOKENIZER.encode("Encode me!") dec = TOKENIZER.decode(enc) print("Encode: " + str(enc)) print("Decode: " + str(dec))
Natural Language Processing with Disaster Tweets
10,038,839
count_lsvc = LinearSVC() count_lsvc.fit(count_train ,y_train) count_lsvc_pred = count_lsvc.predict(count_test) count_lsvc_score = accuracy_score(y_test,count_lsvc_pred) print('LinearSVC Count Score: ', count_lsvc_score) count_lsvc_cm = confusion_matrix(y_test, count_lsvc_pred) count_lsvc_cm<compute_train_metric>
def bert_encode(data,maximum_len): input_ids = [] attention_masks = [] for i in range(len(data.text)) : encoded = TOKENIZER.encode_plus(data.text[i], add_special_tokens=True, max_length=maximum_len, pad_to_max_length=True, return_attention_mask=True) input_ids.append(encoded['input_ids']) attention_masks.append(encod...
Natural Language Processing with Disaster Tweets
10,038,839
count_svc = SVC() count_svc.fit(count_train ,y_train) count_svc_pred = count_svc.predict(count_test) count_svc_score = accuracy_score(y_test,count_svc_pred) print('SVC Count Score: ', count_svc_score) count_svc_cm = confusion_matrix(y_test, count_svc_pred) count_svc_cm<compute_train_metric>
def build_model(model_layer, learning_rate, use_meta = USE_META, add_dense = ADD_DENSE, dense_dim = DENSE_DIM, add_dropout = ADD_DROPOUT, dropout = DROPOUT): input_ids = tf.keras.Input(shape=(60,),dtype='int32') attention_masks = tf.keras.Input(shape=(60,),dtype='int32') meta_input = tf.keras.Input(shape =(meta_train...
Natural Language Processing with Disaster Tweets
10,038,839
count_nusvc = NuSVC(0.4) count_nusvc.fit(count_train ,y_train) count_nusvc_pred = count_nusvc.predict(count_test) count_nusvc_score = accuracy_score(y_test,count_nusvc_pred) print('NuSVC Count Score: ', count_nusvc_score) count_nusvc_cm = confusion_matrix(y_test, count_nusvc_pred) count_nusvc_cm<train_on_grid>
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,038,839
<compute_test_metric>
bert_large = TFAutoModel.from_pretrained('bert-large-uncased') TOKENIZER = AutoTokenizer.from_pretrained("bert-large-uncased") train_input_ids,train_attention_masks = bert_encode(train,60) test_input_ids,test_attention_masks = bert_encode(test,60) print('Train length:', len(train_input_ids)) print('Test length:', l...
Natural Language Processing with Disaster Tweets
10,038,839
<compute_train_metric>
history_bert = BERT_large.fit([train_input_ids,train_attention_masks, meta_train], train.target, validation_split =.2, epochs = EPOCHS, callbacks = [checkpoint], batch_size = BATCH_SIZE )
Natural Language Processing with Disaster Tweets
10,038,839
count_sgd = SGDClassifier() count_sgd.fit(count_train ,y_train) count_sgd_pred = count_sgd.predict(count_test) count_sgd_score = accuracy_score(y_test,count_sgd_pred) print('SGD Count Score: ', count_sgd_score) count_sgd_cm = confusion_matrix(y_test, count_sgd_pred) count_sgd_cm<compute_train_metric>
BERT_large.load_weights('large_model.h5') preds_bert = BERT_large.predict([test_input_ids,test_attention_masks,meta_test] )
Natural Language Processing with Disaster Tweets
10,038,839
count_lr = LogisticRegression() count_lr.fit(count_train ,y_train) count_lr_pred = count_lr.predict(count_test) count_lr_score = accuracy_score(y_test,count_lr_pred) print('LogisticRegression Count Score: ', count_lr_score) count_lr_cm = confusion_matrix(y_test, count_lr_pred) count_lr_cm<feature_engineering>
submission_bert = pd.DataFrame() submission_bert['id'] = test_id submission_bert['prob'] = preds_bert submission_bert['target'] = np.round(submission_bert['prob'] ).astype(int) submission_bert.head(10 )
Natural Language Processing with Disaster Tweets
10,038,839
tfidf_vectorizer = TfidfVectorizer(stop_words='english') tfidf_train = tfidf_vectorizer.fit_transform(X_train) tfidf_test = tfidf_vectorizer.transform(X_test) tfidf_train_sub = tfidf_vectorizer.transform(X) tfidf_sub = tfidf_vectorizer.transform(test_x )<compute_train_metric>
submission_bert = submission_bert[['id', 'target']] submission_bert.to_csv('submission_bert.csv', index = False) print('Blended submission has been saved to disk' )
Natural Language Processing with Disaster Tweets
10,038,839
tfidf_nb = MultinomialNB() tfidf_nb.fit(tfidf_train, y_train) tfidf_nb_pred = tfidf_nb.predict(tfidf_test) tfidf_nb_score = accuracy_score(y_test,tfidf_nb_pred) print('MultinomialNaiveBayes Tfidf Score: ', tfidf_nb_score) tfidf_nb_cm = confusion_matrix(y_test, tfidf_nb_pred) tfidf_nb_cm<compute_train_metric>
plt.style.use('ggplot') warnings.filterwarnings('ignore')
Natural Language Processing with Disaster Tweets
10,038,839
tfidf_svc = LinearSVC() tfidf_svc.fit(tfidf_train, y_train) tfidf_svc_pred = tfidf_svc.predict(tfidf_test) tfidf_svc_score = accuracy_score(y_test,tfidf_svc_pred) print("LinearSVC Score: %0.3f" % tfidf_svc_score) svc_cm = confusion_matrix(y_test, tfidf_svc_pred) svc_cm<compute_train_metric>
def seed_everything(seed): os.environ['PYTHONHASHSEED']=str(seed) tf.random.set_seed(seed) np.random.seed(seed) random.seed(seed) seed_everything(34 )
Natural Language Processing with Disaster Tweets
10,038,839
tfidf_svc0 = SVC() tfidf_svc0.fit(tfidf_train, y_train) tfidf_svc_pred0 = tfidf_svc.predict(tfidf_test) tfidf_svc_score0 = accuracy_score(y_test,tfidf_svc_pred0) print("SVC Score: %0.3f" % tfidf_svc_score0) svc_cm0 = confusion_matrix(y_test, tfidf_svc_pred0) classification_report(y_test, tfidf_svc_pred0) svc_cm0<...
train = pd.read_csv('.. /input/nlp-getting-started/train.csv') test = pd.read_csv('.. /input/nlp-getting-started/test.csv') train.head()
Natural Language Processing with Disaster Tweets
10,038,839
tfidf_nusvc = NuSVC() tfidf_nusvc.fit(tfidf_train, y_train) tfidf_nusvc_pred = tfidf_nusvc.predict(tfidf_test) tfidf_nusvc_score = accuracy_score(y_test,tfidf_nusvc_pred) print("NuSVC Score: %0.3f" % tfidf_nusvc_score) nusvc_cm = confusion_matrix(y_test, tfidf_nusvc_pred) classification_report(y_test, tfidf_nusvc_...
test_id = test['id'] columns = {'id', 'location'} train = train.drop(columns = columns) test = test.drop(columns = columns) train['keyword'] = train['keyword'].fillna('unknown') test['keyword'] = test['keyword'].fillna('unknown') train['text'] = train['text'] + ' ' + train['keyword'] test['text'] = test['text'] + '...
Natural Language Processing with Disaster Tweets
10,038,839
tfidf_bnb = BernoulliNB() tfidf_bnb.fit(tfidf_train, y_train) tfidf_bnb_pred = tfidf_bnb.predict(tfidf_test) tfidf_bnb_score = accuracy_score(y_test,tfidf_bnb_pred) print('BernoulliNaiveBayes Tfidf Score: %0.3f' % tfidf_bnb_score) tfidf_bnb_cm = confusion_matrix(y_test, tfidf_bnb_pred) tfidf_bnb_cm<compute_train_m...
total['unique word count'] = total['text'].apply(lambda x: len(set(x.split()))) total['stopword count'] = total['text'].apply(lambda x: len([i for i in x.lower().split() if i in wordcloud.STOPWORDS])) total['stopword ratio'] = total['stopword count'] / total['word count'] total['punctuation count'] = total['text'].app...
Natural Language Processing with Disaster Tweets
10,038,839
tfidf_sgd = SGDClassifier() tfidf_sgd.fit(tfidf_train, y_train) tfidf_sgd_pred = tfidf_sgd.predict(tfidf_test) tfidf_sgd_score = accuracy_score(y_test,tfidf_sgd_pred) print("SGD Score: %0.3f" % tfidf_sgd_score) sgd_cm = confusion_matrix(y_test, tfidf_sgd_pred) sgd_cm<compute_train_metric>
def remove_punctuation(x): return x.translate(str.maketrans('', '', string.punctuation)) def remove_stopwords(x): return ' '.join([i for i in x.split() if i not in wordcloud.STOPWORDS]) def remove_less_than(x): return ' '.join([i for i in x.split() if len(i)> 3]) def remove_non_alphabet(x): return ' '.join([i for i i...
Natural Language Processing with Disaster Tweets
10,038,839
tfidf_lr = LogisticRegression() tfidf_lr.fit(tfidf_train, y_train) tfidf_lr_pred = tfidf_lr.predict(tfidf_test) tfidf_lr_score = accuracy_score(y_test,tfidf_lr_pred) print("LogisticRegression Score: %0.3f" % tfidf_lr_score) lr_cm = confusion_matrix(y_test, tfidf_lr_pred) lr_cm<load_from_csv>
strip_all_entities('@shawn Titanic Times: Telegraph.co.ukTitanic tragedy could have been preve...http://bet.ly/tuN2wx' )
Natural Language Processing with Disaster Tweets
10,038,839
sample_sub=pd.read_csv('/kaggle/input/nlp-getting-started/sample_submission.csv') <predict_on_test>
!pip install autocorrect def spell_check(x): spell = Speller(lang='en') return " ".join([spell(i)for i in x.split() ]) mispelled = 'Pleaze spelcheck this sentince' spell_check(mispelled )
Natural Language Processing with Disaster Tweets