kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
13,013,100 | <SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<save_to_csv> | nlp = spacy.load("en_core_web_lg" ) | Natural Language Processing with Disaster Tweets |
13,013,100 | sub.to_csv("/kaggle/working/submission.csv", index=False )<set_options> | train_data = pd.read_csv('.. /input/nlp-getting-started/train.csv')
train_data | Natural Language Processing with Disaster Tweets |
13,013,100 | warnings.filterwarnings("ignore")
warnings.filterwarnings(action="ignore",category=DeprecationWarning)
warnings.filterwarnings(action="ignore",category=FutureWarning)
<define_variables> | test_data = pd.read_csv('.. /input/nlp-getting-started/test.csv')
test_data | Natural Language Processing with Disaster Tweets |
13,013,100 | DATA_PATH = '.. /input/champs-scalar-coupling'
SUBMISSIONS_PATH = './'
ATOMIC_NUMBERS = {
'H': 1,
'C': 6,
'N': 7,
'O': 8,
'F': 9
}<load_from_csv> | train_data_shape = train_data.shape[0] | Natural Language Processing with Disaster Tweets |
13,013,100 | 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)
train_csv['molecule_index'] = train_csv.molecule_name.str.replace('dsgdb9nsd_',... | df = pd.concat([train_data, test_data])
df.shape | Natural Language Processing with Disaster Tweets |
13,013,100 | submit = pd.read_csv(f'{DATA_PATH}/sample_submission.csv' )<load_from_csv> | 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,013,100 | 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')
test_csv = test_csv[['molecule_index', 'atom_index_0', 'atom_index_1', 'type']]
test_csv.head(10 )<data_type_conversions> | with nlp.disable_pipes() :
doc_vectors = np.array([nlp(text ).vector for text in df["text"]] ) | Natural Language Processing with Disaster Tweets |
13,013,100 | structures_dtypes = {
'molecule_name': 'category',
'atom_index': 'int8',
'atom': 'category',
'x': 'float32',
'y': 'float32',
'z': 'float32'
}
structures_csv = pd.read_csv(f'{DATA_PATH}/structures.csv', dtype=structures_dtypes)
structures_csv['molecule_index'] = structures_csv.molecule_name.str.replace('dsgdb9nsd_', ''... | Natural Language Processing with Disaster Tweets | |
13,013,100 | def build_type_dataframes(base, structures, coupling_type):
base = base[base['type'] == coupling_type].drop('type', axis=1 ).copy()
base = base.reset_index()
base['id'] = base['id'].astype('int32')
structures = structures[structures['molecule_index'].isin(base['molecule_index'])]
return base, structures<merge> | train_doc_vectors = doc_vectors[:train_data_shape]
submission_doc_vectors = doc_vectors[train_data_shape:] | Natural Language Processing with Disaster Tweets |
13,013,100 | def add_coordinates(base, structures, index):
df = pd.merge(base, structures, how='inner',
left_on=['molecule_index', f'atom_index_{index}'],
right_on=['molecule_index', 'atom_index'] ).drop(['atom_index'], axis=1)
df = df.rename(columns={
'atom': f'atom_{index}',
'x': f'x_{index}',
'y': f'y_{index}',
'z': f'z_{index}... | from sklearn.ensemble import RandomForestClassifier
| Natural Language Processing with Disaster Tweets |
13,013,100 | def add_atoms(base, atoms):
df = pd.merge(base, atoms, how='inner',
on=['molecule_index', 'atom_index_0', 'atom_index_1'])
return df<merge> | X = train_doc_vectors
y = train_data.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.1, random_state = 1 ) | Natural Language Processing with Disaster Tweets |
13,013,100 | def merge_all_atoms(base, structures):
df = pd.merge(base, structures, how='left',
left_on=['molecule_index'],
right_on=['molecule_index'])
df = df[(df.atom_index_0 != df.atom_index)&(df.atom_index_1 != df.atom_index)]
return df<feature_engineering> | model = svm.SVC(kernel='linear' ) | Natural Language Processing with Disaster Tweets |
13,013,100 | def add_center(df):
df['x_c'] =(( df['x_1'] + df['x_0'])* np.float32(0.5))
df['y_c'] =(( df['y_1'] + df['y_0'])* np.float32(0.5))
df['z_c'] =(( df['z_1'] + df['z_0'])* np.float32(0.5))
def add_distance_to_center(df):
df['d_c'] =((
(df['x_c'] - df['x'])**np.float32(2)+
(df['y_c'] - df['y'])**np.float32(2)+
(df['z_c']... | model.fit(X_train, y_train ) | Natural Language Processing with Disaster Tweets |
13,013,100 | def add_distances(df):
n_atoms = 1 + max([int(c.split('_')[1])for c in df.columns if c.startswith('x_')])
for i in range(1, n_atoms):
for vi in range(min(4, i)) :
add_distance_between(df, i, vi )<merge> | model_final =RandomForestClassifier(n_estimators=100)
model_final.fit(X, y)
predictions_final = model_final.predict(submission_doc_vectors ) | Natural Language Processing with Disaster Tweets |
13,013,100 | def add_n_atoms(base, structures):
dfs = structures['molecule_index'].value_counts().rename('n_atoms' ).to_frame()
return pd.merge(base, dfs, left_on='molecule_index', right_index=True )<drop_column> | sample_submission = pd.read_csv("/kaggle/input/nlp-getting-started/sample_submission.csv")
submission = model.predict(submission_doc_vectors)
submission | Natural Language Processing with Disaster Tweets |
13,013,100 | def build_couple_dataframe(some_csv, structures_csv, coupling_type, n_atoms=15):
base, structures = build_type_dataframes(some_csv, structures_csv, coupling_type)
base = add_coordinates(base, structures, 0)
base = add_coordinates(base, structures, 1)
base = base.drop(['atom_0', 'atom_1'], axis=1)
atoms = base.drop(... | submission = pd.DataFrame({'id': test_data.id, 'target' : predictions_final})
submission.head() | Natural Language Processing with Disaster Tweets |
13,013,100 | def take_n_atoms(df, n_atoms, four_start=4):
labels = []
for i in range(2, n_atoms):
label = f'atom_{i}'
labels.append(label)
for i in range(n_atoms):
num = min(i, 4)if i < four_start else 4
for j in range(num):
labels.append(f'd_{i}_{j}')
if 'scalar_coupling_constant' in df:
labels.append('scalar_coupling_constant')... | submission.to_csv('submission1.csv', index=False ) | Natural Language Processing with Disaster Tweets |
10,517,929 | def create_nn_model(input_shape):
inp = Input(shape=(input_shape,))
x = Dense(2048, activation="relu" )(inp)
x = BatchNormalization()(x)
x = Dropout(0.1 )(x)
x = Dense(1024, activation="relu" )(x)
x = BatchNormalization()(x)
x = Dense(512, activation="relu" )(x)
x = BatchNormalization()(x)
out = Dense(1, activat... | !pip install transformers==2.11.0 --quiet
!pip install simpletransformers==0.41.0 --quiet
!pip install pyspellchecker --quiet | Natural Language Processing with Disaster Tweets |
10,517,929 | 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 )<define_variables> | import random
import torch | Natural Language Processing with Disaster Tweets |
10,517,929 | mol_types=train_csv["type"].unique()
cv_score=[]
cv_score_total=0
epoch_n = 2000
verbose = 1
batch_size = 2048
retrain =True
start_time=datetime.now()
test_prediction=np.zeros(len(test_csv))
distance_features = [
'd_1_0', 'd_2_0', 'd_2_1', 'd_3_0',
'd_3_1', 'd_3_2', 'd_4_0', 'd_4_1', 'd_4_2', 'd_4_3', 'd_5_0',
'd_5_1',... | from simpletransformers.classification import ClassificationModel
import pandas as pd | Natural Language Processing with Disaster Tweets |
10,517,929 | print('Total training time: ', datetime.now() - start_time)
i=0
for mol_type in mol_types:
print(mol_type,": cv score is ",cv_score[i])
i+=1
print("total cv score is",cv_score_total )<save_to_csv> | if torch.cuda.is_available() :
device = torch.device("cuda")
print('There are %d GPU(s)available.' % torch.cuda.device_count())
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 |
10,517,929 | def submits(predictions):
submit["scalar_coupling_constant"] = predictions
submit.to_csv("/kaggle/working/submission.csv", index=False)
submits(test_prediction )<set_options> | warnings.simplefilter('ignore')
| Natural Language Processing with Disaster Tweets |
10,517,929 | warnings.filterwarnings("ignore")
warnings.filterwarnings(action="ignore",category=DeprecationWarning)
warnings.filterwarnings(action="ignore",category=FutureWarning)
<define_variables> | def seed_all(seed_value):
random.seed(seed_value)
np.random.seed(seed_value)
torch.manual_seed(seed_value)
if torch.cuda.is_available() :
torch.cuda.manual_seed(seed_value)
torch.cuda.manual_seed_all(seed_value)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
seed_all(79 ) | Natural Language Processing with Disaster Tweets |
10,517,929 | DATA_PATH = '.. /input/champs-scalar-coupling'
SUBMISSIONS_PATH = './'
ATOMIC_NUMBERS = {
'H': 1,
'C': 6,
'N': 7,
'O': 8,
'F': 9
}<load_from_csv> | train = pd.read_csv("/kaggle/input/nlp-getting-started/train.csv")
test = pd.read_csv("/kaggle/input/nlp-getting-started/test.csv")
print("Shape of train data : ",train.shape)
print("Shape of test data : ",test.shape ) | Natural Language Processing with Disaster Tweets |
10,517,929 | 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)
train_csv['molecule_index'] = train_csv.molecule_name.str.replace('dsgdb9nsd_',... | Natural Language Processing with Disaster Tweets | |
10,517,929 | submit = pd.read_csv(f'{DATA_PATH}/sample_submission.csv' )<load_from_csv> | train['keyword'].fillna('', inplace=True)
train['final_text'] = train['keyword'] + ' ' + train['text']
test['keyword'].fillna('', inplace=True)
test['final_text'] = test['keyword'] + ' ' + test['text'] | Natural Language Processing with Disaster Tweets |
10,517,929 | 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')
test_csv = test_csv[['molecule_index', 'atom_index_0', 'atom_index_1', 'type']]
test_csv.head(10 )<data_type_conversions> | train=train.drop(['id'],axis=1)
train=train.drop(['keyword'],axis=1)
train=train.drop(['text'],axis=1)
train=train.drop(['location'],axis=1)
train.head() | Natural Language Processing with Disaster Tweets |
10,517,929 | structures_dtypes = {
'molecule_name': 'category',
'atom_index': 'int8',
'atom': 'category',
'x': 'float32',
'y': 'float32',
'z': 'float32'
}
structures_csv = pd.read_csv(f'{DATA_PATH}/structures.csv', dtype=structures_dtypes)
structures_csv['molecule_index'] = structures_csv.molecule_name.str.replace('dsgdb9nsd_', ''... | final=pd.DataFrame()
final['id']=test['id']
final.head() | Natural Language Processing with Disaster Tweets |
10,517,929 | def build_type_dataframes(base, structures, coupling_type):
base = base[base['type'] == coupling_type].drop('type', axis=1 ).copy()
base = base.reset_index()
base['id'] = base['id'].astype('int32')
structures = structures[structures['molecule_index'].isin(base['molecule_index'])]
return base, structures<merge> | test=test.drop(['id'],axis=1)
test=test.drop(['keyword'],axis=1)
test=test.drop(['text'],axis=1)
test=test.drop(['location'],axis=1)
test['label']=0
test.head() | Natural Language Processing with Disaster Tweets |
10,517,929 | def add_coordinates(base, structures, index):
df = pd.merge(base, structures, how='inner',
left_on=['molecule_index', f'atom_index_{index}'],
right_on=['molecule_index', 'atom_index'] ).drop(['atom_index'], axis=1)
df = df.rename(columns={
'atom': f'atom_{index}',
'x': f'x_{index}',
'y': f'y_{index}',
'z': f'z_{index}... | train['target'].value_counts() | Natural Language Processing with Disaster Tweets |
10,517,929 | def add_atoms(base, atoms):
df = pd.merge(base, atoms, how='inner',
on=['molecule_index', 'atom_index_0', 'atom_index_1'])
return df<merge> | 4313/3245 | Natural Language Processing with Disaster Tweets |
10,517,929 | def merge_all_atoms(base, structures):
df = pd.merge(base, structures, how='left',
left_on=['molecule_index'],
right_on=['molecule_index'])
df = df[(df.atom_index_0 != df.atom_index)&(df.atom_index_1 != df.atom_index)]
return df<feature_engineering> | train = train.reindex(np.random.permutation(train.index))
train= train.reset_index(drop=True)
train.head() | Natural Language Processing with Disaster Tweets |
10,517,929 | def add_center(df):
df['x_c'] =(( df['x_1'] + df['x_0'])* np.float32(0.5))
df['y_c'] =(( df['y_1'] + df['y_0'])* np.float32(0.5))
df['z_c'] =(( df['z_1'] + df['z_0'])* np.float32(0.5))
def add_distance_to_center(df):
df['d_c'] =((
(df['x_c'] - df['x'])**np.float32(2)+
(df['y_c'] - df['y'])**np.float32(2)+
(df['z_c']... | from sklearn.model_selection import KFold, StratifiedKFold
from scipy.special import softmax | Natural Language Processing with Disaster Tweets |
10,517,929 | def add_distances(df):
n_atoms = 1 + max([int(c.split('_')[1])for c in df.columns if c.startswith('x_')])
for i in range(1, n_atoms):
for vi in range(min(4, i)) :
add_distance_between(df, i, vi )<merge> | f1=sklearn.metrics.f1_score | Natural Language Processing with Disaster Tweets |
10,517,929 | def add_n_atoms(base, structures):
dfs = structures['molecule_index'].value_counts().rename('n_atoms' ).to_frame()
return pd.merge(base, dfs, left_on='molecule_index', right_index=True )<drop_column> | model_args = {
"save_eval_checkpoints": False,
"save_model_every_epoch": False,
'reprocess_input_data': True,
'overwrite_output_dir': True,
'manual_seed': 79,
"silent": True,
'num_train_epochs': 2,
'learning_rate': 2e-5,
'fp16': False,
'max_seq_length': 64,
}
| Natural Language Processing with Disaster Tweets |
10,517,929 | def build_couple_dataframe(some_csv, structures_csv, coupling_type, n_atoms=15):
base, structures = build_type_dataframes(some_csv, structures_csv, coupling_type)
base = add_coordinates(base, structures, 0)
base = add_coordinates(base, structures, 1)
base = base.drop(['atom_0', 'atom_1'], axis=1)
atoms = base.drop(... | %%time
torch.cuda.empty_cache()
kf = StratifiedKFold(n_splits=15, shuffle=True, random_state=79)
err=[]
y_pred_tot=[]
for train_index, test_index in kf.split(train, train['target']):
train1_trn, train1_val = train.iloc[train_index], train.iloc[test_index]
model_rb = ClassificationModel('roberta', 'roberta-base', weigh... | Natural Language Processing with Disaster Tweets |
10,517,929 | def take_n_atoms(df, n_atoms, four_start=4):
labels = []
for i in range(2, n_atoms):
label = f'atom_{i}'
labels.append(label)
for i in range(n_atoms):
num = min(i, 4)if i < four_start else 4
for j in range(num):
labels.append(f'd_{i}_{j}')
if 'scalar_coupling_constant' in df:
labels.append('scalar_coupling_constant')... | to_submit =np.mean(y_pred_tot,0 ) | Natural Language Processing with Disaster Tweets |
10,517,929 | def create_nn_model(input_shape):
inp = Input(shape=(input_shape,))
x = Dense(2048, activation="relu" )(inp)
x = BatchNormalization()(x)
x = Dense(1024, activation="relu" )(x)
x = BatchNormalization()(x)
x = Dense(1024, activation="relu" )(x)
x = BatchNormalization()(x)
x = Dense(512, activation="relu" )(x)
x = ... | final['target']=to_submit
final['target'] = final['target'].apply(lambda x: 1 if x>0.5 else 0)
final.head() | Natural Language Processing with Disaster Tweets |
10,517,929 | <define_variables><EOS> | final.to_csv('model_robert_base_lr2e5_ep2_skf15_.csv',index=False ) | Natural Language Processing with Disaster Tweets |
12,854,901 | <SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<train_model> | !wget --quiet https://raw.githubusercontent.com/tensorflow/models/master/official/nlp/bert/tokenization.py | Natural Language Processing with Disaster Tweets |
12,854,901 | print('Total training time: ', datetime.now() - start_time)
i=0
for mol_type in mol_types:
print(mol_type,": cv score is ",cv_score[i])
i+=1
print("total cv score is",cv_score_total )<save_to_csv> | import os
import sys
import logging
import itertools
import re
import pandas as pd
import numpy as np
import sklearn.metrics
import sklearn.preprocessing
import nltk
import tensorflow as tf
import tensorflow_hub as hub
import tokenization
import matplotlib.pyplot as plt
import plotly
import plotly.graph_objects as go
i... | Natural Language Processing with Disaster Tweets |
12,854,901 | def submits(predictions):
submit["scalar_coupling_constant"] = predictions
submit.to_csv("/kaggle/working/submission.csv", index=False)
submits(test_prediction )<set_options> | plotly.offline.init_notebook_mode(connected=True)
pd.options.mode.chained_assignment = None
pd.options.display.max_rows = 500
pd.options.display.max_columns = None
pd.options.display.max_colwidth = 160 | Natural Language Processing with Disaster Tweets |
12,854,901 | %matplotlib inline
<define_variables> | log = logging.getLogger(name=__name__)
log.setLevel(logging.INFO)
logging.captureWarnings(True)
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
stream_handler.setFormatter(formatter)
log.addHan... | Natural Language Processing with Disaster Tweets |
12,854,901 | DATA_PATH = '.. /input'
SUBMISSIONS_PATH = './'
ATOMIC_NUMBERS = {
'H': 1,
'C': 6,
'N': 7,
'O': 8,
'F': 9
}<set_options> | SEED = 1
tf.random.set_seed(SEED)
log.info(f"tensorflow.random seed: {SEED}" ) | Natural Language Processing with Disaster Tweets |
12,854,901 | pd.set_option('display.max_colwidth', -1)
pd.set_option('display.max_rows', 120)
pd.set_option('display.max_columns', 120 )<load_from_csv> | SUCCESS = 0
UNK = "UNK"
NUM = "number"
AT = "recipient"
http = "http"
html = "html"
target = "target"
keyword = "keyword"
old_text = "text"
location = "location"
text = "t"
hashtag = "hashtag"
at = "at"
href = "href"
y_cols = [f"{target}_0", f"{target}_1"] | Natural Language Processing with Disaster Tweets |
12,854,901 | 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)
train_csv['molecule_index'] = train_csv.molecule_name.str.replace('dsgdb9nsd_',... | try:
nltk.download('stopwords')
except:
log.error('...')
try:
stopwords =(nltk.corpus.stopwords.words("english")
+ ["u", "im", "st", "nd", "rd", "th"]
)
except:
log.error('...' ) | Natural Language Processing with Disaster Tweets |
12,854,901 | submission_csv = pd.read_csv(f'{DATA_PATH}/sample_submission.csv', index_col='id' )<load_from_csv> | data_dir = ".. /input/nlp-getting-started"
log.info(f"Data directory: {data_dir}")
train_bn = "train.csv"
test_bn = "test.csv"
train_fn = os.path.join(data_dir, train_bn)
test_fn = os.path.join(data_dir, test_bn)
| Natural Language Processing with Disaster Tweets |
12,854,901 | 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')
test_csv = test_csv[['molecule_index', 'atom_index_0', 'atom_index_1', 'type']]
test_csv.head(10 )<data_type_conversions> | df_train = pd.read_csv(train_fn)
df_test = pd.read_csv(test_fn)
log.info(f"Training data shape: {df_train.shape}")
log.info(f"Test data shape: {df_test.shape}")
train_pts = df_train.shape[0] | Natural Language Processing with Disaster Tweets |
12,854,901 | structures_dtypes = {
'molecule_name': 'category',
'atom_index': 'int8',
'atom': 'category',
'x': 'float32',
'y': 'float32',
'z': 'float32'
}
structures_csv = pd.read_csv(f'{DATA_PATH}/structures.csv', dtype=structures_dtypes)
structures_csv['molecule_index'] = structures_csv.molecule_name.str.replace('dsgdb9nsd_', ''... | def to_lower(df, col=text):
df[col] = df[col].apply(lambda x: x.casefold())
return SUCCESS | Natural Language Processing with Disaster Tweets |
12,854,901 | def build_type_dataframes(base, structures, coupling_type):
base = base[base['type'] == coupling_type].drop('type', axis=1 ).copy()
base = base.reset_index()
base['id'] = base['id'].astype('int32')
structures = structures[structures['molecule_index'].isin(base['molecule_index'])]
return base, structures<merge> | def hash_handling(df, col=text):
reg_hash_full = re.compile("(
reg_hash = re.compile("(
f = lambda x: [y.group() for y in reg_hash_full.finditer(x)]
g = lambda x: ' '.join(x)
df[hashtag] = df[col].apply(f ).apply(g)
df[col] = df[col].apply(lambda x: reg_hash.sub(' ', x))
return SUCCESS | Natural Language Processing with Disaster Tweets |
12,854,901 | def add_coordinates(base, structures, index):
df = pd.merge(base, structures, how='inner',
left_on=['molecule_index', f'atom_index_{index}'],
right_on=['molecule_index', 'atom_index'] ).drop(['atom_index'], axis=1)
df = df.rename(columns={
'atom': f'atom_{index}',
'x': f'x_{index}',
'y': f'y_{index}',
'z': f'z_{index}... | def at_handling(df, col=text, at_col=at):
reg_at = re.compile("(@)")
reg_at_full = re.compile("(@)\w+")
f = lambda x: [y.group() for y in reg_at_full.finditer(x)]
g = lambda x: ' '.join(x)
df[at_col] = df[col].apply(f ).apply(g)
df[col] = df[col].apply(lambda x: reg_at_full.sub(f" {AT} ", x))
return SUCCESS | Natural Language Processing with Disaster Tweets |
12,854,901 | def add_atoms(base, atoms):
df = pd.merge(base, atoms, how='inner',
on=['molecule_index', 'atom_index_0', 'atom_index_1'])
return df<merge> | def href_handling(df, col=text, new_col=href):
reg_href_full = re.compile("(htt)\S+")
f = lambda x: len(list(reg_href_full.finditer(x)))
df[new_col] = df[col].apply(f)
df[col] = df[col].apply(lambda x: reg_href_full.sub(f' {http} ', x))
return SUCCESS | Natural Language Processing with Disaster Tweets |
12,854,901 | def merge_all_atoms(base, structures):
df = pd.merge(base, structures, how='left',
left_on=['molecule_index'],
right_on=['molecule_index'])
df = df[(df.atom_index_0 != df.atom_index)&(df.atom_index_1 != df.atom_index)]
return df<feature_engineering> | def html_special_handling(df, col=text):
reg_html = re.compile("(&)\w+(;)")
df[col] = df[col].apply(lambda x: reg_html.sub(f' {html} ', x))
return SUCCESS | Natural Language Processing with Disaster Tweets |
12,854,901 | def add_center(df):
df['x_c'] =(( df['x_1'] + df['x_0'])* np.float32(0.5))
df['y_c'] =(( df['y_1'] + df['y_0'])* np.float32(0.5))
df['z_c'] =(( df['z_1'] + df['z_0'])* np.float32(0.5))
def add_distance_to_center(df):
df['d_c'] =((
(df['x_c'] - df['x'])**np.float32(2)+
(df['y_c'] - df['y'])**np.float32(2)+
(df['z_c']... | def xc2x89_byte_handling(df, col=text):
reg_x89 = re.compile(b"\xc2\x89".decode('utf-8')+"\S+")
df[col] = df[col].apply(lambda x: reg_x89.sub(' ', x))
return SUCCESS | Natural Language Processing with Disaster Tweets |
12,854,901 | def add_distances(df):
n_atoms = 1 + max([int(c.split('_')[1])for c in df.columns if c.startswith('x_')])
for i in range(1, n_atoms):
for vi in range(min(4, i)) :
add_distance_between(df, i, vi )<merge> | def special_char_handling(df, col=text):
reg_special = re.compile("[^\w\s]")
df[col] = df[col].apply(lambda x: reg_special.sub(' ', x))
df[col] = df[col].apply(lambda x: re.sub('_', ' ', x))
return SUCCESS | Natural Language Processing with Disaster Tweets |
12,854,901 | def add_n_atoms(base, structures):
dfs = structures['molecule_index'].value_counts().rename('n_atoms' ).to_frame()
return pd.merge(base, dfs, left_on='molecule_index', right_index=True )<drop_column> | def contraction_handling(df, col=text):
reg_contract = re.compile("\s(s|m|t|(nt)|(ve)|w)\s")
df[col] = df[col].apply(lambda x: reg_contract.sub(' ', x))
return SUCCESS | Natural Language Processing with Disaster Tweets |
12,854,901 | def build_couple_dataframe(some_csv, structures_csv, coupling_type, n_atoms=10):
base, structures = build_type_dataframes(some_csv, structures_csv, coupling_type)
base = add_coordinates(base, structures, 0)
base = add_coordinates(base, structures, 1)
base = base.drop(['atom_0', 'atom_1'], axis=1)
atoms = base.drop(... | def encode_numerals(df, col=text):
reg_numerals = re.compile("\d+[\s\d]*")
df[col] = df[col].apply(lambda x: reg_numerals.sub(f' {NUM} ', x))
return SUCCESS | Natural Language Processing with Disaster Tweets |
12,854,901 | def take_n_atoms(df, n_atoms, four_start=4):
labels = []
for i in range(2, n_atoms):
label = f'atom_{i}'
labels.append(label)
for i in range(n_atoms):
num = min(i, 4)if i < four_start else 4
for j in range(num):
labels.append(f'd_{i}_{j}')
if 'scalar_coupling_constant' in df:
labels.append('scalar_coupling_constant')... | def remove_stopwords(df, col=text, to_remove=stopwords):
f =(lambda x:
' '.join([y for y in x.strip().split() if y not in to_remove])
)
df[col] = df[col].apply(f)
return SUCCESS | Natural Language Processing with Disaster Tweets |
12,854,901 | %%time
def type_select(types = '1JHN'):
full = build_couple_dataframe(train_csv, structures_csv, types, n_atoms=10)
print(full.shape)
df = take_n_atoms(full, 7)
df = df.fillna(0)
X_data = df.drop(['scalar_coupling_constant'], axis=1 ).values.astype('float32')
y_data = df['scalar_coupling_constant'].values.astype('... | def preprocess(df, col=text, old_col=old_text):
df[col] = df[old_col]
to_lower(df)
hash_handling(df)
at_handling(df)
href_handling(df)
html_special_handling(df)
xc2x89_byte_handling(df)
special_char_handling(df)
contraction_handling(df)
remove_stopwords(df)
encode_numerals(df)
return SUCCESS | Natural Language Processing with Disaster Tweets |
12,854,901 | model_params = {
'1JHN': 7,
'1JHC': 10,
'2JHH': 9,
'2JHN': 9,
'2JHC': 9,
'3JHH': 9,
'3JHC': 10,
'3JHN': 10
}
model_params.keys()<prepare_x_and_y> | log.info(f"Training set preprocessing status: {preprocess(df_train)}.")
log.info(f"Test set preprocessing status: {preprocess(df_test)}." ) | Natural Language Processing with Disaster Tweets |
12,854,901 | X_train, X_val, y_train, y_val = type_select(types = '3JHN' )<init_hyperparams> | ave_words_positive =(
df_train.loc[df_train[target]==1, text].apply(lambda x: len(x.split()))
.sum()
/ df_train.loc[df_train[target]==1, text].count()
)
ave_words_negative =(
df_train.loc[df_train[target]==0, text].apply(lambda x: len(x.split()))
.sum()
/ df_train.loc[df_train[target]==0, text].count()
)
log.in... | Natural Language Processing with Disaster Tweets |
12,854,901 | %%time
LGB_PARAMS = {
'objective': 'regression',
'metric': 'mae',
'verbosity': -1,
'boosting_type': 'gbdt',
'learning_rate': 0.1455,
'num_leaves': 129,
'min_child_samples': 78,
'max_depth': 13,
'subsample_freq': 1,
'subsample': 0.88,
'bagging_seed': 15,
'reg_alpha': 0.10107001,
'reg_lambda': 0.300132,
'colsample_bytree... | tokenize_flatten = lambda series:(
list(itertools.chain(*[x.split() for x in series]))
)
wc_size =(14, 14)
tdf = df_train[df_train[target]==1]
unique_words, word_counts =(
np.unique(tokenize_flatten(tdf[text]), return_counts=True)
)
sm = np.sum(word_counts)
frequency_dict = {
x: word_counts[i]/sm
for i, x in np.... | Natural Language Processing with Disaster Tweets |
12,854,901 | categorical_feature=[0,1,2,3,4]<init_hyperparams> | def bigrams_count(df, col, top_n=10):
words = [x.split() for x in df[col]]
bigrams = [x[i]+"_"+x[i+1] for x in words for i in range(len(x)-1)]
uniq_pairs, counts = np.unique(np.array(bigrams), return_counts=True)
return np.array([uniq_pairs, counts] ) | Natural Language Processing with Disaster Tweets |
12,854,901 | LGB_PARAMS_3JHN={'bagging_seed': 14, 'colsample_bytree': 1.0, 'learning_rate': 0.14548931924611134, 'max_depth': 14, 'min_child_samples': 80, 'num_leaves': 129, 'random_state': 42, 'reg_alpha': 0.1, 'reg_lambda': 0.3, 'subsample': 0.89, 'subsample_freq': 1, 'verbosity': -1}<categorify> | df_bi_0 = pd.DataFrame(
bigrams_count(df_train[df_train[target]==0], text ).T,
columns=["bigram", "count"]
)
df_bi_1 = pd.DataFrame(
bigrams_count(df_test[df_train[target]==0], text ).T,
columns=["bigram", "count"]
)
df_bi = df_bi_0.merge(df_bi_1, how="outer", left_on="bigram",
suffixes=("_0", "_1"), right_on="bi... | Natural Language Processing with Disaster Tweets |
12,854,901 |
<prepare_x_and_y> | top_n = 100
top_bigrams = df_bi.nlargest(top_n, "total" ) | Natural Language Processing with Disaster Tweets |
12,854,901 | def build_x_y_data(some_csv, coupling_type, n_atoms):
full = build_couple_dataframe(some_csv, structures_csv, coupling_type, n_atoms=n_atoms)
df = take_n_atoms(full, n_atoms)
df = df.fillna(0)
print(df.columns)
if 'scalar_coupling_constant' in df:
X_data = df.drop(['scalar_coupling_constant'], axis=1 ).values.astyp... | def tokenize_dataframe(df, col, max_len=20):
df_tmp = pd.DataFrame(
df[col].apply(lambda x: reversed(x.split())).tolist()
)
orig_len = len(df_tmp.columns)
df_tmp = df_tmp.rename(
lambda x: f'{col}_{max_len-1-x:02d}',
axis=1
)
enum_cols = [f'{col}_{i:02d}' for i in range(max_len)]
if orig_len < max_len:
compl_c... | Natural Language Processing with Disaster Tweets |
12,854,901 | def train_and_predict_for_one_coupling_type(coupling_type, submission, n_atoms, n_folds=4, n_splits=4, random_state=128):
print(f'*** Training Model for {coupling_type} ***')
X_data, y_data = build_x_y_data(train_csv, coupling_type, n_atoms)
X_test, _ = build_x_y_data(test_csv, coupling_type, n_atoms)
y_pred = np.ze... | def transform_data(df, col=text):
word_cols = tokenize_dataframe(df, col, max_len=25)
df[word_cols] = df[word_cols].fillna('')
lemmatizer = nltk.stem.WordNetLemmatizer()
ps = nltk.stem.PorterStemmer()
df[word_cols] = df[word_cols].applymap(lambda x: ps.stem(x))
df[word_cols] = df[word_cols].applymap(lambda x: lemma... | Natural Language Processing with Disaster Tweets |
12,854,901 | model_params = {
'1JHN': 7,
'1JHC': 10,
'2JHH': 9,
'2JHN': 9,
'2JHC': 9,
'3JHH': 9,
'3JHC': 10,
'3JHN': 10
}
cat_code = {'1JHN': 5,'1JHC': 7,'2JHH': 7,
'2JHN': 7,'2JHC': 7,'3JHH': 7,
'3JHC': 8,'3JHN': 7}
categorical_feature = [0,1,2,3,4,5,6]
LGB_PARAMS_2JHC={'bagging_seed': 14, 'colsample_bytree': 1.0, 'learning_rate':... | def bert_tokenize(df, col):
gs_folder_bert = "gs://cloud-tpu-checkpoints/bert/keras_bert/uncased_L-12_H-768_A-12"
tf.io.gfile.listdir(gs_folder_bert)
tokenizer = tokenization.FullTokenizer(
vocab_file=os.path.join(gs_folder_bert, "vocab.txt"),
do_lower_case=True
)
bert_token =(lambda x: tokenizer
.convert_tokens... | Natural Language Processing with Disaster Tweets |
12,854,901 | submission.to_csv(f'{SUBMISSIONS_PATH}/submission.csv' )<define_variables> | def tf_tokenizer(df, col, num_words):
tokenizer =(
tf.keras.preprocessing.text.Tokenizer(num_words=num_words)
)
tokenizer.fit_on_texts(df[col].values)
word_ar = tf.keras.preprocessing.sequence.pad_sequences(
tokenizer.texts_to_sequences(df[col].values)
)
word_cols = [f"text_{i:02d}" for i in range(word_ar.shape[... | Natural Language Processing with Disaster Tweets |
12,854,901 | DATA_PATH = '.. /input'
SUBMISSIONS_PATH = './'
ATOMIC_NUMBERS = {
'H': 1,
'C': 6,
'N': 7,
'O': 8,
'F': 9
}<set_options> | df_full = pd.concat([df_train, df_test], ignore_index=True)
tokenizer, num_unique_words, word_cols, mask_cols, type_cols = bert_tokenize(df_full, text)
log.info(f"Vocab size: {num_unique_words}" ) | Natural Language Processing with Disaster Tweets |
12,854,901 | %matplotlib inline
<set_options> | hub_url_bert = "https://tfhub.dev/tensorflow/bert_en_uncased_L-12_H-768_A-12/2"
bert_layer = hub.KerasLayer(hub_url_bert, trainable=True ) | Natural Language Processing with Disaster Tweets |
12,854,901 | pd.set_option('display.max_colwidth', -1)
pd.set_option('display.max_rows', 120)
pd.set_option('display.max_columns', 120 )<load_from_csv> | class TwolayerModel(tf.keras.Model):
def __init__(self,
batch_size=32,
units=40,
embed_dim=100,
sequence_length=len(word_cols),
):
super(TwolayerModel, self ).__init__()
self.inps =(None, sequence_length)
self.bs = batch_size
out_dim = 2
self._embed1 = tf.keras.layers.Embedding(
num_unique_words,
embed_dim,
inpu... | Natural Language Processing with Disaster Tweets |
12,854,901 | 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)
train_csv['molecule_index'] = train_csv.molecule_name.str.replace('dsgdb9nsd_',... | class OnelayerModel(tf.keras.Model):
def __init__(self,
batch_size=32,
units=40,
embed_dim=100,
sequence_length=len(word_cols),
):
super(OnelayerModel, self ).__init__()
self.inps = [
(None, sequence_length),
(None, sequence_length),
(None, sequence_length),
]
self.bs = batch_size
out_dim = 2
self._embed1 = tf.... | Natural Language Processing with Disaster Tweets |
12,854,901 | submission_csv = pd.read_csv(f'{DATA_PATH}/sample_submission.csv', index_col='id' )<load_from_csv> | class ConvModel(tf.keras.Model):
def __init__(self,
batch_size=32,
units=40,
embed_dim=100,
sequence_length=len(word_cols),
):
self.inps =(None, sequence_length)
self.bs = batch_size
out_dim = 2
super(ConvModel, self ).__init__()
self._embed1 = tf.keras.layers.Embedding(
num_unique_words,
embed_dim,
input_length... | Natural Language Processing with Disaster Tweets |
12,854,901 | 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')
test_csv = test_csv[['molecule_index', 'atom_index_0', 'atom_index_1', 'type']]
test_csv.head(10 )<data_type_conversions> | class BERTModel(tf.keras.Model):
def __init__(self,
batch_size=64,
units=40,
embed_dim=100,
sequence_length=len(word_cols),
):
super(BERTModel, self ).__init__()
self.inps = [
(None, sequence_length),
(None, sequence_length),
(None, sequence_length),
]
self.bs = batch_size
out_dim = 2
self.max_seq_length = sequ... | Natural Language Processing with Disaster Tweets |
12,854,901 | structures_dtypes = {
'molecule_name': 'category',
'atom_index': 'int8',
'atom': 'category',
'x': 'float32',
'y': 'float32',
'z': 'float32'
}
structures_csv = pd.read_csv(f'{DATA_PATH}/structures.csv', dtype=structures_dtypes)
structures_csv['molecule_index'] = structures_csv.molecule_name.str.replace('dsgdb9nsd_', ''... | tfboard_dir = "logs"
if not os.path.exists(tfboard_dir):
os.mkdir(tfboard_dir)
tensorboard_callback = tf.keras.callbacks.TensorBoard(
log_dir=tfboard_dir,
histogram_freq=1,
write_graph=True,
write_images=True,
)
early_stopping = tf.keras.callbacks.EarlyStopping(
monitor="val_binary_accuracy",
min_delta=1e-5,
patie... | Natural Language Processing with Disaster Tweets |
12,854,901 | def build_type_dataframes(base, structures, coupling_type):
base = base[base['type'] == coupling_type].drop('type', axis=1 ).copy()
base = base.reset_index()
base['id'] = base['id'].astype('int32')
structures = structures[structures['molecule_index'].isin(base['molecule_index'])]
return base, structures<merge> | model = BERTModel(batch_size=32)
df_test = df_full.iloc[train_pts:]
df_train = df_full.iloc[:train_pts]
log.info(f"Dataset size: {df_train.shape[0]}")
remainder = df_train.shape[0] % model.bs
pad_size = model.bs - remainder if remainder !=0 else 0
log.info(f"Remainder from batch size: {remainder}
"
f"Padding {pad_siz... | Natural Language Processing with Disaster Tweets |
12,854,901 | def add_coordinates(base, structures, index):
df = pd.merge(base, structures, how='inner',
left_on=['molecule_index', f'atom_index_{index}'],
right_on=['molecule_index', 'atom_index'] ).drop(['atom_index'], axis=1)
df = df.rename(columns={
'atom': f'atom_{index}',
'x': f'x_{index}',
'y': f'y_{index}',
'z': f'z_{index}... | hist = model.fit(
X_train,
epochs=8,
validation_data=X_valid,
callbacks=[
early_stopping,
],
) | Natural Language Processing with Disaster Tweets |
12,854,901 | def add_atoms(base, atoms):
df = pd.merge(base, atoms, how='inner',
on=['molecule_index', 'atom_index_0', 'atom_index_1'])
return df<merge> | Y_train_pred = model.predict(X_unpad)
Y_test_pred = model.predict(X_test ) | Natural Language Processing with Disaster Tweets |
12,854,901 | def merge_all_atoms(base, structures):
df = pd.merge(base, structures, how='left',
left_on=['molecule_index'],
right_on=['molecule_index'])
df = df[(df.atom_index_0 != df.atom_index)&(df.atom_index_1 != df.atom_index)]
return df<feature_engineering> | df_train_pred = pd.DataFrame(Y_train_pred, columns=y_cols)
df_train_pred = df_train_pred.apply(np.round ).astype({x: int for x in y_cols})
df_train_pred[target] = df_train_pred["target_1"]
df_train_pred.drop(y_cols, inplace=True, axis=1)
df_train_pred["id"] = df_train["id"].values
df_train_pred = df_train_pred[["id"... | Natural Language Processing with Disaster Tweets |
12,854,901 | def add_center(df):
df['x_c'] =(( df['x_1'] + df['x_0'])* np.float32(0.5))
df['y_c'] =(( df['y_1'] + df['y_0'])* np.float32(0.5))
df['z_c'] =(( df['z_1'] + df['z_0'])* np.float32(0.5))
def add_distance_to_center(df):
df['d_c'] =((
(df['x_c'] - df['x'])**np.float32(2)+
(df['y_c'] - df['y'])**np.float32(2)+
(df['z_c']... | df_test_pred = pd.DataFrame(Y_test_pred, columns=y_cols)
df_test_pred = df_test_pred.apply(np.round ).astype({x: int for x in y_cols})
df_test_pred[target] = df_test_pred["target_1"]
df_test_pred.drop(y_cols, inplace=True, axis=1)
df_test_pred.drop(list(df_test_pred.index[df_train.shape[0]:]), inplace=True, axis=0)
... | Natural Language Processing with Disaster Tweets |
12,854,901 | def add_n_atoms(base, structures):
dfs = structures['molecule_index'].value_counts().rename('n_atoms' ).to_frame()
return pd.merge(base, dfs, left_on='molecule_index', right_index=True )<define_variables> | log.info("
" +
sklearn.metrics.classification_report(
df_train[target],
df_train_pred[target],
target_names=["Not disaster", "Disaster"]
)
) | Natural Language Processing with Disaster Tweets |
12,854,901 | def take_n_atoms(df, n_atoms, four_start=4):
labels = []
for i in range(2, n_atoms):
label = f'atom_{i}'
labels.append(label)
for i in range(n_atoms):
num = min(i, 4)if i < four_start else 4
for j in range(num):
labels.append(f'd_{i}_{j}')
if 'scalar_coupling_constant' in df:
labels.append('scalar_coupling_constant')... | log.info("Training accuracy score {}.".format(
sklearn.metrics.accuracy_score(df_train[target], df_train_pred[target])
)
) | Natural Language Processing with Disaster Tweets |
12,854,901 | <train_model><EOS> | output_dir = "./"
results_bn = "results.csv"
results_fn = os.path.join(output_dir, results_bn)
df_test_pred.to_csv(results_fn, index=False ) | Natural Language Processing with Disaster Tweets |
12,513,336 | <SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<prepare_x_and_y> | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import re
import spacy
import nltk
import pickle
from nltk.tokenize import RegexpTokenizer
from scipy import sparse
from sklearn.naive_bayes import BernoulliNB
from sklearn.linear_model import LogisticRegressionCV
from sklearn.svm import SVC
from sk... | Natural Language Processing with Disaster Tweets |
12,513,336 | X_train, X_val, y_train, y_val = type_select(types = '3JHN')
<define_search_space> | train = pd.read_csv(r'.. /input/nlp-getting-started/train.csv')
test = pd.read_csv(r'.. /input/nlp-getting-started/test.csv')
train.head() | Natural Language Processing with Disaster Tweets |
12,513,336 | model_parameters = {'n_estimators': [50, 100, 150, 200, 250, 300],
'max_depth':[5,7,9,11], 'learning_rate': [0.07, 0.1, 0.15],
'gamma': [0, 0.0001, 0.001, 0.01],
'subsample': [0.5, 0.8, 1], 'colsample_bytree': [0.5, 0.66, 1]
}
fit_params = {'eval_metric': 'mae',
'early_stopping_rounds': 5,
'eval_set': [(X_val, y_val)]}... | plt.bar(train['target'].value_counts().index, train['target'].value_counts().values ) | Natural Language Processing with Disaster Tweets |
12,513,336 | best_parameters = {'base_score': 0.5,
'booster': 'gbtree',
'colsample_bylevel': 1,
'colsample_bynode': 1,
'colsample_bytree': 1,
'gamma': 0,
'importance_type': 'gain',
'learning_rate': 0.15,
'max_delta_step': 0,
'max_depth': 11,
'min_child_weight': 1,
'missing': None,
'n_estimators': 300,
'n_jobs': 4,
'nthread': None,
... | train['location'].value_counts(dropna=False ) | Natural Language Processing with Disaster Tweets |
12,513,336 |
<prepare_x_and_y> | train_for_plot = train.fillna('NOINFO')
locations = train_for_plot['location'].value_counts(dropna=False)
freq_locations = list(locations.index ) | Natural Language Processing with Disaster Tweets |
12,513,336 | def build_x_y_data(some_csv, coupling_type, n_atoms):
full = build_couple_dataframe(some_csv, structures_csv, coupling_type, n_atoms=n_atoms)
df = take_n_atoms(full, n_atoms)
df = df.fillna(0)
print(df.columns)
if 'scalar_coupling_constant' in df:
X_data = df.drop(['scalar_coupling_constant'], axis=1 ).values.astyp... | frames = [train, test]
full_data = pd.concat(frames ) | Natural Language Processing with Disaster Tweets |
12,513,336 | def train_and_predict_for_one_coupling_type(coupling_type, submission, n_atoms, random_state=128):
print(f'*** Training Model for {coupling_type} ***')
X_data, y_data = build_x_y_data(train_csv, coupling_type, n_atoms)
X_test, _ = build_x_y_data(test_csv, coupling_type, n_atoms)
y_pred = np.zeros(X_test.shape[0], dt... | locs = full_data['location'].value_counts(dropna=True ) | Natural Language Processing with Disaster Tweets |
12,513,336 | submission = submission_csv.copy()
for coupling_type in model_params.keys() :
cv_score = train_and_predict_for_one_coupling_type(
coupling_type, submission, n_atoms=model_params[coupling_type] )<save_to_csv> | locations_nan = locs[locs > 8]
print(locations_nan.index ) | Natural Language Processing with Disaster Tweets |
12,513,336 | submission.to_csv(f'{SUBMISSIONS_PATH}/submission.csv' )<import_modules> | def change_location(dataset, name='dataset'):
dataset['location'] = dataset['location'].replace('United States', 'USA')
dataset['location'] = dataset['location'].replace('US', 'USA')
dataset['location'] = dataset['location'].replace('Worldwide', 'Anywhere')
dataset['location'] = dataset['location'].replace('worldwid... | Natural Language Processing with Disaster Tweets |
12,513,336 |
print(tf.__version__)
for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
print(os.path.join(dirname, filename))
<load_from_csv> | keywords = train_for_plot['keyword'].value_counts(dropna=False)
keywords | Natural Language Processing with Disaster Tweets |
12,513,336 | train =pd.read_csv(os.path.join(dirname,'train.csv'))
test =pd.read_csv(os.path.join(dirname,'test.csv'))
sample_submission =pd.read_csv(os.path.join(dirname,'sample_submission.csv'))<prepare_x_and_y> | train['target'].value_counts() [1] / train['target'].value_counts() [0] | Natural Language Processing with Disaster Tweets |
12,513,336 | X_train=train.drop('label',axis=1)
Y_train=train.label
X_test = test.drop('id', axis = 1)
<feature_engineering> | np.random.seed(144)
train.fillna('noinfo', inplace=True)
test.fillna('noinfo', inplace=True)
shuffled_train = train.iloc[np.random.permutation(len(train)) ]
max_iter = 100
cv = 5
clf = LogisticRegressionCV(cv = cv, n_jobs = -1, max_iter = max_iter, scoring='f1')
X = shuffled_train[['location', 'keyword']]
Y = shuff... | Natural Language Processing with Disaster Tweets |
12,513,336 | X_train = X_train / 255.0
X_test = X_test / 255.0<categorify> | np.random.seed(144)
shuffled_train = train.iloc[np.random.permutation(len(train)) ]
clf = BernoulliNB(fit_prior = False)
X = shuffled_train[['location', 'keyword']]
Y = shuffled_train['target']
enc = OneHotEncoder()
X = enc.fit_transform(X)
score = cross_val_score(estimator=clf, X=X, y=Y, scoring='f1')
print('Best ... | Natural Language Processing with Disaster Tweets |
12,513,336 | Y_train = to_categorical(Y_train,num_classes=10)
display(Y_train )<split> | train['text'] = train['text'].str.lower()
test['text'] = test['text'].str.lower() | Natural Language Processing with Disaster Tweets |
12,513,336 | X_train,X_val,y_train,y_val=train_test_split(X_train,Y_train,random_state=42,test_size=0.10)
<choose_model_class> | train['text'] = train['text'].apply(lambda x:
re.sub(r'https?://\S+|www\.\S+','', x))
test['text'] = test['text'].apply(lambda x:
re.sub(r'https?://\S+|www\.\S+','', x)) | Natural Language Processing with Disaster Tweets |
12,513,336 | kernel_size_3 =(3,3)
kernel_size_5 =(5,5)
filters_32 = 32
filters_64 = 64
filters_128 = 128
filters_256 = 256
model = Sequential()
model.add(Conv2D(filters_64, kernel_size_3, activation='relu', input_shape=(28,28,1),padding='same'))
model.add(BatchNormalization(momentum=0.9, epsilon=1e-5, gamma_initializer="uniform")... | train['text'] = train['text'].apply(lambda x:
re.sub(r'@[A-Za-z0-9]+','', x))
test['text'] = test['text'].apply(lambda x:
re.sub(r'@[A-Za-z0-9]+','', x))
train['text'] = train['text'].apply(lambda x:
re.sub(r'
test['text'] = test['text'].apply(lambda x:
re.sub(r' | Natural Language Processing with Disaster Tweets |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.