Kaggle competition: Tweet Sentiment Extraction
def extract_title(name):

 for string in name.split() :
if '.' in string:
return string[:-1]
train_data['Title'] = train_data['Name'].apply(lambda n: extract_title(n))
test_data['Title'] = test_data['Name'].apply(lambda n: extract_title(n))
print(test_data['Title'].value_counts() ,'
',train_data['Title'].value_counts())
<create_dataframe>
print('TF version',tf.__version__ )
for dataframe in [train_data, test_data]:
dataframe['Title'] = dataframe['Title'].replace('Mlle', 'Miss')
 dataframe['Title'] = dataframe['Title'].replace('Ms', 'Miss')
 dataframe['Title'] = dataframe['Title'].replace('Mme', 'Mrs')
 dataframe['Title'] = dataframe['Title'].replace(['Lady', 'Capt', 'Col','Don', 'Dr',
'Major', 'Rev', 'Sir', 'Dona', 'Countess', 'Jonkheer'], 'Other')
 dataframe.drop('Name', axis=1, inplace=True)
<count_values>
train_df = pd.read_csv('.. /input/tweet-sentiment-extraction/train.csv')
 train_df.head()
print('% of survived females:', train_data['Survived'][train_data['Sex'] == 'female'].value_counts(normalize = True)[1]*100)
 print('% of survived males:', train_data['Survived'][train_data['Sex'] == 'male'].value_counts(normalize = True)[1]*100)
<sort_values>
train_df.sentiment.value_counts()
train_data[['Sex', 'Survived']].groupby(['Sex'], as_index=False ).mean().sort_values(by='Survived', ascending=False )<feature_engineering>
def read_train() :
train=pd.read_csv('.. /input/tweet-sentiment-extraction/train.csv')
 train['text'] = train['text'].astype(str)
 train['selected_text'] = train['selected_text'].astype(str)
 return train
def read_test() :
test = pd.read_csv('.. /input/tweet-sentiment-extraction/test.csv')
 test['text'] = test['text'].astype(str)
 return test
def read_submission() :
sub = pd.read_csv('.. /input/tweet-sentiment-extraction/sample_submission.csv')
 return sub
train_data['FamilySize'] = train_data['SibSp'] + train_data['Parch']
test_data['FamilySize'] = train_data['SibSp'] + train_data['Parch']
train_data['IsAlone'] = train_data['FamilySize'].apply(lambda fs: 1 if fs == 0 else 0)
 test_data['IsAlone'] = test_data['FamilySize'].apply(lambda fs: 1 if fs == 0 else 0 )<sort_values>
train_df = read_train()
test_df = read_test()
submission_df = read_submission()
train_data[['FamilySize', 'Survived']].groupby('FamilySize', as_index=False ).mean().sort_values(by='Survived', ascending=False )<drop_column>
MAX_LEN = 96
PATH = '.. /input/tf-roberta/'
tokenizer = tokenizers.ByteLevelBPETokenizer(
 vocab_file=PATH+'vocab-roberta-base.json',
merges_file=PATH+'merges-roberta-base.txt',
lowercase=True,
add_prefix_space=True 
)
 sentiment_id = {'positive': 1313, 'negative': 2430, 'neutral': 7974}
train_data.drop(['Parch', 'SibSp'], axis=1, inplace=True)
 test_data.drop(['Parch', 'SibSp'], axis=1, inplace=True )<sort_values>
ct = train_df.shape[0]
input_ids = np.ones(( ct,MAX_LEN),dtype='int32')
 attention_mask = np.zeros(( ct,MAX_LEN),dtype='int32')
 token_type_ids = np.zeros(( ct,MAX_LEN),dtype='int32')
 start_tokens = np.zeros(( ct,MAX_LEN),dtype='int32')
 end_tokens = np.zeros(( ct,MAX_LEN),dtype='int32' )
train_data[['Ticket', 'PassengerId']].groupby('Ticket', as_index=False ).count().sort_values('PassengerId', ascending=False )<categorify>
import time
train_data['TicketGroupSize'] = train_data.groupby(['Ticket'])['PassengerId'].transform('count')
 test_data['TicketGroupSize'] = test_data.groupby(['Ticket'])['PassengerId'].transform('count' )<drop_column>
%%time
for k in range(train_df.shape[0]):
text1 = " "+" ".join(train_df.loc[k,'text'].split())
 text2 = " ".join(train_df.loc[k,'selected_text'].split())
 idx = text1.find(text2)
 chars = np.zeros(( len(text1)))
 chars[idx:idx+len(text2)]=1
if text1[idx-1]==' ': chars[idx-1] = 1
enc = tokenizer.encode(text1)
 offsets = []; idx=0
for t in enc.ids:
w = tokenizer.decode([t])
 offsets.append(( idx,idx+len(w)))
 idx += len(w)
 toks = []
for i,(a,b)in enumerate(offsets):
sm = np.sum(chars[a:b])
 if sm>0: toks.append(i)
 s_tok = sentiment_id[train_df.loc[k,'sentiment']]
input_ids[k,:len(enc.ids)+5] = [0] + enc.ids + [2,2] + [s_tok] + [2]
attention_mask[k,:len(enc.ids)+5] = 1
if len(toks)>0:
start_tokens[k,toks[0]+1] = 1
end_tokens[k,toks[-1]+1] = 1
train_data.drop('Ticket', axis=1, inplace=True)
 test_data.drop('Ticket', axis=1, inplace=True )<feature_engineering>
ct = test_df.shape[0]
input_ids_t = np.ones(( ct,MAX_LEN),dtype='int32')
 attention_mask_t = np.zeros(( ct,MAX_LEN),dtype='int32')
 token_type_ids_t = np.zeros(( ct,MAX_LEN),dtype='int32')
 for k in range(test_df.shape[0]):
text1 = " "+" ".join(test_df.loc[k,'text'].split())
 enc = tokenizer.encode(text1)
 s_tok = sentiment_id[test_df.loc[k,'sentiment']]
input_ids_t[k,:len(enc.ids)+5] = [0] + enc.ids + [2,2] + [s_tok] + [2]
attention_mask_t[k,:len(enc.ids)+5] = 1
fare_median = test_data['Fare'].median()
test_data['Fare'] = test_data['Fare'].fillna(fare_median )<data_type_conversions>
def build_model() :
ids = tf.keras.layers.Input(( MAX_LEN,), dtype=tf.int32)
 att = tf.keras.layers.Input(( MAX_LEN,), dtype=tf.int32)
 tok = tf.keras.layers.Input(( MAX_LEN,), dtype=tf.int32)
 config = RobertaConfig.from_pretrained(PATH+'config-roberta-base.json')
 bert_model = TFRobertaModel.from_pretrained(PATH+'pretrained-roberta-base.h5',config=config)
 x = bert_model(ids,attention_mask=att,token_type_ids=tok)
 x1 = tf.keras.layers.Dropout(0.1 )(x[0])
 x1 = tf.keras.layers.Conv1D(128, 2,padding='same' )(x1)
 x1 = tf.keras.layers.LeakyReLU()(x1)
 x1 = tf.keras.layers.Conv1D(64, 2,padding='same' )(x1)
 x1 = tf.keras.layers.Dense(1 )(x1)
 x1 = tf.keras.layers.Flatten()(x1)
 x1 = tf.keras.layers.Activation('softmax' )(x1)
 x2 = tf.keras.layers.Dropout(0.1 )(x[0])
 x2 = tf.keras.layers.Conv1D(128, 2, padding='same' )(x2)
 x2 = tf.keras.layers.LeakyReLU()(x2)
 x2 = tf.keras.layers.Conv1D(64, 2, padding='same' )(x2)
 x2 = tf.keras.layers.Dense(1 )(x2)
 x2 = tf.keras.layers.Flatten()(x2)
 x2 = tf.keras.layers.Activation('softmax' )(x2)
 model = tf.keras.models.Model(inputs=[ids, att, tok], outputs=[x1,x2])
 optimizer = tf.keras.optimizers.Adam(learning_rate=3e-5)
 model.compile(loss='binary_crossentropy', optimizer=optimizer)
 return model
train_data['HasCabin'] = train_data['Cabin'].notnull().astype('int')
 test_data['HasCabin'] = test_data['Cabin'].notnull().astype('int' )<drop_column>
def jaccard(str1, str2):
a = set(str1.lower().split())
 b = set(str2.lower().split())
 if(len(a)==0)&(len(b)==0): return 0.5
c = a.intersection(b)
 return float(len(c)) /(len(a)+ len(b)- len(c))
train_data.drop('Cabin', axis=1, inplace=True)
 test_data.drop('Cabin', axis=1, inplace=True )<count_values>
%%time
n_splits = 5
preds_start = np.zeros(( input_ids_t.shape[0],MAX_LEN))
preds_end = np.zeros(( input_ids_t.shape[0],MAX_LEN))
DISPLAY=1
for i in range(5):
print('
print('
print('
K.clear_session()
model = build_model()
model.load_weights('/kaggle/input/model4/v4-roberta-%i.h5'%i)
 print('Predicting Test...')
 preds = model.predict([input_ids_t,attention_mask_t,token_type_ids_t],verbose=DISPLAY)
 preds_start += preds[0]/n_splits
preds_end += preds[1]/n_splits
train_data['Embarked'].value_counts()<concatenate>
all = []
for k in range(input_ids_t.shape[0]):
a = np.argmax(preds_start[k,])
 b = np.argmax(preds_end[k,])
 if a>b:
st = test_df.loc[k,'text']
else:
text1 = " "+" ".join(test_df.loc[k,'text'].split())
 enc = tokenizer.encode(text1)
 st = tokenizer.decode(enc.ids[a-1:b])
 all.append(st )
<groupby><EOS> 
test_df['selected_text'] = all
test_df[['textID','selected_text']].to_csv('submission.csv',index=False )