kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
11,309,718
X = dataset.iloc[:,1:].values y = dataset.iloc[:,0].values <import_modules>
try: trials = load_trials(trials_file_name, True) print('Found trials file') except FileNotFoundError as e: trials = ho.Trials() print('Not found trials file') len(trials.trials )
Natural Language Processing with Disaster Tweets
11,309,718
from sklearn.model_selection import train_test_split<import_modules>
MAX_LENGTH = 200 BATCH_SIZE = 16 EPOCHS = 5
Natural Language Processing with Disaster Tweets
11,309,718
from sklearn.model_selection import train_test_split<split>
def encode_with_tokinizer(data, tokenizer, maximum_length): input_ids = [] attention_mask = [] for i in range(len(data)) : encoded = tokenizer.encode_plus( data[i], add_special_tokens=True, max_length=maximum_length, pad_to_max_length=True, return_attention_mask=True, return_token_type_ids=False ) input_ids.append(e...
Natural Language Processing with Disaster Tweets
11,309,718
X_train, X_val, y_train, y_val = train_test_split(X, y,test_size=0.20,random_state=42 )<train_model>
def node_params(n_layers): params = {} params['pack_size'] = n_layers for n in range(n_layers): params['n_nodes_layer_{}'.format(n)] = ho.hp.quniform('n_nodes_{}_{}'.format(n_layers, n), 10, 2000, 25) params['dropout_layer_{}'.format(n)] = ho.hp.quniform('dropout_{}_{}'.format(n_layers, n), 0, 0.6, 0.05) return param...
Natural Language Processing with Disaster Tweets
11,309,718
print("train samples:",X_train.shape[0]) print("validation samples:",X_val.shape[0] )<data_type_conversions>
def create_model(transformer_model, hparams): input_ids = tf.keras.Input(shape=(MAX_LENGTH,),dtype='int32') attention_mask = tf.keras.Input(shape=(MAX_LENGTH,), dtype='int32') transformer = transformer_model([input_ids, attention_mask]) hidden_states = transformer[1] if hparams['hidden_states_size'] == 1: output = h...
Natural Language Processing with Disaster Tweets
11,309,718
X_train = X_train.astype('float32') X_val = X_val.astype('float32') X_train /= 255 X_val /= 255<train_model>
tokenizers = { 'bert': trfo.BertTokenizer.from_pretrained('bert-large-uncased', do_lower_case=True), 'roberta': trfo.RobertaTokenizer.from_pretrained('roberta-large', do_lower_case=True), 'distilbert': trfo.DistilBertTokenizer.from_pretrained('distilbert-base-uncased', do_lower_case=True) }
Natural Language Processing with Disaster Tweets
11,309,718
img_shape = 28 X_train = np.reshape(X_train,(X_train.shape[0], img_shape, img_shape, 1)) X_val = np.reshape(X_val,(X_val.shape[0], img_shape, img_shape, 1)) input_shape =(img_shape, img_shape, 1 )<import_modules>
models = { 'bert': lambda : trfo.TFBertForSequenceClassification.from_pretrained('bert-large-uncased', output_hidden_states=True), 'roberta': lambda : trfo.TFRobertaForSequenceClassification.from_pretrained('roberta-large', output_hidden_states=True), 'distilbert': lambda : trfo.TFDistilBertForSequenceClassification.fr...
Natural Language Processing with Disaster Tweets
11,309,718
from tensorflow import keras import tensorflow from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten,BatchNormalization from keras.layers import Conv2D, MaxPooling2D,GlobalAveragePooling2D<define_variables>
kf = ms.KFold(n_splits=4, shuffle=False )
Natural Language Processing with Disaster Tweets
11,309,718
batch_size = 256 num_classes = 10 epochs = 50 <categorify>
def cross_validate_transformer_hparams(df, kf, hparams): errors = np.zeros(0) input_ids, attention_mask = encode_with_tokinizer(df.text, tokenizers[hparams['model_name']], MAX_LENGTH) for train_index, val_index in kf.split(df): init_tpu(tpu) model = create_model(models[hparams['model_name']]() , hparams) model.fit(...
Natural Language Processing with Disaster Tweets
11,309,718
y_train = keras.utils.to_categorical(y_train,num_classes) y_val = keras.utils.to_categorical(y_val,num_classes) <choose_model_class>
max_evals = 100
Natural Language Processing with Disaster Tweets
11,309,718
model = Sequential() model.add(Conv2D(64, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Dropout(0.25)) model.add(Conv2D(64,(3, 3), activation='relu')) model.add(Dropout(0.25)) model.add(Conv2D(64,(3, 3), activation='relu')) model.add(MaxPooling2D(( 2,2))) model.add(Dropout(0.25)) model.add...
space = { 'layers': ho.hp.choice('layers', [node_params(n)for n in [n for n in range(4)]]), 'lr_rate': ho.hp.loguniform("lr_rate", np.log(0.00001), np.log(0.001)) , 'model_name': ho.hp.choice('model_name', ['bert', 'roberta', 'distilbert']), 'hidden_states_size': ho.hp.choice('hidden_states_size', [n for n in range(1, ...
Natural Language Processing with Disaster Tweets
11,309,718
model.compile(loss=keras.losses.categorical_crossentropy, optimizer="rmsprop", metrics=['accuracy'] )<choose_model_class>
max_evals = 200
Natural Language Processing with Disaster Tweets
11,309,718
callback = keras.callbacks.EarlyStopping(monitor='val_loss', patience=7 )<train_model>
trials.trials
Natural Language Processing with Disaster Tweets
11,309,718
history = model.fit(X_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, callbacks=[callback], validation_data=(X_val, y_val)) <compute_test_metric>
EPOCHS = 3
Natural Language Processing with Disaster Tweets
11,309,718
loss,accuracy = model.evaluate(X_val, y_val,batch_size=256, verbose=1) print("accuracy:",accuracy) print("loss:",loss) <train_model>
tr, hold, val = np.split(train_df, [int (.7*len(train_df)) , int (.9*len(train_df)) ]) tr.shape, hold.shape, val.shape
Natural Language Processing with Disaster Tweets
11,309,718
val_loss = history.history['val_loss'] val_acc = history.history['val_accuracy'] train_loss = history.history['loss'] train_acc = history.history['accuracy']<load_from_csv>
def create_final_bert_model(train, val): input_ids = tf.keras.Input(shape=(MAX_LENGTH,),dtype='int32') attention_mask = tf.keras.Input(shape=(MAX_LENGTH,), dtype='int32') transformer = models['bert']()([input_ids, attention_mask]) hidden_states = transformer[1] output = hidden_states[-1] output = tf.keras.layers.Den...
Natural Language Processing with Disaster Tweets
11,309,718
sample_sub = pd.read_csv("/kaggle/input/Kannada-MNIST/sample_submission.csv" )<load_from_csv>
def create_final_roberta_model(train, val): input_ids = tf.keras.Input(shape=(MAX_LENGTH,),dtype='int32') attention_mask = tf.keras.Input(shape=(MAX_LENGTH,), dtype='int32') transformer = models['roberta']()([input_ids, attention_mask]) hidden_states = transformer[1] hiddes_states_ind = list(range(-3, 0, 1)) output ...
Natural Language Processing with Disaster Tweets
11,309,718
test = pd.read_csv("/kaggle/input/Kannada-MNIST/test.csv") X_test = test.iloc[:,1:].values test_ID = test.iloc[:,0].values X_test = X_test.astype('float32') X_test /=255 X_test = np.reshape(X_test,(X_test.shape[0], img_shape, img_shape, 1))<predict_on_test>
def get_predicitons_with_ensemble(x, ensemble_of_classifiers, y=None): bert_pred = get_prediciton_with_tokenizer(x, ensemble_of_classifiers['bert'], tokenizers['bert']) roberta_pred = get_prediciton_with_tokenizer(x, ensemble_of_classifiers['roberta'], tokenizers['roberta']) if y is not None: print(f'bert accuracy: {...
Natural Language Processing with Disaster Tweets
11,309,718
predicts = model.predict(X_test,batch_size=256 )<create_dataframe>
def get_prediciton_with_tokenizer(x, classifier, tokenizer): pred_results = pd.DataFrame() input_ids, attention_mask = encode_with_tokinizer(x, tokenizer, MAX_LENGTH) y_pred = classifier.predict([input_ids, attention_mask])[:, 0].reshape(-1) return y_pred
Natural Language Processing with Disaster Tweets
11,309,718
predicts_d = pd.DataFrame(predicts )<define_variables>
with tpu_strategy.scope() : bert_model = create_final_bert_model(tr, hold) roberta_model = create_final_roberta_model(tr, hold )
Natural Language Processing with Disaster Tweets
11,309,718
number_pred =[] for i in range(predicts_d.shape[0]): probs = predicts_d.values[i] for index,number in enumerate(probs): max_ = probs.max() if probs[index] == max_: number_pred.append(index) <create_dataframe>
ensemble_of_classifiers = {'bert': bert_model, 'roberta': roberta_model}
Natural Language Processing with Disaster Tweets
11,309,718
sub_dict = {"id":test_ID,"label":number_pred} sub_dt = pd.DataFrame(sub_dict )<save_to_csv>
hold_ens_prediction = get_predicitons_with_ensemble(hold.text.values, ensemble_of_classifiers, hold.target.values )
Natural Language Processing with Disaster Tweets
11,309,718
sub_csv = sub_dt.to_csv('my-submission23.csv',index=False )<set_options>
X_stack_train = hold_ens_prediction y_stack_train = hold.target.values
Natural Language Processing with Disaster Tweets
11,309,718
<import_modules>
def cross_validate_xgb_hparams(hparams, x, y): estimator = xgboost.XGBClassifier(learning_rate=hparams['learning_rate'], max_depth=hparams['max_depth'], n_estimators=int(hparams['n_estimators'])) cv_results = ms.cross_validate(estimator, x, y, cv=5, scoring='accuracy', n_jobs=3) mean_acc = np.mean(cv_results['test_sco...
Natural Language Processing with Disaster Tweets
11,309,718
from fastai.vision import *<load_from_csv>
trials_xgb = ho.Trials()
Natural Language Processing with Disaster Tweets
11,309,718
path = Path('.. /input/Kannada-MNIST') train = pd.read_csv('.. /input/Kannada-MNIST/train.csv') test = pd.read_csv('.. /input/Kannada-MNIST/test.csv') train_other = pd.read_csv('.. /input/Kannada-MNIST/Dig-MNIST.csv' )<define_variables>
max_evals_xgb = 50
Natural Language Processing with Disaster Tweets
11,309,718
data,labels =(train.iloc[:,1:],train.iloc[:,0] )<define_variables>
learning_rate_xgb_arr = [0.1, 0.05, 0.0025, 0.01, 0.005, 0.0025, 0.001, 0.0005, 0.00025, 0.0001] max_depth_xgb_arr = [2, 3, 4, 5, 6]
Natural Language Processing with Disaster Tweets
11,309,718
data_other,labels_other =(train_other.iloc[:,1:],train_other.iloc[:,0] )<concatenate>
space_xgb = { 'learning_rate': ho.hp.choice('learning_rate', learning_rate_xgb_arr), 'max_depth': ho.hp.choice('max_depth', max_depth_xgb_arr), 'n_estimators': ho.hp.quniform('n_estimators', 50, 2000, 5), } ho.fmin(fn=partial(cross_validate_xgb_hparams, x=X_stack_train, y=y_stack_train), space=space_xgb, algo=ho.tpe.su...
Natural Language Processing with Disaster Tweets
11,309,718
data_train,labels_train =(pd.concat([data, data_other]),pd.concat([labels, labels_other]))<split>
max_evals_xgb = 100
Natural Language Processing with Disaster Tweets
11,309,718
data_train, data_valid, labels_train, labels_valid = train_test_split(data_train, labels_train, test_size=0.25, random_state=42,stratify=labels_train )<train_model>
best_xgb = ho.fmin(fn=partial(cross_validate_xgb_hparams, x=X_stack_train, y=y_stack_train), space=space_xgb, algo=ho.anneal.suggest, max_evals=max_evals_xgb, trials=trials_xgb )
Natural Language Processing with Disaster Tweets
11,309,718
def save_img_to_folder(path:Path,data,labels): path.mkdir(parents=True,exist_ok=True) for i in range(len(data)) : test = path temp_path = test/(str(labels[i])) if os.path.isdir(temp_path): imageio.imwrite(str(temp_path/(str(i)+'.jpg')) , data[i]) else: temp_path.mkdir(parents=True,exist_ok=True) imageio.imwrite(str(...
learning_rate_xgb = learning_rate_xgb_arr[best_xgb['learning_rate']] max_depth_xgb = max_depth_xgb_arr[best_xgb['max_depth']] n_estimators_xgb = int(best_xgb['n_estimators'] )
Natural Language Processing with Disaster Tweets
11,309,718
data_arr = np.array(data_valid ).reshape(-1,28,28) labels_arr = np.array(labels_valid )<save_to_csv>
learning_rate_xgb, max_depth_xgb, n_estimators_xgb
Natural Language Processing with Disaster Tweets
11,309,718
save_img_to_folder(Path('valid'),data_arr,labels_arr )<prepare_x_and_y>
metalearner = xgboost.XGBClassifier( learning_rate=learning_rate_xgb, max_depth=max_depth_xgb, n_estimators=n_estimators_xgb ) metalearner.fit(X_stack_train, y_stack_train )
Natural Language Processing with Disaster Tweets
11,309,718
data_arr1 = np.array(data_train ).reshape(-1,28,28) labels_arr1 = np.array(labels_train )<load_pretrained>
val_ens_predictions = get_predicitons_with_ensemble(val.text.values, ensemble_of_classifiers, val.target.values )
Natural Language Processing with Disaster Tweets
11,309,718
save_img_to_folder(Path('train'),data_arr1,labels_arr1 )<define_variables>
X_stack_val = val_ens_predictions val_meta_predictions = metalearner.predict(X_stack_val) X_stack_val.shape, val_meta_predictions.shape
Natural Language Processing with Disaster Tweets
11,309,718
path = Path('/kaggle/working') train_path = path/'train' valid_path = path/'valid' path.ls()<import_modules>
m.accuracy_score(val_meta_predictions, val.target.values )
Natural Language Processing with Disaster Tweets
11,309,718
from fastai.metrics import error_rate from fastai.vision import *<feature_engineering>
def get_test_predictions_using_metalearner(model, x, ids): prediction = model.predict(x) result = np.round(prediction ).astype(int) output = pd.DataFrame({'id':ids,'target': result}) return output
Natural Language Processing with Disaster Tweets
11,309,718
np.random.seed(42) tfms = get_transforms(do_flip=False )<split>
pred_df = pd.read_csv('.. /input/nlp-getting-started/test.csv') pred_df['text'] = pred_df['text'].apply(lambda x: x.lower()) pred_df['text'] = pred_df['text'].apply(lambda x: remove_url(x)) pred_df['text'] = pred_df['text'].apply(lambda x: remove_user(x)) pred_df['text'] = pred_df['text'].apply(lambda x: translate_wi...
Natural Language Processing with Disaster Tweets
11,309,718
src =(ImageList.from_folder(path) .split_by_folder(train='train', valid='valid') .label_from_folder() )<normalization>
pred_ens_predictions = get_predicitons_with_ensemble(pred_df.text.values, ensemble_of_classifiers )
Natural Language Processing with Disaster Tweets
11,309,718
<train_model><EOS>
get_test_predictions_using_metalearner(metalearner, pred_ens_predictions, pred_df.id ).to_csv('submission.csv', index=False )
Natural Language Processing with Disaster Tweets
7,371,124
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<define_variables>
warnings.filterwarnings("ignore") pd.options.display.max_colwidth = 170
Natural Language Processing with Disaster Tweets
7,371,124
data.show_batch(rows=4,figsize=(7,8))<choose_model_class>
train = pd.read_csv('/kaggle/input/nlp-getting-started/train.csv') test = pd.read_csv('/kaggle/input/nlp-getting-started/test.csv')
Natural Language Processing with Disaster Tweets
7,371,124
learner = cnn_learner(data,models.resnet152, metrics=[error_rate, accuracy] )<train_model>
train.target.value_counts()
Natural Language Processing with Disaster Tweets
7,371,124
learner.fit_one_cycle(12 )<save_model>
train = train.reindex(np.random.permutation(train.index))
Natural Language Processing with Disaster Tweets
7,371,124
learner.save('kannada-stage1' )<choose_model_class>
train_len = train.shape[0] test_len = test.shape[0] train_keyword_null_count = train[train.keyword.isnull() == True].shape[0] test_keyword_null_count = test[test.keyword.isnull() == True].shape[0] train_location_null_count = train[train.location.isnull() == True].shape[0] test_location_null_count = test[test.location.i...
Natural Language Processing with Disaster Tweets
7,371,124
interp = ClassificationInterpretation.from_learner(learner )<find_best_params>
train.location.isnull().value_counts()
Natural Language Processing with Disaster Tweets
7,371,124
losses,idx = interp.top_losses()<filter>
train.drop("location", axis = 1, inplace = True) test.drop("location", axis = 1, inplace = True )
Natural Language Processing with Disaster Tweets
7,371,124
len(data.valid_ds)==len(losses)==len(idx )<find_best_params>
train.keyword.fillna("", inplace = True) test.keyword.fillna("", inplace = True) train.text = train.text + " " + train.keyword test.text = test.text + " " + test.keyword
Natural Language Processing with Disaster Tweets
7,371,124
learner.lr_find()<train_model>
train.drop("keyword", axis = 1, inplace = True) test.drop("keyword", axis = 1, inplace = True )
Natural Language Processing with Disaster Tweets
7,371,124
learner.unfreeze() learner.fit_one_cycle(10, max_lr=slice(1e-6,1e-4))<save_model>
train_filter0 = train.target == 0 train_filter1 = train.target == 1
Natural Language Processing with Disaster Tweets
7,371,124
learner.save('kannada-stage2' )<load_pretrained>
train["length"] = train.text.map(len) test["length"] = test.text.map(len )
Natural Language Processing with Disaster Tweets
7,371,124
learner.load('kannada-stage2' )<define_variables>
train["word_cnt"] = train.text.apply(lambda x : len(x.split(" "))) test["word_cnt"] = test.text.apply(lambda x : len(x.split(" "))) train["a_count"] = train.text.apply(lambda x : len([char for char in str(x)if char == "@"])) test["a_count"] = test.text.apply(lambda x : len([char for char in str(x)if char == "@"])) tr...
Natural Language Processing with Disaster Tweets
7,371,124
img = learner.data.valid_ds[0][0]<predict_on_test>
def dict_formation(data): dict_word = {} for sent in data.text.tolist() : words = sent.split(" ") for word in words: word = word.lower() try: dict_word[word] = dict_word[word]+1 except: dict_word[word] = 1 return dict_word
Natural Language Processing with Disaster Tweets
7,371,124
learner.predict(img )<predict_on_test>
train_target0_words_dict = dict_formation(train[train_filter0]) train_target1_words_dict = dict_formation(train[train_filter1]) test_words_dict = dict_formation(test) train_word_dict = dict_formation(train )
Natural Language Processing with Disaster Tweets
7,371,124
<load_from_csv>
def get_ngram_dataframe(n, data, label): train_ngram = ngrams(data.text.str.cat(sep=' ' ).split() , n=n) train_ngram = Counter(train_ngram) train_ngram = dict(train_ngram) train_ngram = dict(sorted(train_ngram.items() , key=lambda x: x[1], reverse=True)) train_ngram_df = pd.DataFrame() train_ngram_df[label] = train_...
Natural Language Processing with Disaster Tweets
7,371,124
test_csv = pd.read_csv('.. /input/Kannada-MNIST/test.csv') test_csv.drop('id',axis = 'columns',inplace = True) sub_df = pd.DataFrame(columns=['id','label']) test_data = np.array(test_csv )<normalization>
%%time glove = '.. /input/glove6b100dtxt/glove.6B.100d.txt' print("Extracting GloVe embedding") embed_glove = load_embed(glove )
Natural Language Processing with Disaster Tweets
7,371,124
def get_img(data): t1 = data.reshape(28,28)/255 t1 = np.stack([t1]*3,axis=0) img = Image(FloatTensor(t1)) return img<import_modules>
def build_vocab(texts): sentences = texts.apply(lambda x: x.split() ).values vocab = {} for sentence in sentences: for word in sentence: try: vocab[word.lower() ] += 1 except KeyError: vocab[word.lower() ] = 1 return vocab
Natural Language Processing with Disaster Tweets
7,371,124
from fastprogress import progress_bar<feature_engineering>
def check_coverage(vocab, embeddings_index): known_words = {} unknown_words = {} nb_known_words = 0 nb_unknown_words = 0 for word in vocab.keys() : try: known_words[word] = embeddings_index[word] nb_known_words += vocab[word] except: unknown_words[word] = vocab[word] nb_unknown_words += vocab[word] pass print('Found ...
Natural Language Processing with Disaster Tweets
7,371,124
def decr(ido): return ido-1 sub_df['id'] = sub_df['id'].map(decr )<save_to_csv>
vocab_train = build_vocab(train['text']) print("Glove : Train") oov_glove_train = check_coverage(vocab_train, embed_glove) vocab_test = build_vocab(test['text']) print("Glove : Test") oov_glove_test = check_coverage(vocab_test, embed_glove )
Natural Language Processing with Disaster Tweets
7,371,124
sub_df.to_csv("submission.csv", index=False )<load_from_csv>
contraction_mapping = {"ain't": "is not", "aren't": "are not","can't": "cannot", "'cause": "because", "could've": "could have", "couldn't": "could not", "didn't": "did not", "doesn't": "does not", "don't": "do not", "hadn't": "had not", "hasn't": "has not", "haven't": "have not", "he'd": "he would", "he'll": "he will",...
Natural Language Processing with Disaster Tweets
7,371,124
train_data = pd.read_csv(".. /input/Kannada-MNIST/train.csv") train_data.shape<split>
%%time train.text = train.text.apply(lambda x: x.lower()) test.text = test.text.apply(lambda x: x.lower() )
Natural Language Processing with Disaster Tweets
7,371,124
X_train_test = train_data.values[:, 1:] y_train_test = train_data.label.values X_train, X_test, y_train, y_test = train_test_split(X_train_test, y_train_test, test_size = 0.02, random_state=42) print('Train shapes: ', X_train.shape, y_train.shape) print('Test shapes: ', X_test.shape, y_test.shape )<prepare_output>
%%time train.text = train.text.apply(lambda x : " ".join([contraction_mapping[word].lower() if word in contraction_mapping.keys() else word.lower() for word in x.split(" ")])) test.text = test.text.apply(lambda x : " ".join([contraction_mapping[word].lower() if word in contraction_mapping.keys() else word.lower() for w...
Natural Language Processing with Disaster Tweets
7,371,124
print(np.min(X_train), np.max(X_train)) X_train_max = np.max(X_train) X_train = X_train /(0.5 * X_train_max)- 1 print(np.min(X_train), np.max(X_train)) print(np.min(X_test), np.max(X_test)) X_test = X_test /(0.5 * X_train_max)- 1 print(np.min(X_test), np.max(X_test))<import_modules>
vocab_train = build_vocab(train['text']) print("Glove : Train") oov_glove_train = check_coverage(vocab_train, embed_glove) vocab_test = build_vocab(test['text']) print("Glove : Test") oov_glove_test = check_coverage(vocab_test, embed_glove )
Natural Language Processing with Disaster Tweets
7,371,124
from keras.layers import * from keras.models import Sequential from keras.optimizers import * from keras import regularizers from keras.utils import plot_model, model_to_dot from IPython.display import SVG<choose_model_class>
def split_textnum(text): match = re.match(r"([a-z]+ )([0-9]+)", text, re.I) if match: items = " ".join(list(match.groups())) else: match = re.match(r"([0-9]+ )([a-z]+)", text, re.I) if match: items = " ".join(list(match.groups())) else: return text return(items )
Natural Language Processing with Disaster Tweets
7,371,124
model = Sequential() l2_reg_conv2d = 0 l2_reg_dense = 0.01 activation_type = 'relu' model.add(Conv2D(64, kernel_size=3, activation=activation_type, input_shape=(28, 28, 1), padding='same', kernel_regularizer=regularizers.l2(l2_reg_conv2d))) model.add(BatchNormalization()) model.add(Conv2D(64, kernel_size=3, activatio...
def clean_text(text): text = re.sub(r"%20", " ", text) text = text.replace(r"@", " ") text = text.replace(r" text = text.replace(r"'", " ") text = text.replace(r"\x89û_", " ") text = text.replace(r"??????", " ") text = text.replace(r"\x89ûò", " ") text = text.replace(r"16yr", "16 year") text = text.replace(r"re\...
Natural Language Processing with Disaster Tweets
7,371,124
datagen = ImageDataGenerator( rotation_range = 20, width_shift_range = 0.3, height_shift_range = 0.3, shear_range = 0.2, zoom_range = 0.3, horizontal_flip = False )<train_model>
%%time train.text = train.text.apply(lambda x : clean_text(x)) test.text = test.text.apply(lambda x : clean_text(x)) train.text = train.text.apply(lambda x : " ".join([contraction_mapping[word].lower() if word in contraction_mapping.keys() else word.lower() for word in x.split(" ")])) test.text = test.text.apply(lambda...
Natural Language Processing with Disaster Tweets
7,371,124
epochs = 75 batch_size = 128 X_train = X_train.reshape(X_train.shape[0],28,28,1) X_test = X_test.reshape(X_test.shape[0],28,28,1) train_story = model.fit_generator(datagen.flow(X_train, y_train, batch_size=batch_size), epochs = epochs, steps_per_epoch = 100, validation_data =(X_test, y_test), callbacks=[ ModelCheckpo...
vocab_train = build_vocab(train['text']) print("Glove : Train") oov_glove_train = check_coverage(vocab_train, embed_glove) vocab_test = build_vocab(test['text']) print("Glove : Test") oov_glove_test = check_coverage(vocab_test, embed_glove )
Natural Language Processing with Disaster Tweets
7,371,124
log_batch_norm = np.array(pd.read_csv("/kaggle/working/learning_log_RMSprop_with_BN.csv")['val_accuracy']) log_no_batch_norm = np.array(pd.read_csv("/kaggle/working/learning_log_RMSprop_without_BN.csv")['val_accuracy']) plt.figure(figsize=(20,10)) plt.plot(range(1, 11), log_batch_norm, label='with BatchNorm') plt.pl...
lemmatizer = WordNetLemmatizer() train.text = train.text.apply(lambda x : "".join([lemmatizer.lemmatize(word)for word in x])) test.text = test.text.apply(lambda x : "".join([lemmatizer.lemmatize(word)for word in x]))
Natural Language Processing with Disaster Tweets
7,371,124
log_softmax = np.array(pd.read_csv("/kaggle/working/learning_log_RMSprop_softmax.csv")['val_accuracy']) log_elu = np.array(pd.read_csv("/kaggle/working/learning_log_RMSprop_elu.csv")['val_accuracy']) log_relu = np.array(pd.read_csv("/kaggle/working/learning_log_RMSprop_relu.csv")['val_accuracy']) log_tanh = np.array...
vocab_train = build_vocab(train['text']) print("Glove : Train") oov_glove_train = check_coverage(vocab_train, embed_glove) vocab_test = build_vocab(test['text']) print("Glove : Test") oov_glove_test = check_coverage(vocab_test, embed_glove )
Natural Language Processing with Disaster Tweets
7,371,124
<load_from_csv>
del oov_glove_test del embed_glove gc.collect()
Natural Language Processing with Disaster Tweets
7,371,124
log_SGD = np.array(pd.read_csv("/kaggle/working/learning_log_SGD.csv")['val_accuracy']) log_SGD_mom = np.array(pd.read_csv("/kaggle/working/learning_log_SGD_mom.csv")['val_accuracy']) log_Adam = np.array(pd.read_csv("/kaggle/working/learning_log_Adam.csv")['val_accuracy']) log_Adadelta = np.array(pd.read_csv("/kaggl...
class ClassificationReport(Callback): def __init__(self, train_data=() , validation_data=()): super(Callback, self ).__init__() self.X_train, self.Y_train = train_data self.X_val, self.Y_val = validation_data self.train_precision_score = [] self.train_recall_score = [] self.train_f1_score = [] self.val_precision_score ...
Natural Language Processing with Disaster Tweets
7,371,124
test_csv = pd.read_csv(".. /input/Kannada-MNIST/test.csv") X_val = np.array(test_csv.drop("id",axis=1), dtype=np.float32) X_val.shape<predict_on_test>
!wget --quiet https://raw.githubusercontent.com/tensorflow/models/master/official/nlp/bert/tokenization.py bert_layer = hub.KerasLayer('https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/1', trainable=True )
Natural Language Processing with Disaster Tweets
7,371,124
best_model = load_model('/kaggle/working/best_kannada_model.h5') Y_val = best_model.predict(X_val) Y_val = np.argmax(Y_val, axis = 1 )<save_to_csv>
class BertTraining: def __init__(self, bert_layer, fold_k=2, dropout=0.2, max_seq_len=160, lr=0.0001, epochs=15, batch_size=32): self.fold_k = fold_k self.bert_layer = bert_layer self.max_seq_len = max_seq_len self.lr = lr self.dropout = dropout self.epochs = epochs self.batch_size = batch_size self.models = [] self.sc...
Natural Language Processing with Disaster Tweets
7,371,124
submission = pd.read_csv(".. /input/Kannada-MNIST/sample_submission.csv") submission['label'] = Y_val submission.to_csv("submission.csv",index=False )<import_modules>
SEED = 42 clf = BertTraining(bert_layer, fold_k=3, dropout=0.5, max_seq_len=140, lr=0.0001, epochs=20, batch_size=64) clf.train_model(train )
Natural Language Processing with Disaster Tweets
7,371,124
import pandas as pd import numpy as np import seaborn as sns from sklearn.model_selection import train_test_split from sklearn import metrics import time import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.optimizers import Adam from tensorflow.keras.preprocessing.image import I...
prediction = clf.predict(test) prediction
Natural Language Processing with Disaster Tweets
7,371,124
train_data = pd.read_csv('/kaggle/input/Kannada-MNIST/train.csv') test_data = pd.read_csv("/kaggle/input/Kannada-MNIST/test.csv") dig_data = pd.read_csv("/kaggle/input/Kannada-MNIST/Dig-MNIST.csv" )<prepare_x_and_y>
prediction = np.where(prediction < 0.5, 0, 1) prediction
Natural Language Processing with Disaster Tweets
7,371,124
data_train = train_data.iloc[:,1:].values x_train = data_train.reshape(data_train.shape[0], 28, 28, 1) train_label = train_data.iloc[:,0].values y_train = tf.keras.utils.to_categorical(train_label, 10) print(x_train.shape, y_train.shape )<categorify>
result = pd.DataFrame() result["id"] = test['id'] result["target"] = np.squeeze(prediction) result.head()
Natural Language Processing with Disaster Tweets
7,371,124
data_val=dig_data.drop('label',axis=1 ).iloc[:,:].values x_val = data_val.reshape(data_val.shape[0], 28, 28,1) val_label=dig_data.label y_val = tf.keras.utils.to_categorical(val_label, 10) print(x_val.shape, y_val.shape )<choose_model_class>
result.target.value_counts()
Natural Language Processing with Disaster Tweets
7,371,124
<choose_model_class><EOS>
result.to_csv('submission.csv', index=False )
Natural Language Processing with Disaster Tweets
11,292,835
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<normalization>
import numpy as np import pandas as pd import os import seaborn as sns import matplotlib.pyplot as plt from nltk.corpus import stopwords import string, re from bs4 import BeautifulSoup from wordcloud import WordCloud from keras.preprocessing import text, sequence from nltk.tokenize.toktok import ToktokTokenizer from sk...
Natural Language Processing with Disaster Tweets
11,292,835
def lr_decay(epoch): return learning_rate * 0.99 ** epoch<choose_model_class>
np.random.seed(1) tf.random.set_seed(1 )
Natural Language Processing with Disaster Tweets
11,292,835
train_data_generator = ImageDataGenerator(rescale = 1./255., rotation_range = 20, width_shift_range = 0.1, height_shift_range = 0.1, shear_range = 0.1, zoom_range = [0.2, 1.2], horizontal_flip = False) val_data_generator = ImageDataGenerator(rescale=1./255 )<choose_model_class>
train_df = pd.read_csv('.. /input/nlp-getting-started/train.csv', index_col='id') test_df = pd.read_csv('.. /input/nlp-getting-started/test.csv', index_col='id' )
Natural Language Processing with Disaster Tweets
11,292,835
model.compile(optimizer=optimizer, loss=['categorical_crossentropy'], metrics=['accuracy'] )<train_model>
stop = set(stopwords.words('english')) punctuation = list(string.punctuation) stop.update(punctuation )
Natural Language Processing with Disaster Tweets
11,292,835
start = time.time() time_spent = 0 accuracy = [] val_accuracy = [] for epoch in range(220): time_spent = time.time() -start if time_spent >= 7150: break else: epoch += 1 print('epoch:', epoch) history = model.fit_generator( train_data_generator.flow(x_train,y_train, batch_size=batch_size), steps_per_epoch=100, epochs...
def strip_html(text): soup = BeautifulSoup(text, "html.parser") return soup.get_text() def remove_between_square_brackets(text): return re.sub('\[[^]]*\]', '', text) def remove_url(text): return re.sub(r'http\S+', '', text) def add_space(text): return re.sub('%20', ' ', text) def remove_stopwords(text): final_text ...
Natural Language Processing with Disaster Tweets
11,292,835
x_test = x_test/255 predictions = model.predict_classes(x_test) submission = pd.read_csv('.. /input/Kannada-MNIST/sample_submission.csv') submission['label'] = predictions submission.head()<save_to_csv>
def preprocess_df(df): df = df.fillna("") df['text'] = df['location'] + " " + df['keyword'] + " " + df['text'] del df['keyword'] del df['location'] df['text'] = df['text'].apply(denoise_text) return df
Natural Language Processing with Disaster Tweets
11,292,835
submission.to_csv("submission.csv",index=False )<train_model>
train_df = preprocess_df(train_df) test_df = preprocess_df(test_df )
Natural Language Processing with Disaster Tweets
11,292,835
print('end...' )<init_hyperparams>
X_train, X_dev, y_train, y_dev = train_test_split(train_df.text.values, train_df.target.values )
Natural Language Processing with Disaster Tweets
11,292,835
<load_from_csv>
max_features = 10000 max_len = 300
Natural Language Processing with Disaster Tweets
11,292,835
test5000 = pd.read_csv(".. /input/Kannada-MNIST/test.csv") train = pd.read_csv(".. /input/Kannada-MNIST/train.csv") print(train.shape) print(test5000.shape )<prepare_x_and_y>
tokenizer = text.Tokenizer(num_words=max_features) tokenizer.fit_on_texts(X_train )
Natural Language Processing with Disaster Tweets
11,292,835
X_train = train.drop(labels = ["label"],axis = 1) X_train = X_train / 255.0 X_train = X_train.values.reshape(-1,28,28,1) Y_trainlabel = train["label"] Y_train = to_categorical(Y_trainlabel, num_classes = 10) X_test5000 = test5000.drop(labels = ["id"],axis = 1) X_test5000 = X_test5000 / 255.0 X_test5000 = X_test5000...
tokenized_train = tokenizer.texts_to_sequences(X_train) X_train = sequence.pad_sequences(tokenized_train, maxlen=max_len) tokenized_dev = tokenizer.texts_to_sequences(X_dev) X_dev = sequence.pad_sequences(tokenized_dev, maxlen=max_len )
Natural Language Processing with Disaster Tweets
11,292,835
init = he_normal(seed=82) nets = 3 model = [0] *(nets+1) for j in range(nets+1): model[j] = Sequential() model[j].add(Conv2D(32, kernel_size=3, activation='relu' , kernel_initializer=init, input_shape=(28, 28, 1))) model[j].add(BatchNormalization()) model[j].add(Conv2D(32, kernel_size=3, activation='relu' , kernel_...
EMBEDDING_FILE = '.. /input/glove-twitter/glove.twitter.27B.100d.txt'
Natural Language Processing with Disaster Tweets
11,292,835
for j in range(nets): loadmodelname = ".. /input/kmnist-trio/weights_N" + str(j) model[j].load_weights(loadmodelname) savemodelname = "weights_N" + str(j) model[j].save_weights(savemodelname) print("Saving", loadmodelname, "back to", savemodelname )<train_model>
all_embs = np.stack(list(embeddings_index.values())) emb_mean,emb_std = all_embs.mean() , all_embs.std() embed_size = all_embs.shape[1] word_index = tokenizer.word_index nb_words = min(max_features, len(word_index)) embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size)) for word, i in word_index....
Natural Language Processing with Disaster Tweets
11,292,835
datagen = ImageDataGenerator(rotation_range=10, zoom_range = 0.1, width_shift_range=0.1, height_shift_range=0.1) annealer = LearningRateScheduler(lambda x: 1e-3 * 0.95 ** x, verbose=0) nets2train = 0 history = [0] * nets2train epoks = 35 for j in range(nets2train): rs = 10 * j + 1 X_train2, X_val2, Y_train2, Y_val2 =...
batch_size = 1024 epochs = 15 embed_size = 100
Natural Language Processing with Disaster Tweets
11,292,835
results5000 = np.zeros(( X_test5000.shape[0], 10)) nets4predict = 3 allthree = False for j in range(nets4predict): if allthree or j== 2: print("CNN",j) loadmodelname = "weights_N" + str(j) model[j].load_weights(loadmodelname) results5000 = results5000 + model[j].predict(X_test5000) results5000 = np.argmax(results50...
learning_rate_reduction = ReduceLROnPlateau(monitor='val_accuracy', patience = 2, verbose=1,factor=0.5, min_lr=0.00001 )
Natural Language Processing with Disaster Tweets
11,292,835
import numpy as np import pandas as pd import tensorflow as tf<import_modules>
model = Sequential() model.add(Embedding(max_features, output_dim=embed_size, weights=[embedding_matrix], input_length=max_len, trainable=False)) model.add(LSTM(units=128 , return_sequences = False , recurrent_dropout = 0.3 , dropout = 0.3)) model.add(Dense(units=64 , activation = 'relu', kernel_regularizer='l2')) mode...
Natural Language Processing with Disaster Tweets
11,292,835
Activation, LeakyReLU, Flatten, Dropout, BatchNormalization <load_from_csv>
history = model.fit(X_train, y_train, batch_size = batch_size , validation_data =(X_dev,y_dev), epochs = epochs , callbacks = [learning_rate_reduction] )
Natural Language Processing with Disaster Tweets
11,292,835
train_datas=pd.read_csv(".. /input/Kannada-MNIST/train.csv") val_datas = pd.read_csv(".. /input/Kannada-MNIST/Dig-MNIST.csv" )<split>
print("Accuracy of the model on Training Data is - " , model.evaluate(X_train,y_train)[1]*100) print("Accuracy of the model on Dev Data is - " , model.evaluate(X_dev,y_dev)[1]*100 )
Natural Language Processing with Disaster Tweets
11,292,835
datas = pd.concat([train_datas,val_datas],axis=0) print(datas.shape) datas_X = np.array(datas.drop("label",axis=1),dtype=np.float32) datas_Y = np.array(datas[["label"]],dtype=np.int32) train_X,val_X,train_Y,val_Y = train_test_split(datas_X,datas_Y,test_size=0.2,shuffle=True )<train_model>
X_test = test_df.text.values
Natural Language Processing with Disaster Tweets
11,292,835
train_X = train_X / 255.0 val_X = val_X / 255.0 train_X = np.reshape(train_X,(-1,28,28,1)) val_X = np.reshape(val_X,(-1,28,28,1))<import_modules>
tokenized_dev = tokenizer.texts_to_sequences(X_test) X_test = sequence.pad_sequences(tokenized_dev, maxlen=max_len )
Natural Language Processing with Disaster Tweets
11,292,835
from tensorflow.keras.layers import Activation,GlobalAveragePooling2D<choose_model_class>
classes = model.predict_classes(X_test)[:, 0]
Natural Language Processing with Disaster Tweets