kernel_id
int64
24.2k
23.3M
prompt
stringlengths
8
1.85M
completetion
stringlengths
1
182k
comp_name
stringlengths
5
57
14,068,986
learning_rate = 0.001 def step_decay(epoch): initial_lrate = learning_rate drop = 0.1 epochs_drop = 20.0 lrate = initial_lrate * np.power(drop, np.floor(( epoch)/epochs_drop)) tf.print("Learning rate: ", lrate) return lrate lrate = tf.keras.callbacks.LearningRateScheduler(step_decay) early_stop = tf.keras.callbacks.E...
corpus_disaster, corpus_non_disaster = create_corpus(1), create_corpus(0) counter_disaster, counter_non_disaster = Counter(corpus_disaster), Counter(corpus_non_disaster) x_disaster, y_disaster, x_non_disaster, y_non_disaster = [], [], [], [] counter = 0 for word, count in counter_disaster.most_common() [0:100]: if(wo...
Natural Language Processing with Disaster Tweets
14,068,986
mpnn = MPNN(mp_int_dim = 512, up_int_dim = 1024, out_int_dim = 512, state_dim = 256, T = 3) mpnn.compile(opt, log_mae, metrics = [mae, log_mae]) <define_variables>
def bigrams(target): corpus = train[train["target"] == target]["text"] count_vec = CountVectorizer(ngram_range=(2, 2)).fit(corpus) bag_of_words = count_vec.transform(corpus) sum_words = bag_of_words.sum(axis=0) words_freq = [(word, sum_words[0, idx])for word, idx in count_vec.vocabulary_.items() ] words_freq =sorted...
Natural Language Processing with Disaster Tweets
14,068,986
batch_size = 64 epochs = 30 <train_model>
def remove_pattern(input_txt, pattern): r = re.findall(pattern, input_txt) for i in r: input_txt = re.sub(i, '', input_txt) return input_txt train['tweet'] = np.vectorize(remove_pattern )(train['text'], " test['tweet'] = np.vectorize(remove_pattern )(test['text'], " train.head() train['tweet'] = train['tweet'].str.re...
Natural Language Processing with Disaster Tweets
14,068,986
def train() : nodes_train = np.load(datadir + "internalgraphdata/nodes_train.npz")['arr_0'] in_edges_train = np.load(datadir + "internalgraphdata/in_edges_train.npz")['arr_0'] out_edges_train = np.load(datadir + "internalgraphdata/out_edges_train.npz")['arr_0'] out_labels = out_edges_train.reshape(-1,out_edges_train.sh...
warnings.filterwarnings("ignore") tqdm.pandas() stopword=set(STOPWORDS) lem = WordNetLemmatizer() tokenizer=TweetTokenizer() np.random.seed(0) random_state = 29
Natural Language Processing with Disaster Tweets
14,068,986
%%time preds, train_size, history = train()<load_pretrained>
!pip install GPUtil def free_gpu_cache() : print("Initial GPU Usage") gpu_usage() torch.cuda.empty_cache() cuda.select_device(0) cuda.close() cuda.select_device(0) for obj in gc.get_objects() : if torch.is_tensor(obj): del obj gc.collect() print("GPU Usage after emptying the cache") gpu_usage()
Natural Language Processing with Disaster Tweets
14,068,986
mpnn.save_weights("model.h5" )<load_pretrained>
train = pd.read_csv(".. /input/nlp-getting-started/train.csv") test = pd.read_csv(".. /input/nlp-getting-started/test.csv") sub= pd.read_csv(".. /input/nlp-getting-started/sample_submission.csv" )
Natural Language Processing with Disaster Tweets
14,068,986
with open('/trainHistoryDict.pkl', 'wb')as file_pi: pickle.dump(history.history, file_pi )<load_from_csv>
abbreviations = { "$" : " dollar ", "€" : " euro ", "4ao" : "for adults only", "a.m" : "before midday", "a3" : "anytime anywhere anyplace", "aamof" : "as a matter of fact", "acct" : "account", "adih" : "another day in hell", "afaic" : "as far as i am concerned", "afaict" : "as far as i can tell", "afaik" : "as far as i...
Natural Language Processing with Disaster Tweets
14,068,986
train = pd.read_csv(datadir + "champs-scalar-coupling/train.csv") test = pd.read_csv(datadir + "champs-scalar-coupling/test.csv") train_mol_names = train['molecule_name'].unique() val = train[train.molecule_name.isin(train_mol_names[train_size:])] val_group = val.groupby('molecule_name' )<compute_test_metric>
def remove_URL(text): url = re.compile(r'https?://\S+|www\.\S+') return url.sub(r'URL',text) def remove_HTML(text): html=re.compile(r'<.*?>') return html.sub(r'',text) def remove_not_ASCII(text): text = ''.join([word for word in text if word in string.printable]) return text def word_abbrev(word): return abbreviat...
Natural Language Processing with Disaster Tweets
14,068,986
def make_outs(test_group, preds): i = 0 x = np.array([]) for test_gp, preds in zip(test_group, preds): if(not i%1000): print(i) gp = test_gp[1] x = np.append(x,(preds[gp['atom_index_0'].values, gp['atom_index_1'].values] + preds[gp['atom_index_1'].values, gp['atom_index_0'].values])/2.0) i = i+1 return x def group_m...
def clean_tweet(text): text = remove_URL(text) text = remove_HTML(text) text = remove_not_ASCII(text) text = text.lower() text = replace_abbrev(text) text = remove_mention(text) text = remove_number(text) text = remove_emoji(text) text = transcription_sad(text) text = transcription_smile(text) text = transcrip...
Natural Language Processing with Disaster Tweets
14,068,986
max_size = 29 preds = preds.reshape(( -1,max_size, max_size)) out_unscaled = make_outs(val_group, preds )<feature_engineering>
train["clean_text"] = train["text"].apply(clean_tweet) test["clean_text"] = test["text"].apply(clean_tweet) train["clean_tokens"] = train["clean_text"].apply(lambda x: word_tokenize(x)) test["clean_tokens"] = test["clean_text"].apply(lambda x: word_tokenize(x))
Natural Language Processing with Disaster Tweets
14,068,986
val['pred_scalar_coupling_constant'] = out_unscaled coups_to_isolate = ['1JHC', '1JHN', '2JHC', '2JHH', '2JHN', '3JHC', '3JHH', '3JHN'] for i, coup in enumerate(coups_to_isolate): scale_min = train['scalar_coupling_constant'].loc[train.type == coup].min() scale_max = train['scalar_coupling_constant'].loc[train.type == ...
skip_gram_model = Word2Vec(train['clean_tokens'],size=150,window=3,min_count=2,sg=1) skip_gram_model.train(train['clean_tokens'],total_examples=len(train['clean_tokens']),epochs=10) cbow_model = Word2Vec(train['clean_tokens'],size=150,window=3,min_count=2) cbow_model.train(train['clean_tokens'],total_examples=len(tr...
Natural Language Processing with Disaster Tweets
14,068,986
for coup in coups_to_isolate: log_mae = group_mean_log_mae(val['scalar_coupling_constant'], val['pred_scalar_coupling_constant'], val['type'][val.type == coup]) print(coup,"\t", log_mae) total = group_mean_log_mae(val['scalar_coupling_constant'], val['pred_scalar_coupling_constant'], val['type']) print("") print("T...
max_features=5000 count_vectorizer = CountVectorizer(max_features=max_features) sparce_matrix_train=count_vectorizer.fit_transform(train['clean_text']) sparce_matrix_test=count_vectorizer.fit_transform(train['clean_text']) def count_vector(data): count_vectorizer = CountVectorizer() vect = count_vectorizer.fit_trans...
Natural Language Processing with Disaster Tweets
14,068,986
nodes_test = np.load(datadir + "internalgraphdata/nodes_test.npz")['arr_0'] in_edges_test = np.load(datadir + "internalgraphdata/in_edges_test.npz")['arr_0'] in_edges_test = in_edges_test.reshape(-1,in_edges_test.shape[1]*in_edges_test.shape[2],in_edges_test.shape[3] )<predict_on_test>
metrics = pd.DataFrame(columns=['model' ,'vectoriser', 'f1 score', 'train accuracy','test accuracy'] )
Natural Language Processing with Disaster Tweets
14,068,986
preds = mpnn.predict({'adj_input' : in_edges_test, 'nod_input': nodes_test}, verbose=1 )<save_model>
models=[ XGBClassifier(max_depth=6, n_estimators=1000), LogisticRegression(random_state=random_state), SVC(random_state=random_state), MultinomialNB() , DecisionTreeClassifier(random_state = random_state), KNeighborsClassifier() , RandomForestClassifier(random_state=random_state), ]
Natural Language Processing with Disaster Tweets
14,068,986
np.save("preds_kernel.npy" , preds )<groupby>
for model in models: y = train.target x = X_train_count x_train, x_test, y_train, y_test = train_test_split(x,y, test_size = 0.3) fit_and_predict(model,x_train,x_test,y_train,y_test,'Count vector') x = X_train_tfidf x_train, x_test, y_train, y_test = train_test_split(x,y, test_size = 0.3) fit_and_predict(model,x_tra...
Natural Language Processing with Disaster Tweets
14,068,986
test_group = test.groupby('molecule_name' )<normalization>
metrics = metrics.sort_values('f1 score',ascending=False )
Natural Language Processing with Disaster Tweets
14,068,986
preds = preds.reshape(( -1,max_size, max_size)) out_unscaled = make_outs(test_group, preds )<feature_engineering>
free_gpu_cache()
Natural Language Processing with Disaster Tweets
14,068,986
test['scalar_coupling_constant'] = out_unscaled coups_to_isolate = ['1JHC', '1JHN', '2JHC', '2JHH', '2JHN', '3JHC', '3JHH', '3JHN'] for i, coup in enumerate(coups_to_isolate): scale_min = train['scalar_coupling_constant'].loc[train.type == coup].min() scale_max = train['scalar_coupling_constant'].loc[train.type == coup...
from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow import keras from keras.models import Sequential from keras.layers import Dense, Embedding, LSTM,GRU, Dropout, Activation, Input, Flatten, Bidirectional, Conv1D, MaxPooling1D from ...
Natural Language Processing with Disaster Tweets
14,068,986
test[['id','scalar_coupling_constant']].to_csv('submission.csv', index=False )<install_modules>
def train_lstm(x_train,x_test,y_train,y_test,vectorizer_name,vocab_size,input_length): epochs = 1 verbose = 1 batch_size = 32 embed_dim = 32 optimizer = optimizers.Adam(lr=0.002) model = Sequential() model.add(Embedding(vocab_size, embed_dim,input_length = input_length)) model.add(Dropout(0.2)) model.add(LSTM(32, drop...
Natural Language Processing with Disaster Tweets
14,068,986
!pip install tensorflow-gpu==2.0a0<import_modules>
y = train['target'].values x_train, x_test, y_train, y_test = train_test_split(X_train_skip_gram,y, test_size = 0.3) train_lstm(x_train,x_test,y_train,y_test, 'skip gram vector',5329,150)
Natural Language Processing with Disaster Tweets
14,068,986
print(tf.__version__ )<set_options>
%reset -f
Natural Language Processing with Disaster Tweets
14,068,986
tf.test.is_gpu_available( cuda_only=False, min_cuda_compute_capability=None ) <define_variables>
!pip install GPUtil def free_gpu_cache() : print("Initial GPU Usage") gpu_usage() torch.cuda.empty_cache() cuda.select_device(0) cuda.close() cuda.select_device(0) for obj in gc.get_objects() : if torch.is_tensor(obj): del obj gc.collect() print("GPU Usage after emptying the cache") gpu_usage() free_gpu_cache()
Natural Language Processing with Disaster Tweets
14,068,986
tf.random.set_seed(42) datadir = ".. /input/"<choose_model_class>
import re import torch from transformers import ElectraTokenizer, ElectraForSequenceClassification,AdamW import torch from sklearn.metrics import classification_report import random import time import datetime import numpy as np import pandas as pd from transformers import get_linear_schedule_with_warmup from torch.uti...
Natural Language Processing with Disaster Tweets
14,068,986
class Message_Passer_1(tf.keras.layers.Layer): def __init__(self, intermediate_dim, state_dim): super(Message_Passer_1, self ).__init__() self.concat_layer = tf.keras.layers.Concatenate() self.hidden_layer_1 = tf.keras.layers.Dense(units=intermediate_dim, activation=tf.nn.relu) self.output_layer = tf.keras.layers.Dens...
if torch.cuda.is_available() : device = torch.device("cuda") print('We will use the GPU:', torch.cuda.get_device_name(0)) else: print('No GPU available, using the CPU instead.') device = torch.device("cpu" )
Natural Language Processing with Disaster Tweets
14,068,986
class Message_Agg(tf.keras.layers.Layer): def __init__(self): super(Message_Agg, self ).__init__() def call(self, messages): return tf.math.reduce_sum(messages, 2 )<choose_model_class>
train = pd.read_csv(".. /input/nlp-getting-started/train.csv") test = pd.read_csv(".. /input/nlp-getting-started/test.csv") df_train= train df_test= test
Natural Language Processing with Disaster Tweets
14,068,986
class Update_Func_1(tf.keras.layers.Layer): def __init__(self, intermediate_dim, state_dim): super(Update_Func_1, self ).__init__() self.concat_layer = tf.keras.layers.Concatenate() self.hidden_layer_1 = tf.keras.layers.Dense(units=intermediate_dim, activation=tf.nn.relu) self.output_layer = tf.keras.layers.Dense(unit...
def preprocess(text): text=text.lower() text = re.sub(r'https?:\/\/.*[\r ]*', '', text) text = re.sub(r'http?:\/\/.*[\r ]*', '', text) text=text.replace(r'&amp;?',r'and') text=text.replace(r'&lt;',r'<') text=text.replace(r'&gt;',r'>') text = re.sub(r"(?:\@)\w+", '', text) text=text.encode("ascii",errors="ignore" ...
Natural Language Processing with Disaster Tweets
14,068,986
class Adj_Updater_1(tf.keras.layers.Layer): def __init__(self, intermediate_dim, state_dim): super(Adj_Updater_1, self ).__init__() self.concat_layer = tf.keras.layers.Concatenate() self.hidden_layer_1 = tf.keras.layers.Dense(units=intermediate_dim, activation=tf.nn.relu) self.output_layer = tf.keras.layers.Dense(unit...
df_train=df_train[["text","target"]]
Natural Language Processing with Disaster Tweets
14,068,986
class Edge_Regressor(tf.keras.layers.Layer): def __init__(self, intermediate_dim): super(Edge_Regressor, self ).__init__() self.concat_layer = tf.keras.layers.Concatenate() self.hidden_layer_1 = tf.keras.layers.Dense(units=intermediate_dim, activation=tf.nn.relu) self.hidden_layer_2 = tf.keras.layers.Dense(units=inter...
texts = df_train.text.values labels = df_train.target.values
Natural Language Processing with Disaster Tweets
14,068,986
class MP_Layer(tf.keras.layers.Layer): def __init__(self, mp_int_dim, up_int_dim, out_int_dim, state_dim): super(MP_Layer, self ).__init__(self) self.state_dim = state_dim self.message_passers = Message_Passer_1(intermediate_dim = mp_int_dim, state_dim = state_dim) self.update_functions = Update_Func_1(intermediate_d...
torch.cuda.empty_cache() tokenizer = ElectraTokenizer.from_pretrained('google/electra-base-discriminator') model = ElectraForSequenceClassification.from_pretrained('google/electra-base-discriminator',num_labels=2) model.cuda()
Natural Language Processing with Disaster Tweets
14,068,986
class MP_Layer_edge_only(tf.keras.layers.Layer): def __init__(self, mp_int_dim, up_int_dim, out_int_dim, state_dim): super(MP_Layer_edge_only, self ).__init__(self) self.adj_updaters = Adj_Updater_1(intermediate_dim = up_int_dim, state_dim = state_dim) self.message_aggs = Message_Agg() self.state_dim = state_dim def ...
indices=tokenizer.batch_encode_plus(texts,max_length=64,add_special_tokens=True, return_attention_mask=True,pad_to_max_length=True,truncation=True) input_ids=indices["input_ids"] attention_masks=indices["attention_mask"]
Natural Language Processing with Disaster Tweets
14,068,986
adj_input = tf.keras.Input(shape=(None,), name='adj_input') nod_input = tf.keras.Input(shape=(None,), name='nod_input') class MPNN(tf.keras.Model): def __init__(self, mp_int_dim, up_int_dim, out_int_dim, state_dim, T): super(MPNN, self ).__init__(self) self.MP = [MP_Layer(mp_int_dim, up_int_dim, out_int_dim, state_d...
train_inputs, validation_inputs, train_labels, validation_labels = train_test_split(input_ids, labels, random_state=42, test_size=0.2) train_masks, validation_masks, _, _ = train_test_split(attention_masks, labels, random_state=42, test_size=0.2 )
Natural Language Processing with Disaster Tweets
14,068,986
def log_mae(orig , preds): mask = tf.where(tf.equal(orig, 0), orig, tf.ones_like(orig)) nums = tf.boolean_mask(orig, mask) preds = tf.boolean_mask(preds, mask) reconstruction_error = tf.math.log(tf.reduce_mean(tf.abs(tf.subtract(nums, preds)))) return reconstruction_error def mae(orig , preds): mask = tf.where(tf.equ...
train_inputs = torch.tensor(train_inputs) validation_inputs = torch.tensor(validation_inputs) train_labels = torch.tensor(train_labels, dtype=torch.long) validation_labels = torch.tensor(validation_labels, dtype=torch.long) train_masks = torch.tensor(train_masks, dtype=torch.long) validation_masks = torch.tensor(v...
Natural Language Processing with Disaster Tweets
14,068,986
mpnn = MPNN(mp_int_dim = 512, up_int_dim = 1024, out_int_dim = 512, state_dim = 256, T = 7) mpnn.compile(opt, log_mae, metrics = [mae, log_mae]) <define_variables>
batch_size = 32 train_data = TensorDataset(train_inputs, train_masks, train_labels) train_sampler = RandomSampler(train_data) train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=batch_size) validation_data = TensorDataset(validation_inputs, validation_masks, validation_labels) validation_sam...
Natural Language Processing with Disaster Tweets
14,068,986
batch_size = 64 epochs = 30 <train_model>
optimizer = AdamW(model.parameters() , lr = 6e-6, eps = 1e-8 ) epochs = 5 total_steps = len(train_dataloader)* epochs scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps = 0, num_training_steps = total_steps )
Natural Language Processing with Disaster Tweets
14,068,986
def train() : nodes_train = np.load(datadir + "internalgraphdata/nodes_train.npz")['arr_0'] in_edges_train = np.load(datadir + "internalgraphdata/in_edges_train.npz")['arr_0'] out_edges_train = np.load(datadir + "internalgraphdata/out_edges_train.npz")['arr_0'] out_labels = out_edges_train.reshape(-1,out_edges_train.sh...
def flat_accuracy(preds, labels): pred_flat = np.argmax(preds, axis=1 ).flatten() labels_flat = labels.flatten() return np.sum(pred_flat == labels_flat)/ len(labels_flat )
Natural Language Processing with Disaster Tweets
14,068,986
preds, train_size, history = train()<load_from_csv>
seed_val = 42 random.seed(seed_val) np.random.seed(seed_val) torch.manual_seed(seed_val) torch.cuda.manual_seed_all(seed_val) loss_values = [] for epoch_i in range(0, epochs): print("") print('======== Epoch {:} / {:} ========'.format(epoch_i + 1, epochs)) print('Training...') t0 = time.time() total_loss = 0 mode...
Natural Language Processing with Disaster Tweets
14,068,986
train = pd.read_csv(datadir + "champs-scalar-coupling/train.csv") test = pd.read_csv(datadir + "champs-scalar-coupling/test.csv") train_mol_names = train['molecule_name'].unique() val = train[train.molecule_name.isin(train_mol_names[train_size:])] val_group = val.groupby('molecule_name' )<compute_test_metric>
print("") print("Running Validation...") t0 = time.time() model.eval() preds=[] true=[] eval_loss, eval_accuracy = 0, 0 nb_eval_steps, nb_eval_examples = 0, 0 for batch in validation_dataloader: batch = tuple(t.to(device)for t in batch) b_input_ids, b_input_mask, b_labels = batch with torch.no_grad() : outputs = mod...
Natural Language Processing with Disaster Tweets
14,068,986
def make_outs(test_group, preds): i = 0 x = np.array([]) for test_gp, preds in zip(test_group, preds): if(not i%1000): print(i) gp = test_gp[1] x = np.append(x,(preds[gp['atom_index_0'].values, gp['atom_index_1'].values] + preds[gp['atom_index_1'].values, gp['atom_index_0'].values])/2.0) i = i+1 return x def group_m...
flat_predictions = [item for sublist in preds for item in sublist] flat_predictions = np.argmax(flat_predictions, axis=1 ).flatten() flat_true_labels = [item for sublist in true for item in sublist]
Natural Language Processing with Disaster Tweets
14,068,986
max_size = 29 preds = preds.reshape(( -1,max_size, max_size)) out_unscaled = make_outs(val_group, preds )<feature_engineering>
comments1 = df_test.text.values indices1=tokenizer.batch_encode_plus(comments1,max_length=128,add_special_tokens=True, return_attention_mask=True,pad_to_max_length=True,truncation=True) input_ids1=indices1["input_ids"] attention_masks1=indices1["attention_mask"] prediction_inputs1= torch.tensor(input_ids1) prediction...
Natural Language Processing with Disaster Tweets
14,068,986
val['pred_scalar_coupling_constant'] = out_unscaled coups_to_isolate = ['1JHC', '1JHN', '2JHC', '2JHH', '2JHN', '3JHC', '3JHH', '3JHN'] for i, coup in enumerate(coups_to_isolate): scale_min = train['scalar_coupling_constant'].loc[train.type == coup].min() scale_max = train['scalar_coupling_constant'].loc[train.type == ...
print('Predicting labels for {:,} test sentences...'.format(len(prediction_inputs1))) model.eval() predictions = [] for batch in prediction_dataloader1: batch = tuple(t.to(device)for t in batch) b_input_ids1, b_input_mask1 = batch with torch.no_grad() : outputs1 = model(b_input_ids1, token_type_ids=None, attention_ma...
Natural Language Processing with Disaster Tweets
14,068,986
for coup in coups_to_isolate: log_mae = group_mean_log_mae(val['scalar_coupling_constant'], val['pred_scalar_coupling_constant'], val['type'][val.type == coup]) print(coup,"\t", log_mae) total = group_mean_log_mae(val['scalar_coupling_constant'], val['pred_scalar_coupling_constant'], val['type']) print("") print("T...
sample_sub=pd.read_csv('.. /input/nlp-getting-started/sample_submission.csv') submit=pd.DataFrame({'id':sample_sub['id'].values.tolist() ,'target':flat_predictions} )
Natural Language Processing with Disaster Tweets
14,068,986
<predict_on_test><EOS>
df_leak = pd.read_csv('/kaggle/input/disasters-on-social-media/socialmedia-disaster-tweets-DFE.csv', encoding ='ISO-8859-1')[['choose_one', 'text']] df_leak['target'] =(df_leak['choose_one'] == 'Relevant' ).astype(np.int8) df_leak['id'] = df_leak.index.astype(np.int16) df_leak.drop(columns=['choose_one', 'text'], inp...
Natural Language Processing with Disaster Tweets
13,985,799
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<save_model>
sns.set_style("darkgrid")
Natural Language Processing with Disaster Tweets
13,985,799
np.save("preds_kernel.npy" , preds )<groupby>
df_train = pd.read_csv("/kaggle/input/nlp-getting-started/train.csv") print(df_train.shape) df_train.head()
Natural Language Processing with Disaster Tweets
13,985,799
test_group = test.groupby('molecule_name' )<normalization>
df_test = pd.read_csv("/kaggle/input/nlp-getting-started/test.csv") print(df_test.shape) df_test.head()
Natural Language Processing with Disaster Tweets
13,985,799
preds = preds.reshape(( -1,max_size, max_size)) out_unscaled = make_outs(test_group, preds )<feature_engineering>
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 )
Natural Language Processing with Disaster Tweets
13,985,799
test['scalar_coupling_constant'] = out_unscaled coups_to_isolate = ['1JHC', '1JHN', '2JHC', '2JHH', '2JHN', '3JHC', '3JHH', '3JHN'] for i, coup in enumerate(coups_to_isolate): scale_min = train['scalar_coupling_constant'].loc[train.type == coup].min() scale_max = train['scalar_coupling_constant'].loc[train.type == coup...
set_stopwords = set(stopwords.words('english')) df_train['text_processed'] = df_train['text'].apply(lambda x: re.compile(r'https?://\S+|www\.\S+' ).sub(r'',x)) df_test['text_processed'] = df_test['text'].apply(lambda x: re.compile(r'https?://\S+|www\.\S+' ).sub(r'',x)) df_train['text_processed'] = df_train['text_proces...
Natural Language Processing with Disaster Tweets
13,985,799
test[['id','scalar_coupling_constant']].to_csv('submission.csv', index=False )<define_variables>
abbreviations = { "$" : " dollar ", "€" : " euro ", "4ao" : "for adults only", "a.m" : "before midday", "a3" : "anytime anywhere anyplace", "aamof" : "as a matter of fact", "acct" : "account", "adih" : "another day in hell", "afaic" : "as far as i am concerned", "afaict" : "as far as i can tell", "afaik" : "as far as i...
Natural Language Processing with Disaster Tweets
13,985,799
dtypes = {'atom_index_0':'uint8', 'atom_index_1':'uint8', 'scalar_coupling_constant':'float32', 'num_C':'uint8', 'num_H':'uint8', 'num_N':'uint8', 'num_O':'uint8', 'num_F':'uint8', 'total_atoms':'uint8', 'num_bonds':'uint8', 'num_mol_bonds':'uint8', 'min_d':'float32', 'mean_d':'float32', 'max_d':'float32', 'space_dr':'...
def convert_abbrev(word): return abbreviations[word.lower() ] if word.lower() in abbreviations.keys() else word df_train['text_processed'] = df_train['text_processed'].apply(lambda x: ' '.join([convert_abbrev(word)for word in word_tokenize(x)])) df_test['text_processed'] = df_test['text_processed'].apply(lambda x: ' '....
Natural Language Processing with Disaster Tweets
13,985,799
train = pd.read_csv(".. /input/predmolprop-featureengineering-final/train_extend.csv",dtype=dtypes) test = pd.read_csv(".. /input/predmolprop-featureengineering-finaltest/test_extend.csv",dtype=dtypes )<categorify>
ids_with_target_error = [328,443,513,2619,3640,3900,4342,5781,6552,6554,6570,6701,6702,6729,6861,7226] df_train.loc[df_train['id'].isin(ids_with_target_error),'target'] = 0
Natural Language Processing with Disaster Tweets
13,985,799
cols = ['atom_0_type2','atom_2_type','atom_3_type','atom_end_type2'] for col in cols: enc = LabelEncoder() train[col]=enc.fit_transform(train[col] ).astype(np.uint8) test[col]=enc.transform(test[col] ).astype(np.uint8) del cols<define_variables>
learning_rate = 1e-5 valid = 0.2 epochs_num = 3 batch_size_num = 16
Natural Language Processing with Disaster Tweets
13,985,799
prefix_train= ['id', 'type', 'scalar_coupling_constant'] prefix_test= ['id', 'type'] fc_distance = ['space_dr','min_d','mean_d', 'max_d'] fc_COM = ['Dmin_COM', 'Dmean_COM', 'Dmax_COM'] fc_size = ['num_mol_bonds', 'total_atoms','num_C', 'num_H', 'num_N', 'num_O', 'num_F'] fc_atom_0 = ['atom_0_pc','atom_0_type2','COM_dr_...
!wget --quiet https://raw.githubusercontent.com/tensorflow/models/master/official/nlp/bert/tokenization.py
Natural Language Processing with Disaster Tweets
13,985,799
def ProcessData(df,features,test_size=0.25): if test_size == 0: train_Y = df.pop('scalar_coupling_constant') train_type = df.pop('type') df.pop('id') return df.loc[:,df.columns.map(lambda x: x in features)], train_Y, train_type train_X, val_X, train_Y, val_Y = train_test_split(df.loc[:,df.columns.map(lambda x: x in ...
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
Natural Language Processing with Disaster Tweets
13,985,799
def CalcLMAE(y_true, y_pred, groups, floor=1e-9): maes =(y_true-y_pred ).abs().groupby(groups ).mean() return np.log(maes.map(lambda x: max(x, floor)) ).mean()<categorify>
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...
Natural Language Processing with Disaster Tweets
13,985,799
def SingleRun(df,features, test_size=0.25, model_fn=XGBRegressor, includeType=False, early_stopping_rounds=None, do_SHAP=False, **kwargs): data = ProcessData(df,features,test_size) if(test_size==0): train_X,train_Y,train_type = data else: train_X,train_Y,train_type,val_X,val_Y,val_type = data if includeType: train_X=t...
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, ...
Natural Language Processing with Disaster Tweets
13,985,799
coupling_type = '3JHN' train_sample = train[train.type==coupling_type] features=fc1.copy() if(coupling_type[0]=='2'): features.update(fc_2) elif(coupling_type[0]=='3'): features.update(fc_2[:-1]+fc_3) model_3JHN,_,_=SingleRun(train_sample,features,test_size=0.2,model_fn=XGBRegressor,includeType=False,early_stopping_r...
module_url = "https://tfhub.dev/tensorflow/bert_en_uncased_L-24_H-1024_A-16/1" bert_layer = hub.KerasLayer(module_url, trainable=True )
Natural Language Processing with Disaster Tweets
13,985,799
def RunByType(df,test_size=0.25,model_fn=XGBRegressor,includeType=False,early_stopping_rounds=None,**kwargs): model_dict={} train_LMAE_dict={} val_LMAE_dict={} for coupling_type in coupling_types: print('Now training type:',str(coupling_type)) df_type = df[df['type']==coupling_type] features=fc1.copy() if(coupling_type...
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 )
Natural Language Processing with Disaster Tweets
13,985,799
def PredictByType(df_X,model_dict,df_Y=None): predictions = pd.DataFrame() for coupling_type in coupling_types: print('predicting type:',str(coupling_type)) model = model_dict[coupling_type] df_type = df_X[df_X['type']==coupling_type] features=fc1.copy() if(coupling_type[0]=='2'): features.update(fc_2) elif(coupling_t...
train_input = bert_encode(df_train['text_processed'].values, tokenizer, max_len=160) test_input = bert_encode(df_test['text_processed'].values, tokenizer, max_len=160) train_labels = df_train['target'].values
Natural Language Processing with Disaster Tweets
13,985,799
model_dict=RunByType(train,test_size=0.2,includeType=False,early_stopping_rounds=5, max_depth=11, learning_rate=0.1, n_estimators=10000, verbosity=1, objective='reg:squarederror', booster='gbtree',tree_method= 'gpu_hist', n_jobs=4, gamma=0, min_child_weight=1, max_delta_step=0, subsample=1,colsample_bytree=1, colsample...
model_BERT = build_model(bert_layer, max_len=160) model_BERT.summary()
Natural Language Processing with Disaster Tweets
13,985,799
print('FINISHED!' )<load_from_csv>
checkpoint = ModelCheckpoint('model_BERT.h5', monitor='val_loss', save_best_only=True) train_history = model_BERT.fit( train_input, train_labels, validation_split = valid, epochs = epochs_num, callbacks=[checkpoint], batch_size = batch_size_num )
Natural Language Processing with Disaster Tweets
13,985,799
one = pd.read_csv('.. /input/champs-blending-tutorial/1.csv') two = pd.read_csv('.. /input/champs-blending-tutorial/2.csv') three = pd.read_csv('.. /input/champs-blending-tutorial/3.csv') four = pd.read_csv('.. /input/otherkernelsadded/submission-2.csv') five = pd.read_csv('.. /input/otherkernelsadded/submission-gi...
test_pred = model_BERT.predict(test_input) test_pred_int = test_pred.round().astype('int') train_pred = model_BERT.predict(train_input) train_pred_int = train_pred.round().astype('int' )
Natural Language Processing with Disaster Tweets
13,985,799
warnings.filterwarnings("ignore") warnings.filterwarnings(action="ignore",category=DeprecationWarning) warnings.filterwarnings(action="ignore",category=FutureWarning )<compute_train_metric>
print("F1 Score = " + str(f1_score(df_train['target'], train_pred_int)) )
Natural Language Processing with Disaster Tweets
13,985,799
<load_from_csv><EOS>
df_submission = pd.read_csv("/kaggle/input/nlp-getting-started/sample_submission.csv") df_submission['target'] = test_pred_int df_submission.to_csv("submission.csv", index=False, header=True )
Natural Language Processing with Disaster Tweets
13,104,084
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<load_from_csv>
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import nltk from nltk.corpus import stopwords import tensorflow as tf import tensorflow_addons as tfa from transformers import TFAutoModel, AutoTokenizer
Natural Language Processing with Disaster Tweets
13,104,084
scores_nn = dict() for mol_type_index, mol_type in enumerate(mol_types): print(mol_type, f'- run number {run_number}') try: scores_nn = np.load(f'run_{run_number}_scores_nn.npy', allow_pickle=True ).item() except: scores_nn = dict() train = pd.read_csv(train_and_test_with_feats_folder + '/train_' + mol_type + '.csv' )...
tweet_tokenizer = TweetTokenizer() def normalizeToken(token): lowercased_token = token.lower() if token.startswith("@"): return "@USER" elif lowercased_token.startswith("http")or lowercased_token.startswith("www"): return "HTTPURL" elif len(token)== 1: return demojize(token) else: if token == "’": return "'" elif toke...
Natural Language Processing with Disaster Tweets
13,104,084
sub = pd.read_csv(f'{preds_and_oofs_folder}/final_model_submission.csv') sub.to_csv('final_sub.csv', index=False )<import_modules>
def load_train_set() : df = pd.read_csv("/kaggle/input/nlp-getting-started/train.csv")[["text", "target"]] df["text"] = df["text"].apply(normalizeTweet) return df def load_test_set() : df = pd.read_csv("/kaggle/input/nlp-getting-started/test.csv")[["id", "text"]] df["text"] = df["text"].apply(normalizeTweet) return d...
Natural Language Processing with Disaster Tweets
13,104,084
print(os.listdir('.. /input/')) <load_from_csv>
print(train['target'].value_counts()) print() print(train['target'].value_counts(normalize=True))
Natural Language Processing with Disaster Tweets
13,104,084
%%time def group_mean_log_mae(y_true, y_pred, types, floor=1e-9): maes =(y_true-y_pred ).abs().groupby(types ).mean() return np.log(maes.map(lambda x: max(x, floor)) ).mean() train = pd.read_csv('.. /input/pmp-oof/final_train_oof_pmp.csv') test = pd.read_csv('.. /input/pmp-oof/final_test_oof_pmp.csv') drop_features...
disaster_tweets = train[train['target']==1]['text'] non_disaster_tweets = train[train['target']==0]['text'] freq_dist_disaster_tweets= nltk.FreqDist([word for tweet in disaster_tweets for word in tweet.lower().split() if word not in stopwords.words("english")and len(word)> 2]) freq_dist_non_disaster_tweets= nltk.FreqD...
Natural Language Processing with Disaster Tweets
13,104,084
def get_median_from_files(files): print(len(files)) outs = [pd.read_csv(f, index_col=0)for f in files] concat_sub = pd.concat(outs, axis=1, sort=True) champ_median = concat_sub.median(axis=1 ).values return champ_median test = pd.read_csv(f".. /input/champs-scalar-coupling/test.csv") TARGET = 'scalar_coupling_constan...
MAX_LENGTH = 50 short_tweets = sum(np.array(tweets_length)<= MAX_LENGTH) long_tweets = sum(np.array(tweets_length)> MAX_LENGTH) print("{} reviews with LEN > {}({:.2f} % of total data)".format( long_tweets, MAX_LENGTH, 100 * long_tweets / len(train) ))
Natural Language Processing with Disaster Tweets
13,104,084
%matplotlib inline test['nnet_ens'] = test['nnet_cont'] * 0.6 + test['nnet'] * 0.4 test['lgb_ens'] = test['lgb_a'] * 0.8 + test['lgb_m'] * 0.2 test['final_preds'] =( test['n1']*0.5 + test['n2']*0.1 + test['lgb_ens']*0.15 + test['nnet_ens']*0.1 + test['lb']*0.1 + test['final_mpnn'] * 0.03 + test['mpnn'] *0.02 ) test....
def encode_tweets(tokenizer, tweets, max_len): nb_tweets = len(tweets) tokens = np.ones(( nb_tweets,max_len),dtype='int32') masks = np.zeros(( nb_tweets,max_len),dtype='int32') segs = np.zeros(( nb_tweets,max_len),dtype='int32') for k in range(nb_tweets): tweet = tweets[k] enc = tokenizer.encode(tweet) if len(enc)...
Natural Language Processing with Disaster Tweets
13,104,084
submission = pd.DataFrame() submission['id'] = test.id submission['scalar_coupling_constant'] = test['final_preds'] * 0.1 + test['stack15'] * 0.9 submission.to_csv('ensemble_sub.csv', index=False )<set_options>
train_tokens, train_masks, train_segs = encode_tweets(tokenizer,train["text"].to_list() , MAX_LENGTH) train_labels = train["target"]
Natural Language Processing with Disaster Tweets
13,104,084
print(pd.__version__) SEED = 26 LR = 1e-4<set_options>
es = tf.keras.callbacks.EarlyStopping(monitor='val_loss', mode='min', patience=3, restore_best_weights=True, verbose=1) train_labels = train['target'] train_history = model.fit( [train_tokens,train_masks,train_segs], train_labels, validation_split=0.2, epochs=5, batch_size=16, verbose = 1, callbacks = [es] )
Natural Language Processing with Disaster Tweets
13,104,084
<define_variables><EOS>
test_tokens, test_masks, test_segs = encode_tweets(tokenizer,test["text"].to_list() , MAX_LENGTH) test["target"] = model.predict([test_tokens, test_masks, test_segs] ).round().astype(int) submission = test[["id", "target"]] submission.to_csv("submission.csv",index=False )
Natural Language Processing with Disaster Tweets
12,981,393
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<define_variables>
for dirname, _, filenames in os.walk('/kaggle/working'): for filename in filenames: print(os.path.join(dirname, filename)) print('นำเข้าไลบรารี่ข้อมูลเรียบร้อย' )
Natural Language Processing with Disaster Tweets
12,981,393
types_dict = { "1JHC": 0, "2JHH": 3, "1JHN": 1, "2JHN": 4, "2JHC": 2, "3JHH": 6, "3JHC": 5, "3JHN": 7, } atom_features = [ "atom_2", "atom_3", "atom_4", "atom_5", "atom_6", "atom_7", "atom_8", "atom_9", ] fc_feats = [ "fc_preds_type", "fc_preds_akira", "fc_preds_akira2", "fc_preds_akira3", "fc_preds_akira4", ] types_to...
train = pd.read_csv(".. /input/nlp-getting-started/train.csv") test = pd.read_csv(".. /input/nlp-getting-started/test.csv") sample_submission = pd.read_csv('/kaggle/input/nlp-getting-started/sample_submission.csv') print('นำเข้าชุดข้อมูลเรียบร้อย' )
Natural Language Processing with Disaster Tweets
12,981,393
train_dtypes = { 'molecule_name': 'category', 'atom_index_0': 'int8', 'atom_index_1': 'int8', 'type': 'category', 'scalar_coupling_constant': 'float32' } train_csv = pd.read_csv(f'{DATA_PATH}/train.csv', index_col='id', dtype=train_dtypes) cols = ['molecule_name', 'atom_index_0', 'atom_index_1', 'type'] train_csv = tr...
print(train.isnull().sum() )
Natural Language Processing with Disaster Tweets
12,981,393
test_csv = pd.read_csv(f'{DATA_PATH}/test.csv', index_col='id', dtype=train_dtypes) test_csv['molecule_index'] = test_csv['molecule_name'].str.replace('dsgdb9nsd_', '' ).astype('int32') cols = [col for col in cols if 'scalar_coupling_constant' not in col] test_csv = test_csv[cols] gc.collect() print(train_csv.shape) ...
print(test.isnull().sum() )
Natural Language Processing with Disaster Tweets
12,981,393
train_csv, test_csv = add_contributions(train_csv, test_csv )<drop_column>
print(sample_submission.isnull().sum() )
Natural Language Processing with Disaster Tweets
12,981,393
cols = ["molecule_name", "atom_index_0", "atom_index_1"] train_csv = train_csv.drop(cols, axis=1) test_csv = test_csv.drop(cols, axis=1) train_csv.head()<load_from_csv>
!wget --quiet https://raw.githubusercontent.com/tensorflow/models/master/official/nlp/bert/tokenization.py print('ดาวน์โหลด Algorithm สำเร็จ!!!' )
Natural Language Processing with Disaster Tweets
12,981,393
tr = read_pickle(FILETRAIN) tr = tr.fillna(0) train_ix = train_csv.index tr.index = train_ix train_csv = pd.concat([train_csv, tr], axis=1) train_csv.index = train_ix train_csv = train_csv[[col for col in train_csv.columns if col in list(all_feats)+ TARGETS + ["type"]]] del tr<load_from_csv>
print('นำเข้า "tokenization" เรียบร้อย' )
Natural Language Processing with Disaster Tweets
12,981,393
te = read_pickle(FILETEST) te = te.fillna(0) test_ix = test_csv.index te.index = test_ix test_csv = pd.concat([test_csv, te], axis=1) test_csv.index = test_ix test_csv = test_csv[[col for col in test_csv.columns if col in list(all_feats)+ ["type"]]] del te, test_ix, train_ix gc.collect() print(train_csv.shape) prin...
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)...
Natural Language Processing with Disaster Tweets
12,981,393
tr = read_pickle(FILETRAIN1) tr = tr.fillna(0)[[col for col in tr.columns if col not in train_csv.columns]] train_ix = train_csv.index tr.index = train_ix train_csv = pd.concat([train_csv, tr], axis=1) train_csv.index = train_ix del tr train_csv = train_csv[list(all_feats)+ TARGETS + ["type"]] gc.collect() te = read_...
"Let's learn deep learning!" ['Let', "'", 's', 'learn', 'deep', 'learning', '!'] ['[CLS]', 'Let', "'", 's', 'learn', 'deep', 'learning', '!', '[SEP]'] ['[CLS]', 'Let', "'", 's', 'learn', 'deep', 'learning', '!', '[SEP]', '[PAD]','[PAD]','[PAD]','[PAD]','[PAD]'] [101, 2421, 112, 188, 3858, 1996, 3776, 106, 102, 0, 0, 0,...
Natural Language Processing with Disaster Tweets
12,981,393
gc.collect() print(len(train_csv.columns), len(np.unique(train_csv.columns)) )<set_options>
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, ...
Natural Language Processing with Disaster Tweets
12,981,393
config = tf.ConfigProto(device_count = {'GPU': 1 , 'CPU': 2}) config.gpu_options.allow_growth = True config.gpu_options.per_process_gpu_memory_fraction = 0.6 sess = tf.Session(config=config) K.set_session(sess )<categorify>
%%time print('กำลังดาวน์โหลดโมเดลอาจใช้เวลาสักครู่...') module_url = "https://tfhub.dev/tensorflow/bert_en_uncased_L-24_H-1024_A-16/1" bert_layer = hub.KerasLayer(module_url, trainable=True) print('ดาวน์โหลดโมเดลสำเร็จ!!!' )
Natural Language Processing with Disaster Tweets
12,981,393
cv_score = [] cv_score_total = 0 retrain = True start_time = datetime.now() test_prediction = np.zeros(len(test_csv)) class FeatureTransformer: def transform(self, dataset, ohe_features=[], continuous_features=[]): ohe_df = OneHotEncoder().fit_transform(dataset.loc[:, ohe_features] ).toarray() skews = dataset.loc[:, co...
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 )
Natural Language Processing with Disaster Tweets
12,981,393
submit = pd.read_csv(f'{DATA_PATH}/sample_submission.csv') def submits(predictions): submit["scalar_coupling_constant"] = predictions submit.to_csv("/kaggle/working/nnetCont_sub.csv", index=False) submits(test_prediction )<train_model>
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
Natural Language Processing with Disaster Tweets
12,981,393
print('Total training time: ', datetime.now() - start_time) i=0 for mol_type in types_to_run: print(mol_type,": cv score is ",cv_score[i]) i+=1 print("total cv score is",cv_score_total )<save_to_csv>
start_time = time.time() train_history = model.fit(train_input, train_labels, validation_split = 0.2, epochs = 3, batch_size = 16) print(' สำเร็จ!!! ') print("---ใช้เวลาทั้งหมด %s วินาที ---" %(time.time() - start_time))
Natural Language Processing with Disaster Tweets
12,981,393
submit = pd.read_csv(f'{DATA_PATH}/sample_submission.csv') def submits(predictions): submit["scalar_coupling_constant"] = predictions submit.to_csv(f"/kaggle/working/nnetCont_sub_{round(cv_score_total, 4)}.csv", index=False) submits(test_prediction )<set_options>
test_pred = model.predict(test_input) print(' สำเร็จ!!! ' )
Natural Language Processing with Disaster Tweets
12,981,393
%%capture warnings.filterwarnings('ignore') DATA_DIR = '.. /input/champs-scalar-coupling' ATOMIC_NUMBERS = { 'H': 1, 'C': 6, 'N': 7, 'O': 8, 'F': 9 }<load_from_csv>
sample_submission['target'] = test_pred.round().astype(int) sample_submission.to_csv('sample_submission.csv', index=False) print('สร้างไฟล์ submission.csv เรียบร้อย' )
Natural Language Processing with Disaster Tweets
12,981,393
<merge><EOS>
sample_submission.isnull().sum()
Natural Language Processing with Disaster Tweets
13,037,893
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<load_from_csv>
import numpy as np import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer ,TfidfTransformer
Natural Language Processing with Disaster Tweets
13,037,893
def load_j_coupling_csv(file_path: str, train=True, verbose=False): train_dtypes = { 'molecule_name': 'category', 'atom_index_0': 'int8', 'atom_index_1': 'int8', 'type': 'category', 'scalar_coupling_constant': 'float32' } df = pd.read_csv(file_path, dtype=train_dtypes) df['molecule_index'] = df.molecule_name.str.repla...
nlp = spacy.load("en_core_web_lg" )
Natural Language Processing with Disaster Tweets
13,037,893
def get_knn_features_center(j_coupling: pd.Series, structures=structures_df, mol2dist=mol2distance_matrix, k=10)-> np.array: center = j_coupling[['x_c', 'y_c', 'z_c']].values.reshape(1, 3) mol_df = structures.loc[j_coupling.molecule_index] coordinates = mol_df[['x','y', 'z']].values center_distances = distance_matrix(...
train_data = pd.read_csv('.. /input/nlp-getting-started/train.csv') test_data =pd.read_csv('.. /input/nlp-getting-started/test.csv') train_data.head(5 )
Natural Language Processing with Disaster Tweets
13,037,893
def make_data(df: pd.DataFrame, id2features: dict, random_state=128, split=True): tmp_df = df.copy() tmp_df['features'] = tmp_df.id.map(id2features) X = np.stack(tmp_df.features) y = tmp_df.scalar_coupling_constant.values if split: X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=ra...
train_data_shape = train_data.shape[0]
Natural Language Processing with Disaster Tweets
13,037,893
print(f'competition-metric: {np.mean(list(scores.values())) :.2f}') print('scores per type:') pprint(scores, width=1 )<prepare_x_and_y>
def clean_text(text): url = re.compile(r'https?://\S+|www\.\S+') text = url.sub(r'', text) html = re.compile(r'<.*?>') text = html.sub(r'', text) emoji_pattern = re.compile("[" u"\U0001F600-\U0001F64F" u"\U0001F300-\U0001F5FF" u"\U0001F680-\U0001F6FF" u"\U0001F1E0-\U0001F1FF" u"\U00002702-\U000027B0" u"\U000024C2-\...
Natural Language Processing with Disaster Tweets
13,037,893
def make_test_data(df: pd.DataFrame, id2features: dict, random_state=128): tmp_df = df.copy() tmp_df['features'] = tmp_df.id.map(id2features) X = np.stack(tmp_df.features) return X test_df = load_j_coupling_csv(join(DATA_DIR, 'test.csv'), train=False, verbose=True) id2center_knn_test = {row.id : get_knn_features_cen...
def massage_text(text): tweet = re.sub("[^a-zA-Z]", ' ', text) tweet = tweet.lower() tweet = tweet.split() lem = WordNetLemmatizer() tweet = [lem.lemmatize(word)for word in tweet if word not in set(stopwords.words('english')) ] tweet = ' '.join(tweet) return tweet print('--here goes nothing') print(text) print(twee...
Natural Language Processing with Disaster Tweets
13,037,893
prediction_df = prediction_df.sort_values('id') prediction_df.to_csv('submission.csv', index=False )<load_from_csv>
count_vectorizer = feature_extraction.text.CountVectorizer() train_vectors = count_vectorizer.fit_transform(train_data["text"]) test_vectors = count_vectorizer.transform(test_data["text"]) vectorizer = TfidfVectorizer() Train = vectorizer.fit_transform(train_data['text']) test = vectorizer.transform(test_data['text'...
Natural Language Processing with Disaster Tweets
13,037,893
test = pd.read_csv('.. /input/champs-scalar-coupling/test.csv') sub1 = pd.read_csv('.. /input/keras-neural-net-and-distance-features/submission.csv') sub2 = pd.read_csv('.. /input/keras-nn-with-multi-output/submission.csv') display(test.head() ,sub1.head() ,sub2.head() )<create_dataframe>
clf.fit(Train, train_data["target"] )
Natural Language Processing with Disaster Tweets
13,037,893
sub = pd.DataFrame(columns = ['id','scalar_coupling_constant']) mol_types1 = ['2JHH','2JHN','2JHC','3JHH', '3JHC', '3JHN'] mol_types2 = ['1JHC', '1JHN']<concatenate>
sample_submission = pd.read_csv("/kaggle/input/nlp-getting-started/sample_submission.csv") sample_submission["target"] = clf.predict(test) sample_submission.head()
Natural Language Processing with Disaster Tweets
13,037,893
<sort_values><EOS>
sample_submission.to_csv("submission.csv", index=False )
Natural Language Processing with Disaster Tweets