Kaggle competition: Tweet Sentiment Extraction
<SOS> metric: Jaccard Kaggle data source: tweet-sentiment-extraction<compute_test_metric>
warnings.filterwarnings('ignore' )
explained_variance_score(y_test,predictions )<compute_test_metric>
seed=42
print('RMSE',np.sqrt(mean_squared_error(y_test, predictions)) )<train_model>
class TweetDataset(torch.utils.data.Dataset):
def __init__(self, df, max_len=96):
self.df = df
self.max_len = max_len
self.labeled = 'selected_text' in df
self.tokenizer = tokenizers.ByteLevelBPETokenizer(
 vocab_file='.. /input/roberta-base/vocab.json',
merges_file='.. /input/roberta-base/merges.txt',
lowercase=True,
add_prefix_space=True)
 def __getitem__(self, index):
data = {}
row = self.df.iloc[index]
ids, masks, tweet, offsets = self.get_input_data(row)
 data['ids'] = ids
data['masks'] = masks
data['tweet'] = tweet
data['offsets'] = offsets
if self.labeled:
start_idx, end_idx = self.get_target_idx(row, tweet, offsets)
 data['start_idx'] = start_idx
data['end_idx'] = end_idx
return data
def __len__(self):
return len(self.df)
 def get_input_data(self, row):
tweet = " " + " ".join(row.text.lower().split())
 encoding = self.tokenizer.encode(tweet)
 sentiment_id = self.tokenizer.encode(row.sentiment ).ids
ids = [0] + sentiment_id + [2, 2] + encoding.ids + [2]
offsets = [(0, 0)] * 4 + encoding.offsets + [(0, 0)]
pad_len = self.max_len - len(ids)
 if pad_len > 0:
ids += [1] * pad_len
offsets += [(0, 0)] * pad_len
ids = torch.tensor(ids)
 masks = torch.where(ids != 1, torch.tensor(1), torch.tensor(0))
offsets = torch.tensor(offsets)
 return ids, masks, tweet, offsets
def get_target_idx(self, row, tweet, offsets):
selected_text = " " + " ".join(row.selected_text.lower().split())
 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
target_idx = []
for j,(offset1, offset2)in enumerate(offsets):
if sum(char_targets[offset1: offset2])> 0:
target_idx.append(j)
 start_idx = target_idx[0]
end_idx = target_idx[-1]
return start_idx, end_idx
def get_train_val_loaders(df, train_idx, val_idx, batch_size=8):
train_df = df.iloc[train_idx]
val_df = df.iloc[val_idx]
train_loader = torch.utils.data.DataLoader(
 TweetDataset(train_df),
batch_size=batch_size,
shuffle=True,
num_workers=2,
drop_last=True)
 val_loader = torch.utils.data.DataLoader(
 TweetDataset(val_df),
batch_size=batch_size,
shuffle=False,
num_workers=2)
 dataloaders_dict = {"train": train_loader, "val": val_loader}
return dataloaders_dict
def get_test_loader(df, batch_size=32):
loader = torch.utils.data.DataLoader(
 TweetDataset(df),
batch_size=batch_size,
shuffle=False,
num_workers=2)
 return loader
enet=ElasticNet(alpha=besta[0][0], l1_ratio=besta[0][1], normalize=False)
 enet.fit(X_train, y_train)
 predictions=enet.predict(X_test )<compute_test_metric>
class TweetModel(nn.Module):
def __init__(self):
super(TweetModel, self ).__init__()
config = RobertaConfig.from_pretrained(
 '.. /input/roberta-base/config.json', output_hidden_states=True)
 self.roberta = RobertaModel.from_pretrained(
 '.. /input/roberta-base/pytorch_model.bin', config=config)
 self.dropout = nn.Dropout(0.5)
 self.conv1 = nn.Conv1d(in_channels=768, out_channels=768, kernel_size=3, padding=1)
 self.conv2 = nn.Conv1d(in_channels=768, out_channels=64, kernel_size=3, padding=1)
 self.conv3 = nn.Conv1d(in_channels=768, out_channels=768, kernel_size=3, padding=1)
 self.conv4 = nn.Conv1d(in_channels=768, out_channels=64, kernel_size=3, padding=1)
 self.fc1 = nn.Linear(64, 1)
 self.fc2 = nn.Linear(64, 1)
 nn.init.normal_(self.fc1.weight, std=0.02)
 nn.init.normal_(self.fc1.bias, 0)
 nn.init.normal_(self.fc2.weight, std=0.02)
 nn.init.normal_(self.fc2.bias, 0)
 nn.init.xavier_normal_(self.conv1.weight)
 nn.init.xavier_normal_(self.conv2.weight)
 nn.init.xavier_normal_(self.conv3.weight)
 nn.init.xavier_normal_(self.conv4.weight)
 def forward(self, input_ids, attention_mask):
_, _, hs = self.roberta(input_ids, attention_mask)
 x = torch.stack([hs[-1], hs[-2], hs[-3], hs[-4]])
 x = torch.mean(x, 0)
 x = self.dropout(x)
 x1=x.permute(0,2,1)
 x1 = self.conv1(x1)
 x1 = self.conv2(F.leaky_relu(x1))
x1 = x1.permute(0,2,1)
 x1 = self.fc1(x1)
 start_logits = x1.squeeze(-1)
 x2 = x.permute(0,2,1)
 x2 = self.conv3(x2)
 x2 = self.conv4(F.leaky_relu(x2))
x2 = x2.permute(0,2,1)
 x2 = self.fc2(x2)
 end_logits = x2.squeeze(-1)
 return start_logits, end_logits
explained_variance_score(y_test,predictions )<compute_test_metric>
def loss_fn(start_logits, end_logits, start_positions, end_positions):
ce_loss = nn.CrossEntropyLoss()
start_loss = ce_loss(start_logits, start_positions)
 end_loss = ce_loss(end_logits, end_positions)
 total_loss = start_loss + end_loss
return total_loss
print('RMSE',np.sqrt(mean_squared_error(y_test, predictions)) )<predict_on_test>
def get_selected_text(text, start_idx, end_idx, offsets):
selected_text = ""
for ix in range(start_idx, end_idx + 1):
selected_text += text[offsets[ix][0]: offsets[ix][1]]
if(ix + 1)< len(offsets)and offsets[ix][1] < offsets[ix + 1][0]:
selected_text += " "
return selected_text
def jaccard(str1, str2):
a = set(str1.lower().split())
 b = set(str2.lower().split())
 c = a.intersection(b)
 return float(len(c)) /(len(a)+ len(b)- len(c))
def compute_jaccard_score(text, start_idx, end_idx, start_logits, end_logits, offsets):
start_pred = np.argmax(start_logits)
 end_pred = np.argmax(end_logits)
 if start_pred > end_pred:
pred = text
else:
pred = get_selected_text(text, start_pred, end_pred, offsets)
 true = get_selected_text(text, start_idx, end_idx, offsets)
 return jaccard(true, pred )
testpredictions=lasso.predict(test_features)
 testpredictions<prepare_output>
def train_model(model, dataloaders_dict, criterion, optimizer, num_epochs, filename):
model.cuda()
for epoch in range(num_epochs):
for phase in ['train', 'val']:
if phase == 'train':
model.train()
else:
model.eval()
epoch_loss = 0.0
epoch_jaccard = 0.0
for data in(dataloaders_dict[phase]):
ids = data['ids'].cuda()
masks = data['masks'].cuda()
tweet = data['tweet']
offsets = data['offsets'].numpy()
start_idx = data['start_idx'].cuda()
end_idx = data['end_idx'].cuda()
optimizer.zero_grad()
with torch.set_grad_enabled(phase == 'train'):
start_logits, end_logits = model(ids, masks)
 loss = criterion(start_logits, end_logits, start_idx, end_idx)
 if phase == 'train':
loss.backward()
optimizer.step()
epoch_loss += loss.item() * len(ids)
 start_idx = start_idx.cpu().detach().numpy()
end_idx = end_idx.cpu().detach().numpy()
start_logits = torch.softmax(start_logits, dim=1 ).cpu().detach().numpy()
end_logits = torch.softmax(end_logits, dim=1 ).cpu().detach().numpy()
for i in range(len(ids)) :
jaccard_score = compute_jaccard_score(
 tweet[i],
start_idx[i],
end_idx[i],
start_logits[i],
end_logits[i],
offsets[i])
 epoch_jaccard += jaccard_score
epoch_loss = epoch_loss / len(dataloaders_dict[phase].dataset)
 epoch_jaccard = epoch_jaccard / len(dataloaders_dict[phase].dataset)
 print('Epoch {}/{} | {:^5} | Loss: {:.4f} | Jaccard: {:.4f}'.format(
 epoch + 1, num_epochs, phase, epoch_loss, epoch_jaccard))
if epoch<2:
jaccard_check=epoch_jaccard
torch.save(model.state_dict() , filename)
 print('Saving model')
 elif epoch_jaccard>jaccard_check:
jaccard_check=epoch_jaccard
torch.save(model.state_dict() , filename)
 print('Saving model')
 else:
print('Stopping iteration')
 break
Test_price=np.exp(list(testpredictions))
Test_price<save_to_csv>
num_epochs = 10
batch_size = 32
skf = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed )
submission=pd.DataFrame()
submission['Id']=TestId
submission['SalePrice']=Test_price
submission.to_csv('submission.csv', index=False )<feature_engineering>
%%time
train_df = pd.read_csv('.. /input/tweet-sentiment-extraction/train.csv')
 train_df['text'] = train_df['text'].astype(str)
 train_df['selected_text'] = train_df['selected_text'].astype(str)
 for fold,(train_idx, val_idx)in enumerate(skf.split(train_df, train_df.sentiment), start=1):
print(f'Fold: {fold}')
 model = TweetModel()
optimizer = optim.AdamW(model.parameters() , lr=4e-5, betas=(0.9, 0.999))
criterion = loss_fn
dataloaders_dict = get_train_val_loaders(train_df, train_idx, val_idx, batch_size)
 train_model(
 model,
dataloaders_dict,
criterion,
optimizer,
num_epochs,
f'roberta_fold{fold}.pth' )
train_df = pd.read_csv(".. /input/train.csv", header=0)
 train_df["Gender"] = train_df["Sex"].map({"female": 0, "male": 1} ).astype(int)
 train_df.head(3)
 median_age = train_df["Age"].dropna().median()
if len(train_df.Age[train_df.Age.isnull() ])> 0:
train_df.loc[(train_df.Age.isnull()), "Age"] = median_age
train_df['family_size'] = train_df['SibSp'] + train_df['Parch'] + 1
train_df['isAlone'] = train_df['family_size'][train_df['family_size'] == 1]
train_df.loc[(train_df.isAlone.isnull()), 'isAlone'] = 0
def name_classifier(name_df):
name_class_df = pd.DataFrame(columns={'miss', 'mrs', 'master', 'mr'})
 for name in name_df:
if 'Miss' in name:
df = pd.DataFrame([[1,0,0,0]], columns={'miss', 'mrs', 'master', 'mr'})
 elif 'Mrs' in name:
df = pd.DataFrame([[0,1,0,0]], columns={'miss', 'mrs', 'master', 'mr'})
 elif 'Master' in name:
df = pd.DataFrame([[0,0,1,0]], columns={'miss', 'mrs', 'master', 'mr'})
 elif 'Mr' in name:
df = pd.DataFrame([[0,0,0,1]], columns={'miss', 'mrs', 'master', 'mr'})
 else:
df = pd.DataFrame([[0,0,0,0]], columns={'miss', 'mrs', 'master', 'mr'})
 name_class_df = name_class_df.append(df, ignore_index=True)
 return name_class_df
train_df = pd.concat(( train_df,name_classifier(train_df['Name'])) , axis=1)
 train_df = train_df.drop(["Name", "Ticket", "Sex", "SibSp", "Parch", "Cabin","Embarked", "PassengerId"], axis=1)
 test_df = pd.read_csv(".. /input/test.csv", header=0)
 test_df["Gender"] = test_df["Sex"].map({"female": 0, "male": 1} ).astype(int)
 median_age = test_df["Age"].dropna().median()
if len(test_df.Age[test_df.Age.isnull() ])> 0:
test_df.loc[(test_df.Age.isnull()), "Age"] = median_age
test_df['family_size'] = test_df['SibSp'] + test_df['Parch'] + 1
test_df['isAlone'] = test_df['family_size'][test_df['family_size'] == 1]
test_df.loc[(test_df.isAlone.isnull()), 'isAlone'] = 0
test_df = pd.concat(( test_df,name_classifier(test_df['Name'])) , axis=1)
 ids = test_df["PassengerId"].values
test_df = test_df.drop(["Name", "Ticket", "Sex", "SibSp", "Parch", "Cabin", "Embarked", "PassengerId"], axis=1)
 train_data = train_df.values
test_data = test_df.values
model = Sequential()
model.add(Dense(9, activation='relu', input_dim=10))
model.add(Dense(9, activation='relu'))
model.add(Dense(5, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile('adam', 'binary_crossentropy', metrics=['accuracy'])
 model.fit(train_data[:,1:], train_data[:,0], batch_size=32, epochs=200)
 y_pred = model.predict(test_data)
 y_final =(y_pred > 0.5 ).astype(int ).reshape(test_data.shape[0])
 output = y_final
submit_file = open("./submit.csv", "w")
 file_object = csv.writer(submit_file)
 file_object.writerow(["PassengerId", "Survived"])
 file_object.writerows(zip(ids, output))
submit_file.close()
train_df.head(5 )<set_options>
%%time
test_df = pd.read_csv('.. /input/tweet-sentiment-extraction/test.csv')
 test_df['text'] = test_df['text'].astype(str)
 test_loader = get_test_loader(test_df)
 predictions = []
models = []
for fold in range(skf.n_splits):
model = TweetModel()
model.cuda()
model.load_state_dict(torch.load(f'roberta_fold{fold+1}.pth'))
model.eval()
models.append(model)
 for data in test_loader:
ids = data['ids'].cuda()
masks = data['masks'].cuda()
tweet = data['tweet']
offsets = data['offsets'].numpy()
start_logits = []
end_logits = []
for model in models:
with torch.no_grad() :
output = model(ids, masks)
 start_logits.append(torch.softmax(output[0], dim=1 ).cpu().detach().numpy())
 end_logits.append(torch.softmax(output[1], dim=1 ).cpu().detach().numpy())
 start_logits = np.mean(start_logits, axis=0)
 end_logits = np.mean(end_logits, axis=0)
 for i in range(len(ids)) :
start_pred = np.argmax(start_logits[i])
 end_pred = np.argmax(end_logits[i])
 if start_pred > end_pred:
pred = tweet[i]
else:
pred = get_selected_text(tweet[i], start_pred, end_pred, offsets[i])
 predictions.append(pred )
%matplotlib inline
warnings.filterwarnings("ignore" )<load_from_csv>
sub_df = pd.read_csv('.. /input/tweet-sentiment-extraction/sample_submission.csv')
 sub_df['selected_text'] = predictions
sub_df['selected_text'] = sub_df['selected_text'].apply(lambda x: x.replace('!!!!', '!')if len(x.split())==1 else x)
 sub_df['selected_text'] = sub_df['selected_text'].apply(lambda x: x.replace('.. ', '.')if len(x.split())==1 else x)
 sub_df['selected_text'] = sub_df['selected_text'].apply(lambda x: x.replace('...', '.')if len(x.split())==1 else x)
 sub_df.to_csv('submission.csv', index=False)
 sub_df.head()