Kaggle competition: Tweet Sentiment Extraction
<SOS> metric: Jaccard Kaggle data source: tweet-sentiment-extraction<load_from_csv>
import numpy as np
import pandas as pd
import os
import tokenizers
import string
import torch
import transformers
import torch.nn as nn
from torch.nn import functional as F
from tqdm import tqdm
import re
train=pd.read_csv("/kaggle/input/house-prices-advanced-regression-techniques/train.csv")
 test=pd.read_csv("/kaggle/input/house-prices-advanced-regression-techniques/test.csv" )<categorify>
MAX_LEN = 92
TRAIN_BATCH_SIZE = 32
VALID_BATCH_SIZE = 8
EPOCHS = 5
ROBERTA_PATH = ".. /input/roberta-base"
TOKENIZER = tokenizers.ByteLevelBPETokenizer(
 vocab_file=f"{ROBERTA_PATH}/vocab.json",
merges_file=f"{ROBERTA_PATH}/merges.txt",
lowercase=True,
add_prefix_space=True
)
def encode_FE(df1, df2, cols):
for col in cols:
df = pd.concat([df1[col],df2[col]])
 vc = df.value_counts(dropna=True, normalize=True ).to_dict()
vc[-1] = -1
nm = col+'_FE'
df1[nm] = df1[col].map(vc)
 df1[nm] = df1[nm].astype('float32')
 df2[nm] = df2[col].map(vc)
 df2[nm] = df2[nm].astype('float32')
 print(nm,', ',end='')
 def encode_LE(col,train,test,verbose=False):
df_comb = pd.concat([train[col],test[col]],axis=0)
 df_comb,_ = df_comb.factorize(sort=True)
 nm = col
if df_comb.max() >32000:
train[nm] = df_comb[:len(train)].astype('int32')
 test[nm] = df_comb[len(train):].astype('int32')
 else:
train[nm] = df_comb[:len(train)].astype('int16')
 test[nm] = df_comb[len(train):].astype('int16')
 del df_comb; x=gc.collect()
if verbose: print(nm,', ',end='')
 def encode_AG(main_columns, uids, aggregations, train_df, test_df,
fillna=True, usena=False):
for main_column in main_columns:
for col in uids:
for agg_type in aggregations:
new_col_name = main_column+'_'+col+'_'+agg_type
temp_df = pd.concat([train_df[[col, main_column]], test_df[[col,main_column]]])
 if usena: temp_df.loc[temp_df[main_column]==-1,main_column] = np.nan
temp_df = temp_df.groupby([col])[main_column].agg([agg_type] ).reset_index().rename(
 columns={agg_type: new_col_name})
 temp_df.index = list(temp_df[col])
 temp_df = temp_df[new_col_name].to_dict()
train_df[new_col_name] = train_df[col].map(temp_df ).astype('float32')
 test_df[new_col_name] = test_df[col].map(temp_df ).astype('float32')
 if fillna:
train_df[new_col_name].fillna(-1,inplace=True)
 test_df[new_col_name].fillna(-1,inplace=True)
 print("'"+new_col_name+"'",', ',end='')
 def encode_CB(col1,col2,train,test):
nm = str(col1)+'_'+str(col2)
 train[nm] = train[col1].astype(str)+'_'+train[col2].astype(str)
 test[nm] = test[col1].astype(str)+'_'+test[col2].astype(str)
 print("'"+nm+"'",', ',end='')
 encode_LE(nm,train,test)
 def encode_AG2(main_columns, uids, train_df, test_df):
for main_column in main_columns:
for col in uids:
comb = pd.concat([train_df[[col]+[main_column]],test_df[[col]+[main_column]]],axis=0)
 mp = comb.groupby(col)[main_column].agg(['nunique'])['nunique'].to_dict()
train_df[col+'_'+main_column+'_ct'] = train_df[col].map(mp ).astype('float32')
 test_df[col+'_'+main_column+'_ct'] = test_df[col].map(mp ).astype('float32')
 print(col+'_'+main_column+'_ct, ',end='' )<drop_column>
class TweetModel(transformers.BertPreTrainedModel):
def __init__(self, conf):
super(TweetModel, self ).__init__(conf)
 self.roberta = transformers.RobertaModel.from_pretrained(ROBERTA_PATH, config=conf)
 self.drop_out = nn.Dropout(0.1)
 self.l0 = nn.Linear(768 * 2, 2)
 torch.nn.init.normal_(self.l0.weight, std=0.02)
 def forward(self, ids, mask, token_type_ids):
_, _, out = self.roberta(
 ids,
attention_mask=mask,
token_type_ids=token_type_ids 
)
 out = torch.cat(( out[-1], out[-2]), dim=-1)
 out = self.drop_out(out)
 logits = self.l0(out)
 start_logits, end_logits = logits.split(1, dim=-1)
 start_logits = start_logits.squeeze(-1)
 end_logits = end_logits.squeeze(-1)
 return start_logits, end_logits
main_columns=test._get_numeric_data().columns.drop(['Id'])
 categorical_columns=test.columns.drop(main_columns)
 categorical_columns=categorical_columns.drop(['Id'] )<categorify>
def process_data(tweet, selected_text, sentiment, tokenizer, max_len):
tweet = " " + str(tweet)
 selected_text = " " + str(selected_text)
 len_st = len(selected_text)- 1
idx0 = None
idx1 = None
for ind in(i for i, e in enumerate(tweet)if e == selected_text[1]):
if " " + tweet[ind: ind+len_st] == selected_text:
idx0 = ind
idx1 = ind + len_st - 1
break
char_targets = [0] * len(tweet)
 if idx0 != None and idx1 != None:
for ct in range(idx0, idx1 + 1):
char_targets[ct] = 1
tok_tweet = tokenizer.encode(tweet)
 input_ids_orig = tok_tweet.ids
tweet_offsets = tok_tweet.offsets
target_idx = []
for j,(offset1, offset2)in enumerate(tweet_offsets):
if sum(char_targets[offset1: offset2])> 0:
target_idx.append(j)
 try:
targets_start = target_idx[0]
targets_end = target_idx[-1]
except:
print(tweet)
 targets_start = 0
targets_end = -1
sentiment_id = {
'positive': 1313,
'negative': 2430,
'neutral': 7974
}
input_ids = [0] + [sentiment_id[sentiment]] + [2] + [2] + input_ids_orig + [2]
token_type_ids = [0, 0, 0, 0] + [0] *(len(input_ids_orig)+ 1)
 mask = [1] * len(token_type_ids)
 tweet_offsets = [(0, 0)] * 4 + tweet_offsets + [(0, 0)]
targets_start += 4
targets_end += 4
padding_length = max_len - len(input_ids)
 if padding_length > 0:
input_ids = input_ids +([1] * padding_length)
 mask = mask +([0] * padding_length)
 token_type_ids = token_type_ids +([0] * padding_length)
 tweet_offsets = tweet_offsets +([(0, 0)] * padding_length)
 return {
'ids': input_ids,
'mask': mask,
'token_type_ids': token_type_ids,
'targets_start': targets_start,
'targets_end': targets_end,
'orig_tweet': tweet,
'orig_selected': selected_text,
'sentiment': sentiment,
'offsets': tweet_offsets
}
class TweetDataset:
def __init__(self, tweet, sentiment, selected_text):
self.tweet = tweet
self.sentiment = sentiment
self.selected_text = selected_text
self.tokenizer = TOKENIZER
self.max_len = MAX_LEN
def __len__(self):
return len(self.tweet)
 def __getitem__(self, item):
data = process_data(
 self.tweet[item],
self.selected_text[item],
self.sentiment[item],
self.tokenizer,
self.max_len 
)
 return {
'ids': torch.tensor(data["ids"], dtype=torch.long),
'mask': torch.tensor(data["mask"], dtype=torch.long),
'token_type_ids': torch.tensor(data["token_type_ids"], dtype=torch.long),
'targets_start': torch.tensor(data["targets_start"], dtype=torch.long),
'targets_end': torch.tensor(data["targets_end"], dtype=torch.long),
'orig_tweet': data["orig_tweet"],
'orig_selected': data["orig_selected"],
'sentiment': data["sentiment"],
'offsets': torch.tensor(data["offsets"], dtype=torch.long)
 }
encode_FE(train, test, [ 'GarageCars', 'ExterQual',"OverallQual","BsmtQual","Fireplaces","KitchenQual","CentralAir","FullBath","GrLivArea"])
 encode_CB('GarageCars', 'ExterQual',train,test)
 encode_CB("BsmtQual","OverallQual",train,test)
 encode_CB("Fireplaces","KitchenQual",train,test)
 encode_CB("CentralAir","FullBath",train,test)
 encode_CB('GarageCars_ExterQual','BsmtQual_OverallQual',train,test)
 encode_CB('Fireplaces_KitchenQual','CentralAir_FullBath' , train,test)
 encode_CB('GarageCars_ExterQual_BsmtQual_OverallQual' , 'Fireplaces_KitchenQual_CentralAir_FullBath' , train,test)
 encode_AG2(categorical_columns, ["MSSubClass","OverallQual"], train, test )<categorify>
def calculate_jaccard_score(
 original_tweet,
target_string,
sentiment_val,
idx_start,
idx_end,
offsets,
verbose=False):
if idx_end < idx_start:
idx_end = idx_start
filtered_output = ""
for ix in range(idx_start, idx_end + 1):
filtered_output += original_tweet[offsets[ix][0]: offsets[ix][1]]
if(ix+1)< len(offsets)and offsets[ix][1] < offsets[ix+1][0]:
filtered_output += " "
if len(original_tweet.split())< 3:
filtered_output = original_tweet
if sentiment_val != "neutral" and verbose == True:
if filtered_output.strip().lower() != target_string.strip().lower() :
print("********************************")
 print(f"Output= {filtered_output.strip() }")
 print(f"Target= {target_string.strip() }")
 print(f"Tweet= {original_tweet.strip() }")
 print("********************************")
 jac = 0
return jac, filtered_output
encoder=OrdinalEncoder()
imputer=KNN()
def encode(data):

 nonulls = np.array(data.dropna())
 impute_reshape = nonulls.reshape(-1,1)
 impute_ordinal = encoder.fit_transform(impute_reshape)
 data.loc[data.notnull() ] = np.squeeze(impute_ordinal)
 return data<drop_column>
def simple_fix(a):
a = str(a)
 a = a.lower()
a = a.replace("n`****", "n`t it")
 a = a.replace("'", '"')
 a = a.replace("`", "'")
 a = a.replace("Â", "_")
 a = a.replace("ï¿½", "_'_")
 a = a.replace("{", "(")
 a = a.replace("}", ")")
 a = a.replace("[", "(")
 a = a.replace("]", ")")
 a = a.replace("::", "''")
 return a
main_columns=test._get_numeric_data().columns.drop(['Id'])
 categorical_columns=test.columns.drop(main_columns)
 categorical_columns=categorical_columns.drop(['Id'] )<categorify>
df_test = pd.read_csv(".. /input/tweet-sentiment-extraction/test.csv")
 df_test.loc[:, "original_text"] = df_test.text.values
df_test['text'] = df_test.text.map(simple_fix)
 df_test.loc[:, "selected_text"] = df_test.text.values
for i in categorical_columns:
lbe=preprocessing.LabelEncoder()
train[i]=lbe.fit_transform(train[i].astype(str))
test[i]=lbe.fit_transform(test[i].astype(str))<categorify>
device = torch.device("cuda")
 model_config = transformers.RobertaConfig.from_pretrained(ROBERTA_PATH)
 model_config.output_hidden_states = True
train=train.fillna(-1)
 test=test.fillna(-1 )<categorify>
model0 = TweetModel(conf=model_config)
 model0.to(device)
 model0.load_state_dict(torch.load(".. /input/strong-v2/model_f0_s696.bin"))
model0.eval()
model1 = TweetModel(conf=model_config)
 model1.to(device)
 model1.load_state_dict(torch.load(".. /input/strong-v2/model_f1_s696.bin"))
model1.eval()
model2 = TweetModel(conf=model_config)
 model2.to(device)
 model2.load_state_dict(torch.load(".. /input/strong-v2/model_f2_s696.bin"))
model2.eval()
model3 = TweetModel(conf=model_config)
 model3.to(device)
 model3.load_state_dict(torch.load(".. /input/strong-v2/model_f3_s696.bin"))
model3.eval()
model4 = TweetModel(conf=model_config)
 model4.to(device)
 model4.load_state_dict(torch.load(".. /input/strong-v2/model_f4_s696.bin"))
model4.eval()
1+1
for i in categorical_columns:
if(test[i].max() == train[i].max())&(train[i].max() <10):
test = pd.get_dummies(test, columns = [i])
 train=pd.get_dummies(train, columns = [i] )<prepare_x_and_y>
final_output = []
y = train['SalePrice']
X= train.drop(['Id',"SalePrice"], axis=1)
<define_variables>
test_dataset = TweetDataset(
 tweet=df_test.text.values,
sentiment=df_test.sentiment.values,
selected_text=df_test.selected_text.values 
)
 data_loader = torch.utils.data.DataLoader(
 test_dataset,
shuffle=False,
batch_size=VALID_BATCH_SIZE,
num_workers=1 
)
 with torch.no_grad() :
tk0 = tqdm(data_loader, total=len(data_loader))
for bi, d in enumerate(tk0):
ids = d["ids"]
token_type_ids = d["token_type_ids"]
mask = d["mask"]
sentiment = d["sentiment"]
orig_selected = d["orig_selected"]
orig_tweet = d["orig_tweet"]
targets_start = d["targets_start"]
targets_end = d["targets_end"]
offsets = d["offsets"].numpy()
ids = ids.to(device, dtype=torch.long)
 token_type_ids = token_type_ids.to(device, dtype=torch.long)
 mask = mask.to(device, dtype=torch.long)
 targets_start = targets_start.to(device, dtype=torch.long)
 targets_end = targets_end.to(device, dtype=torch.long)
 outputs_start0, outputs_end0 = model0(
 ids=ids,
mask=mask,
token_type_ids=token_type_ids 
)
 outputs_start1, outputs_end1 = model1(
 ids=ids,
mask=mask,
token_type_ids=token_type_ids 
)
 outputs_start2, outputs_end2 = model2(
 ids=ids,
mask=mask,
token_type_ids=token_type_ids 
)
 outputs_start3, outputs_end3 = model3(
 ids=ids,
mask=mask,
token_type_ids=token_type_ids 
)
 outputs_start4, outputs_end4 = model4(
 ids=ids,
mask=mask,
token_type_ids=token_type_ids 
)
 outputs_start =(1.1*outputs_start0 + outputs_start1 + 1.3* outputs_start2 + 0.9*outputs_start3 + outputs_start4)/ 5
outputs_end =(1.1*outputs_end0 + outputs_end1 + 1.3* outputs_end2 + 0.9*outputs_end3 + outputs_end4)/ 5
outputs_start = torch.softmax(outputs_start, dim=1 ).cpu().detach().numpy()
outputs_end = torch.softmax(outputs_end, dim=1 ).cpu().detach().numpy()
jaccard_scores = []
for px, tweet in enumerate(orig_tweet):
selected_tweet = orig_selected[px]
tweet_sentiment = sentiment[px]
_, output_sentence = calculate_jaccard_score(
 original_tweet=tweet,
target_string=selected_tweet,
sentiment_val=tweet_sentiment,
idx_start=np.argmax(outputs_start[px, :]),
idx_end=np.argmax(outputs_end[px, :]),
offsets=offsets[px] 
)
 final_output.append(output_sentence )
models = [LGBMRegressor,
XGBRegressor,
GradientBoostingRegressor,
RandomForestRegressor,
DecisionTreeRegressor,
MLPRegressor,
KNeighborsRegressor,
SVR]<find_best_model_class>
df_test.loc[:, 'raw_output'] = final_output
df_test.head(5 )
def compML(df, y, alg):
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.30,random_state=42)
 model = alg().fit(X_train, y_train)
 y_pred = model.predict(X_test)
 RMSE = np.sqrt(mean_squared_error(y_test, y_pred))
model_name = alg.__name__
print(model_name, "Model Test error:",RMSE )<compute_test_metric>
def unfix(orig, text, raw_output):
orig = ' '.join(str(orig ).split())
 text = ' '.join(str(text ).split())
 raw_output = ' '.join(str(raw_output ).split())
 pos = text.find(raw_output)
 if pos >= 0:
return orig[pos:pos + len(str(raw_output)) ]
else:
return raw_output
df_test['selected_text'] = df_test.apply(lambda r: unfix(r.original_text, r.text, r.raw_output), axis=1)
 df_test.head(5 )
<split><EOS> 
sample = pd.read_csv(".. /input/tweet-sentiment-extraction/sample_submission.csv")
 sample['selected_text'] = df_test.selected_text.values
sample.to_csv("submission.csv", index=False )