Kaggle competition: Mechanisms of Action (MoA) Prediction
<SOS> metric: MeanColumnwiseLogLoss Kaggle data source: mechanisms-of-action-(moa)-prediction<categorify>
!pip install --no-index --find-links /kaggle/input/pytorchtabnet/pytorch_tabnet-2.0.0-py3-none-any.whl pytorch-tabnet
!pip install /kaggle/input/iterative-stratification/iterative-stratification-master/
def quesa_format_train(train):
out = []
for i, row in enumerate(train):
qas = []
con = []
ans = []
question = row[-1]
answer = row[2]
context = row[1]
qid = row[0]
answer_start = l[i]
ans.append({"answer_start": answer_start, "text": answer.lower() })
 qas.append({"question": question, "id": qid, "is_impossible": False, "answers": ans})
 out.append({"context": context.lower() , "qas": qas})
 return out
train_json_format = quesa_format_train(train_array)
 with open('data/train.json', 'w')as outfile:
json.dump(train_json_format, outfile )<categorify>
warnings.filterwarnings("ignore")
 sys.path.append(".. /input/rank-gauss")
 os.environ["CUDA_LAUNCH_BLOCKING"] = '1'
plt.style.use("fivethirtyeight")
 c_ = Fore.CYAN
m_ = Fore.MAGENTA
r_ = Fore.RED
b_ = Fore.BLUE
y_ = Fore.YELLOW
g_ = Fore.GREEN
def quesa_format_test(train):
out = []
for i, row in enumerate(train):
qas = []
con = []
ans = []
question = row[-1]
context = row[1]
qid = row[0]
answer_start = l[i]
ans.append({"answer_start": 1000000, "text": "__None__"})
 qas.append({"question": question, "id": qid, "is_impossible": False, "answers": ans})
 out.append({"context": context.lower() , "qas": qas})
 return out
test_json_format = quesa_format_test(test_array)
 with open('data/test.json', 'w')as outfile:
json.dump(test_json_format, outfile )<install_modules>
seed = 42
def set_seed(seed):
random.seed(seed)
 np.random.seed(seed)
 torch.manual_seed(seed)
 os.environ["PYTHONHASHSEED"] = str(seed)
 if torch.cuda.is_available() :
torch.cuda.manual_seed(seed)
 torch.cuda.manual_seed_all(seed)
 torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
set_seed(seed )
!pip install '/kaggle/input/train-requirements/seqeval-0.0.12-py3-none-any.whl' -q
!pip install '/kaggle/input/train-requirements/simpletransformers-0.22.1-py3-none-any.whl' -q<load_pretrained>
data_path = ".. /input/lish-moa/"
no_ctl = True
scale = "rankgauss"
variance_threshould = 0.7
decompo = "PCA"
ncompo_genes = 80
ncompo_cells = 10
encoding = "dummy"
model_path = '/kaggle/input/transformers-pretrained-distilbert/distilbert-base-uncased-distilled-squad/'
model = QuestionAnsweringModel('distilbert',
model_path,
args={'reprocess_input_data': True,
'overwrite_output_dir': True,
'learning_rate': 5e-5,
'num_train_epochs': 4,
'max_seq_length': 128,
'doc_stride': 64,
'fp16': False,
},
use_cuda=use_cuda)
 model.train_model('data/train.json' )<predict_on_test>
train = pd.read_csv(data_path + "train_features.csv")
 targets = pd.read_csv(data_path + "train_targets_scored.csv")
 test = pd.read_csv(data_path + "test_features.csv")
 submission = pd.read_csv(data_path + "sample_submission.csv" )
pred = model.predict(test_json_format )<save_to_csv>
if no_ctl:
print(b_, "not_ctl")
 train = train[train["cp_type"] != "ctl_vehicle"]
test = test[test["cp_type"] != "ctl_vehicle"]
targets = targets.iloc[train.index]
train.reset_index(drop = True, inplace = True)
 test.reset_index(drop = True, inplace = True)
 targets.reset_index(drop = True, inplace = True )
df = pd.DataFrame.from_dict(pred)
 sample_submission["selected_text"] = df["answer"]
sample_submission.to_csv("submission.csv", index = False)
 print("File submitted successfully." )<set_options>
GENES = [col for col in train.columns if col.startswith("g-")]
CELLS = [col for col in train.columns if col.startswith("c-")]
%matplotlib inline<load_from_csv>
data_all = pd.concat([train, test], ignore_index = True)
 cols_numeric = [feat for feat in list(data_all.columns)if feat not in ["sig_id", "cp_type", "cp_time", "cp_dose"]]
mask =(data_all[cols_numeric].var() >= variance_threshould ).values
tmp = data_all[cols_numeric].loc[:, mask]
data_all = pd.concat([data_all[["sig_id", "cp_type", "cp_time", "cp_dose"]], tmp], axis = 1)
 cols_numeric = [feat for feat in list(data_all.columns)if feat not in ["sig_id", "cp_type", "cp_time", "cp_dose"]]
train = pd.read_csv("/kaggle/input/tweet-sentiment-extraction/train.csv")
 test = pd.read_csv("/kaggle/input/tweet-sentiment-extraction/test.csv")
 sample_submission = pd.read_csv("/kaggle/input/tweet-sentiment-extraction/sample_submission.csv" )<correct_missing_values>
def scale_minmax(col):
return(col - col.min())/(col.max() - col.min())
 def scale_norm(col):
return(col - col.mean())/ col.std()
if scale == "boxcox":
print(b_, "boxcox")
 data_all[cols_numeric] = data_all[cols_numeric].apply(scale_minmax, axis = 0)
 trans = []
for feat in cols_numeric:
trans_var, lambda_var = stats.boxcox(data_all[feat].dropna() + 1)
 trans.append(scale_minmax(trans_var))
data_all[cols_numeric] = np.asarray(trans ).T
elif scale == "norm":
print(b_, "norm")
 data_all[cols_numeric] = data_all[cols_numeric].apply(scale_norm, axis = 0)
 elif scale == "minmax":
print(b_, "minmax")
 data_all[cols_numeric] = data_all[cols_numeric].apply(scale_minmax, axis = 0)
 elif scale == "rankgauss":
print(b_, "Rank Gauss")
 scaler = GaussRankScaler()
data_all[cols_numeric] = scaler.fit_transform(data_all[cols_numeric])
 else:
pass
print(train[train["text"].isnull() == True])
 train.dropna(inplace = True )<feature_engineering>
if decompo == "PCA":
print(b_, "PCA")
 GENES = [col for col in data_all.columns if col.startswith("g-")]
CELLS = [col for col in data_all.columns if col.startswith("c-")]
pca_genes = PCA(n_components = ncompo_genes,
random_state = seed ).fit_transform(data_all[GENES])
 pca_cells = PCA(n_components = ncompo_cells,
random_state = seed ).fit_transform(data_all[CELLS])
 pca_genes = pd.DataFrame(pca_genes, columns = [f"pca_g-{i}" for i in range(ncompo_genes)])
 pca_cells = pd.DataFrame(pca_cells, columns = [f"pca_c-{i}" for i in range(ncompo_cells)])
 data_all = pd.concat([data_all, pca_genes, pca_cells], axis = 1)
 else:
pass
def len_sent(data):
return len(data.split())
 train["num_words_text"] = train["text"].apply(lambda x : len_sent(x))
test["num_words_text"] = test["text"].apply(lambda x : len_sent(x))
train["num_words_selected_text"] = train["selected_text"].apply(lambda x : len_sent(x))<feature_engineering>
if encoding == "lb":
print(b_, "Label Encoding")
 for feat in ["cp_time", "cp_dose"]:
data_all[feat] = LabelEncoder().fit_transform(data_all[feat])
 elif encoding == "dummy":
print(b_, "One-Hot")
 data_all = pd.get_dummies(data_all, columns = ["cp_time", "cp_dose"] )
train["text"] = train["text"].apply(lambda x : x.strip())
 train["selected_text"] = train["selected_text"].apply(lambda x : x.strip())
 train["is_equal"] =(train["text"] == train["selected_text"])
 df_neutral = train[train["sentiment"] == "neutral"]
percentage =(len(df_neutral[df_neutral["is_equal"] == True])/len(df_neutral)) * 100
print(f"Percentage of text column sentences is equal selected_text column for neutral sentiment --> {percentage}" )<feature_engineering>
GENES = [col for col in data_all.columns if col.startswith("g-")]
CELLS = [col for col in data_all.columns if col.startswith("c-")]
for stats in tqdm.tqdm(["sum", "mean", "std", "kurt", "skew"]):
data_all["g_" + stats] = getattr(data_all[GENES], stats )(axis = 1)
 data_all["c_" + stats] = getattr(data_all[CELLS], stats )(axis = 1)
 data_all["gc_" + stats] = getattr(data_all[GENES + CELLS], stats )(axis = 1 )
def punc_count(data):
return len([w for w in data if w in string.punctuation])
 train["text_punc_count"] = train["text"].apply(lambda x : punc_count(x))
train["selected_text_punc_count"] = train["selected_text"].apply(lambda x : punc_count(x))<filter>
with open("data_all.pickle", "wb")as f:
pickle.dump(data_all, f )
word_cloud(train[train["sentiment"] == "neutral"]["text"], "Most Repeated words in neural sentences train['text']" )<filter>
with open("data_all.pickle", "rb")as f:
data_all = pickle.load(f )
word_cloud(train[train["sentiment"] == "negative"]["text"], "Most Repeated words in negative sentences train['text']" )<filter>
features_to_drop = ["sig_id", "cp_type"]
data_all.drop(features_to_drop, axis = 1, inplace = True)
 try:
targets.drop("sig_id", axis = 1, inplace = True)
 except:
pass
train_df = data_all[: train.shape[0]]
train_df.reset_index(drop = True, inplace = True)
 test_df = data_all[train_df.shape[0]: ]
test_df.reset_index(drop = True, inplace = True )
word_cloud(train[train["sentiment"] == "positive"]["text"], "Most Repeated words in positive sentences train['text']" )<string_transform>
MAX_EPOCH = 200
tabnet_params = dict(
 n_d = 32,
n_a = 32,
n_steps = 1,
gamma = 1.3,
lambda_sparse = 0,
optimizer_fn = optim.Adam,
optimizer_params = dict(lr = 2e-2, weight_decay = 1e-5),
mask_type = "entmax",
scheduler_params = dict(
 mode = "min", patience = 5, min_lr = 1e-5, factor = 0.9),
scheduler_fn = ReduceLROnPlateau,
seed = seed,
verbose = 10
)
def n_grams(ngram, data):
freq_dict = defaultdict(int)
 for text in data:
tokens = [w for w in text.lower().split() if w != " " if w not in stopwords]
ngrams = zip(*[tokens[i:] for i in range(ngram)])
 list_grams = [" ".join(ngram)for ngram in ngrams]
for word in list_grams:
freq_dict[word] += 1
fd_sorted = pd.DataFrame(sorted(freq_dict.items() , key=lambda x: x[1])[::-1])
 fd_sorted.columns = ["word", "wordcount"]
return fd_sorted
fd_sorted_neutral1 = n_grams(1, train[train["sentiment"] == "neutral"]["text"])
 fd_sorted_negative1 = n_grams(1, train[train["sentiment"] == "negative"]["text"])
 fd_sorted_positive1 = n_grams(1, train[train["sentiment"] == "positive"]["text"])
 fd_sorted_neutral2 = n_grams(2, train[train["sentiment"] == "neutral"]["text"])
 fd_sorted_negative2 = n_grams(2, train[train["sentiment"] == "negative"]["text"])
 fd_sorted_positive2 = n_grams(2, train[train["sentiment"] == "positive"]["text"])
 fd_sorted_neutral3 = n_grams(3, train[train["sentiment"] == "neutral"]["text"])
 fd_sorted_negative3 = n_grams(3, train[train["sentiment"] == "negative"]["text"])
 fd_sorted_positive3 = n_grams(3, train[train["sentiment"] == "positive"]["text"] )<split>
class LogitsLogLoss(Metric):

 def __init__(self):
self._name = "logits_ll"
self._maximize = False
def __call__(self, y_true, y_pred):

 logits = 1 /(1 + np.exp(-y_pred))
aux =(1 - y_true)* np.log(1 - logits + 1e-15)+ y_true * np.log(logits + 1e-15)
 return np.mean(-aux )
train_array = np.array(train.iloc[:, :4])
 test_array = np.array(test.iloc[:, :3])
 use_cuda = True<sort_values>
scores_auc_all = []
test_cv_preds = []
NB_SPLITS = 10
mskf = MultilabelStratifiedKFold(n_splits = NB_SPLITS, random_state = 0, shuffle = True)
 oof_preds = []
oof_targets = []
scores = []
scores_auc = []
for fold_nb,(train_idx, val_idx)in enumerate(mskf.split(train_df, targets)) :
print(b_,"FOLDS: ", r_, fold_nb + 1)
 print(g_, '*' * 60, c_)
 X_train, y_train = train_df.values[train_idx, :], targets.values[train_idx, :]
X_val, y_val = train_df.values[val_idx, :], targets.values[val_idx, :]
model = TabNetRegressor(**tabnet_params)
 model.fit(
 X_train = X_train,
y_train = y_train,
eval_set = [(X_val, y_val)],
eval_name = ["val"],
eval_metric = ["logits_ll"],
max_epochs = MAX_EPOCH,
patience = 20,
batch_size = 1024,
virtual_batch_size = 32,
num_workers = 1,
drop_last = False,
loss_fn = F.binary_cross_entropy_with_logits 
)
 print(y_, '-' * 60)
 preds_val = model.predict(X_val)
 preds = 1 /(1 + np.exp(-preds_val))
score = np.min(model.history["val_logits_ll"])
 oof_preds.append(preds_val)
 oof_targets.append(y_val)
 scores.append(score)
 preds_test = model.predict(X_test)
 test_cv_preds.append(1 /(1 + np.exp(-preds_test)))
 oof_preds_all = np.concatenate(oof_preds)
 oof_targets_all = np.concatenate(oof_targets)
 test_preds_all = np.stack(test_cv_preds )
def start_index(text, selected_text):
start_index = text.lower().find(selected_text.lower())
 l.append(start_index)
 l = []
for i in range(len(train_array)) :
start_index(train_array[i, 1], train_array[i, 2] )<categorify>
aucs = []
for task_id in range(oof_preds_all.shape[1]):
aucs.append(roc_auc_score(y_true = oof_targets_all[:, task_id],
y_score = oof_preds_all[:, task_id] 
))
print(f"{b_}Overall AUC: {r_}{np.mean(aucs)}")
 print(f"{b_}Average CV: {r_}{np.mean(scores)}" )
def quesa_format_train(train):
out = []
for i, row in enumerate(train):
qas = []
con = []
ans = []
question = row[-1]
answer = row[2]
context = row[1]
qid = row[0]
answer_start = l[i]
ans.append({"answer_start": answer_start, "text": answer.lower() })
 qas.append({"question": question, "id": qid, "is_impossible": False, "answers": ans})
 out.append({"context": context.lower() , "qas": qas})
 return out
train_json_format = quesa_format_train(train_array)
 with open('data/train.json', 'w')as outfile:
json.dump(train_json_format, outfile )<categorify>
all_feat = [col for col in submission.columns if col not in ["sig_id"]]
test = pd.read_csv(data_path + "test_features.csv")
 sig_id = test[test["cp_type"] != "ctl_vehicle"].sig_id.reset_index(drop = True)
 tmp = pd.DataFrame(test_preds_all.mean(axis = 0), columns = all_feat)
 tmp["sig_id"] = sig_id
submission = pd.merge(test[["sig_id"]], tmp, on = "sig_id", how = "left")
 submission.fillna(0, inplace = True)
 submission.to_csv("submission.csv", index = None)
 submission.head()