Kaggle competition: OSIC Pulmonary Fibrosis Progression
<SOS> metric: LaplaceLogLikelihood Kaggle data source: osic-pulmonary-fibrosis-progression<save_to_csv>
pd.set_option('display.max_columns', 50)
 tf_version = tf.__version__
print("
Tensorflow version " + tf_version )
submission = test_df[['qid']].copy()
submission['prediction'] = np.sum(test_preds*np.array(magic_numbers),axis=1)>0.37
submission.to_csv('submission.csv',index=False )<import_modules>
input_path = '.. /input/osic-pulmonary-fibrosis-progression'
pretrained_path = '.. /input/osic-linear-decay-and-quant-reg-base/pretrained_weights'
import os
import time
import re
import regex
import numpy as np
import pandas as pd
from tqdm import tqdm
from pathlib import Path
import random
import matplotlib.pyplot as plt
from multiprocessing import Pool
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import f1_score, roc_curve, precision_recall_curve
from sklearn.preprocessing import StandardScaler
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences<define_variables>
def height_proxy(fvc_e, age, sex):
if sex == 'Female': h = fvc_e/(21.78-0.101*age)
 else: h = fvc_e/(27.63-0.112*age)
 return h
def process_init_week(df, train_df = False):
if train_df:
df['min_week'] = df.groupby('Patient')['Weeks'].transform('min')
 base = df.loc[df.Weeks == df.min_week][['Patient', 'FVC', 'Percent', 'Age', 'Sex']]
base['FVC_init_avg']= base.groupby('Patient')['FVC'].transform('mean' ).astype(int)
 base['Percent_init']= base.groupby('Patient')['Percent'].transform('mean')
 base = base[['Patient', 'FVC_init_avg', 'Percent_init', 'Age', 'Sex']].drop_duplicates()
base['FVC_expected'] =(base['FVC_init_avg'] /(base['Percent_init']/100))
base['Height_proxy'] = base.apply(lambda x: height_proxy(x.FVC_expected, x.Age, x.Sex), axis=1)
 base = base[['Patient', 'Height_proxy', 'FVC_init_avg', 'Percent_init']]
df = df.merge(base, on='Patient', how='left')
 df['init_week'] = df['Weeks'] - df['min_week']
return df
cuda_idx = 0<define_variables>
train = pd.read_csv(input_path + '/train.csv')
 train = process_init_week(train, train_df = True)
 train.drop_duplicates(keep='first', inplace=True, subset=['Patient','Weeks'])
 train.head(3 )
all_start = time.time()<set_options>
sub = pd.read_csv(input_path + '/sample_submission.csv')
 test = pd.read_csv(input_path + '/test.csv')
 sub['Patient'] = sub['Patient_Week'].apply(lambda x:x.split('_')[0])
 sub['Weeks'] = sub['Patient_Week'].apply(lambda x: int(x.split('_')[-1]))
sub = sub[['Patient','Weeks','Confidence','Patient_Week']]
test = test.rename(columns={'Weeks': 'min_week'})
 sub = sub.merge(test, on='Patient')
 sub = process_init_week(sub, train_df = False)
 sub.head(3 )
def seed_torch(seed=1019):
random.seed(seed)
 os.environ['PYTHONHASHSEED'] = str(seed)
 np.random.seed(seed)
 torch.manual_seed(seed)
 torch.cuda.manual_seed(seed)
 torch.backends.cudnn.deterministic = True
SEED = 1019
seed_torch(SEED )<init_hyperparams>
def scale_fn(var_name):
col = train[var_name]
return lambda x:(x - col.min())/(col.max() - col.min())
 scale_age = scale_fn('Age')
 scale_height = scale_fn('Height_proxy')
 scale_percent = scale_fn('Percent')
 scale_fvc = scale_fn('FVC_init_avg')
 scale_week = lambda x:(x -(-12)) /(133-(-12))
def transform_features(df):
df = df.assign(sex_code = np.where(df['Sex'] == 'Female', 1, 0))
df = df.assign(ex_smoker = np.where(df['SmokingStatus'] == 'Ex-smoker', 1, 0))
df = df.assign(never_smoked = np.where(df['SmokingStatus'] == 'Never smoked', 1, 0))
df = df.assign(current_smoker = np.where(df['SmokingStatus'] == 'Currently smokes', 1, 0))
df['has_smoked'] = df['ex_smoker'] + df['current_smoker']
df['age'] = df['Age'].map(scale_age)
 df['height'] = df['Height_proxy'].map(scale_height)
 df['percent'] = df['Percent'].map(scale_percent)
 df['percent_init'] = df['Percent_init'].map(scale_percent)
 df['week'] = df['Weeks'].map(scale_week)
 df['fvc_init'] = df['FVC_init_avg'].map(scale_fvc)
 return df
class Config:
num_epochs = 6
num_embedding_learn_epochs = 1
embedding_noise_var = 0.01
batch_size = [256, 512, 512, 1024, 1024, 1536]
test_batch_size = 512
vocab_size = 120000
max_length = 72
embedding_size = 300
hidden_size = 96
num_layers = 1
num_gru_layers = 1
embedding_dropout = 0.3
layer_dropout = 0.1
dense_size = [hidden_size*2*4+3, int(hidden_size/4)]
output_size = 1
num_cv_splits = 5
num_routings = 4
num_capsules = 5
dim_capsules = 5
learning_rate = 0.001
max_learning_rate = 0.003
clr_step_size = 300
clr_gamma = 0.9999
clip_grad = 5.0
embeddings = ['glove', 'paragram', 'fasttext']
datadir = Path('.. /input')
 c = Config()<define_variables>
train = transform_features(train)
 train.reset_index(inplace=True, drop = True)
 train.head(3 )
puncts = [
',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&',
'/', '[', ']', '%', '=', '
'·', '_', '{', '}', '©', '^', '®', '`', '→', '°', '€', '™', '›',
'♥', '←', '×', '§', '″', '′', 'Â', '█', 'à', '…', '“', '★', '”',
'–', '●', 'â', '►', '−', '¢', '¬', '░', '¶', '↑', '±', '▾',
'═', '¦', '║', '―', '¥', '▓', '—', '‹', '─', '▒', '：', '⊕', '▼',
'▪', '†', '■', '’', '▀', '¨', '▄', '♫', '☆', 'é', '¯', '♦', '¤', '▲',
'è', '¸', 'Ã', '⋅', '‘', '∞', '∙', '）', '↓', '、', '│', '（', '»',
'，', '♪', '╩', '╚', '³', '・', '╦', '╣', '╔', '╗', '▬', '❤', 'ï', 'Ø',
'¹', '≤', '‡', '₹', '´'
]<define_variables>
sub = transform_features(sub)
 sub.head(3 )
abbreviations = {
"ain't": "is not",
"aren't": "are not",
"can't": "cannot",
"'cause": "because",
"could've": "could have",
"couldn't": "could not",
"didn't": "did not",
"doesn't": "does not",
"don't": "do not",
"hadn't": "had not",
"hasn't": "has not",
"haven't": "have not",
"he'd": "he would",
"he'll": "he will",
"he's": "he is",
"how'd": "how did",
"how'd'y": "how do you",
"how'll": "how will",
"how's": "how is",
"I'd": "I would",
"I'd've": "I would have",
"I'll": "I will",
"I'll've": "I will have",
"I'm": "I am",
"I've": "I have",
"i'd": "i would",
"i'd've": "i would have",
"i'll": "i will",
"i'll've": "i will have",
"i'm": "i am",
"i've": "i have",
"isn't": "is not",
"it'd": "it would",
"it'd've": "it would have",
"it'll": "it will",
"it'll've": "it will have",
"it's": "it is",
"let's": "let us",
"ma'am": "madam",
"mayn't": "may not",
"might've": "might have",
"mightn't": "might not",
"mightn't've": "might not have",
"must've": "must have",
"mustn't": "must not",
"mustn't've": "must not have",
"needn't": "need not",
"needn't've": "need not have",
"o'clock": "of the clock",
"oughtn't": "ought not",
"oughtn't've": "ought not have",
"shan't": "shall not",
"sha'n't": "shall not",
"shan't've": "shall not have",
"she'd": "she would",
"she'd've": "she would have",
"she'll": "she will",
"she'll've": "she will have",
"she's": "she is",
"should've": "should have",
"shouldn't": "should not",
"shouldn't've": "should not have",
"so've": "so have",
"so's": "so as",
"this's": "this is",
"that'd": "that would",
"that'd've": "that would have",
"that's": "that is",
"there'd": "there would",
"there'd've": "there would have",
"there's": "there is",
"here's": "here is",
"they'd": "they would",
"they'd've": "they would have",
"they'll": "they will",
"they'll've": "they will have",
"they're": "they are",
"they've": "they have",
"to've": "to have",
"wasn't": "was not",
"we'd": "we would",
"we'd've": "we would have",
"we'll": "we will",
"we'll've": "we will have",
"we're": "we are",
"we've": "we have",
"weren't": "were not",
"what'll": "what will",
"what'll've": "what will have",
"what're": "what are",
"what's": "what is",
"what've": "what have",
"when's": "when is",
"when've": "when have",
"where'd": "where did",
"where's": "where is",
"where've": "where have",
"who'll": "who will",
"who'll've": "who will have",
"who's": "who is",
"who've": "who have",
"why's": "why is",
"why've": "why have",
"will've": "will have",
"won't": "will not",
"won't've": "will not have",
"would've": "would have",
"wouldn't": "would not",
"wouldn't've": "would not have",
"y'all": "you all",
"y'all'd": "you all would",
"y'all'd've": "you all would have",
"y'all're": "you all are",
"y'all've": "you all have",
"you'd": "you would",
"you'd've": "you would have",
"you'll": "you will",
"you'll've": "you will have",
"you're": "you are",
"you've": "you have",
"who'd": "who would",
"who're": "who are",
"'re": " are",
"tryin'": "trying",
"doesn'": "does not",
'howdo': 'how do',
'whatare': 'what are',
'howcan': 'how can',
'howmuch': 'how much',
'howmany': 'how many',
'whydo': 'why do',
'doI': 'do I',
'theBest': 'the best',
'howdoes': 'how does',
}<define_variables>
PREDICTIONS = sub[['Patient', 'Weeks', 'Patient_Week']].copy()
PREDICTIONS.head(5 )
spells = {
'colour': 'color',
'centre': 'center',
'favourite': 'favorite',
'travelling': 'traveling',
'counselling': 'counseling',
'theatre': 'theater',
'cancelled': 'canceled',
'labour': 'labor',
'organisation': 'organization',
'wwii': 'world war 2',
'citicise': 'criticize',
'youtu.be': 'youtube',
'youtu ': 'youtube ',
'qoura': 'quora',
'sallary': 'salary',
'Whta': 'what',
'whta': 'what',
'narcisist': 'narcissist',
'mastrubation': 'masturbation',
'mastrubate': 'masturbate',
"mastrubating": 'masturbating',
'pennis': 'penis',
'Etherium': 'ethereum',
'etherium': 'ethereum',
'narcissit': 'narcissist',
'bigdata': 'big data',
'2k17': '2017',
'2k18': '2018',
'qouta': 'quota',
'exboyfriend': 'ex boyfriend',
'exgirlfriend': 'ex girlfriend',
'airhostess': 'air hostess',
"whst": 'what',
'watsapp': 'whatsapp',
'demonitisation': 'demonetization',
'demonitization': 'demonetization',
'demonetisation': 'demonetization',
'quorans': 'quora user',
'quoran': 'quora user',
'pokémon': 'pokemon',
}<load_from_csv>
LD_inference = pd.read_csv(pretrained_path + '/inference_linear_decay_2020Sep19.csv')
 LD_inference
@timer
def load_data(datadir):
train_df = pd.read_csv(datadir / 'train.csv')
 test_df = pd.read_csv(datadir / 'test.csv')
 print("Train shape : ", train_df.shape)
 print("Test shape : ", test_df.shape)
 return train_df, test_df
def clean(df):
df = clean_lower(df)
 df = clean_unicode(df)
 df = clean_math(df)
 df = clean_abbreviation(df, abbreviations)
 df = clean_spells(df, spells)
 df = clean_language(df)
 df = clean_puncts(df, puncts)
 df = clean_space(df)
 return df
def clean_unicode(df):
codes = ['\x7f', '\u200b', '\xa0', '\ufeff', '\u200e', '\u202a', '\u202c', '\u2060', '\uf0d8', '\ue019', '\uf02d', '\u200f', '\u2061', '\ue01b']
df["question_text"] = df["question_text"].apply(lambda x: _clean_unicode(x, codes))
return df
def _clean_unicode(x, codes):
for u in codes:
if u in x:
x = x.replace(u, '')
 return x
def clean_language(df):
langs1 = r'[\p{Katakana}\p{Hiragana}\p{Han}]'
langs2 = r'[ஆய்தஎழுத்துஆயுதஎழுத்துशुषछछशुषدوउसशुष북한내제តើបងប្អូនមានមធ្យបាយអ្វីខ្លះដើម្បីរកឃើញឯកសារអំពីប្រវត្តិស្ត្រនៃប្រាសាទអង្គរវट्टरौरआदસંઘરાજ્યपीतऊनअहএকটিবাড়িএকটিখামারএরঅধীনেপদেরবাছাইপরীক্ষাএরপ্রশ্নওউত্তরসহকোথায়পেতেপারিص、。Емелядуракلكلمقاممقال수능ί서로가를행복하게기乡국고등학교는몇시간업니《》싱관없어나이रचा키کپڤ」मिलगईकलेजेकोठंडकऋॠऌॡर]'
compiled_langs1 = regex.compile(langs1)
 compiled_langs2 = re.compile(langs2)
 df['question_text'] = df['question_text'].apply(lambda x: _clean_language(x, compiled_langs1))
df['question_text'] = df['question_text'].apply(lambda x: _clean_language(x, compiled_langs2))
return df
def _clean_language(x, compiled_re):
return compiled_re.sub(' <lang> ', x)
 def clean_bitcoin(df, bitcoins):
compiled_bitcoins = re.compile('(%s)' % '|'.join(bitcoins))
df['question_text'] = df['question_text'].apply(lambda x: _clean_language(x, compiled_bitcoins))
return df
def _clean_bitcoin(x, compiled_re):
return compiled_re.sub(' Bitcoin ', x)
 def clean_math(df):
math_puncts = 'θπα÷⁴≠β²¾∫≥⇒¬∠＝∑Φ√½¼'
math_puncts_long = [r'\\frac', r'\[math\]', r'\[/math\]', r'\\lim']
compiled_math = re.compile('(%s)' % '|'.join(math_puncts))
compiled_math_long = re.compile('(%s)' % '|'.join(math_puncts_long))
df['question_text'] = df['question_text'].apply(lambda x: _clean_math(x, compiled_math_long))
df['question_text'] = df['question_text'].apply(lambda x: _clean_math(x, compiled_math))
return df
def _clean_math(x, compiled_re):
return compiled_re.sub(' <math> ', x)
 def clean_lower(df):
df["question_text"] = df["question_text"].apply(lambda x: x.lower())
 return df
def clean_puncts(df, puncts):
df['question_text'] = df['question_text'].apply(lambda x: _clean_puncts(x, puncts))
return df
def _clean_puncts(x, puncts):
x = str(x)
 for punct in puncts:
if punct in x:
x = x.replace(punct, f' {punct} ')
 return x
def clean_bad_case_words(df, bad_case_words):
compiled_bad_case_words = re.compile('(%s)' % '|'.join(bad_case_words.keys()))
def replace(match):
return bad_case_words[match.group(0)]
df['question_text'] = df["question_text"].apply(
 lambda x: _clean_bad_case_words(x, compiled_bad_case_words, replace)
)
 return df
def _clean_bad_case_words(x, compiled_re, replace):
return compiled_re.sub(replace, x)
 def clean_spells(df, spells):
compiled_spells = re.compile('(%s)' % '|'.join(spells.keys()))
def replace(match):
return spells[match.group(0)]
df['question_text'] = df["question_text"].apply(
 lambda x: _clean_spells(x, compiled_spells, replace)
)
 return df
def _clean_spells(x, compiled_re, replace):
return compiled_re.sub(replace, x)
 def clean_abbreviation(df, abbreviations):
compiled_abbreviation = re.compile('(%s)' % '|'.join(abbreviations.keys()))
def replace(match):
return abbreviations[match.group(0)]
df['question_text'] = df["question_text"].apply(
 lambda x: _clean_abreviation(x, compiled_abbreviation, replace)
)
 return df
def _clean_abreviation(x, compiled_re, replace):
return compiled_re.sub(replace, x)
 def clean_space(df):
compiled_re = re.compile(r"\s+")
 df['question_text'] = df["question_text"].apply(lambda x: _clean_space(x, compiled_re))
return df
def _clean_space(x, compiled_re):
return compiled_re.sub(" ", x)
 def prepare_tokenizer(texts, max_words):
tokenizer = Tokenizer(num_words=max_words, filters='', oov_token='<unk>')
 tokenizer.fit_on_texts(list(texts))
return tokenizer
def tokenize_and_padding(texts, tokenizer, max_length):
texts = tokenizer.texts_to_sequences(texts)
 texts = pad_sequences(texts, maxlen=max_length)
 return texts
def get_all_vocabs(texts):
sentences = texts.apply(lambda x: x.split() ).values
vocab = {}
for sentence in sentences:
for word in sentence:
try:
vocab[word] += 1
except KeyError:
vocab[word] = 1
return vocab<feature_engineering>
LD_test = patients_tab_test.reset_index()
pred_cols = ['Patient', 'Weeks', 'Patient_Week', 'FVC_init_avg', 'init_week']
return_cols = ['Patient', 'Weeks', 'Patient_Week', 'FVC_hat', 'sigma']
def get_sigma_function(s_intercept, s_multiplier, s_power):
def alt_sigma(coeff, init_week):
coeff = abs(coeff)
 week_distance = abs(init_week)
 sigma = s_intercept + s_multiplier*coeff*(week_distance**s_power)
 return sigma
return alt_sigma
def pred_test(model, sigma_fn):
X = LD_test[linear_decay_features].copy()
XID = LD_test[['Patient']].copy()
XID['coeff_pred'] = model.predict(X, batch_size = 32)
 P = sub[pred_cols].copy()
P = P.merge(XID, how='left', on='Patient')
 P['FVC_hat'] = P['FVC_init_avg'] +(P['coeff_pred'] * P['init_week'])
 P['sigma'] = P.apply(lambda x: sigma_fn(x.coeff_pred, x.init_week), axis = 1)
 return P[return_cols]
def add_features(df):
df['question_text'] = df['question_text'].apply(lambda x:str(x))
df['lower_question_text'] = df['question_text'].apply(lambda x: x.lower())
 df['total_length'] = df['question_text'].apply(len)
 df['capitals'] = df['question_text'].apply(lambda comment: sum(1 for c in comment if c.isupper()))
df['caps_vs_length'] = df.apply(lambda row: float(row['capitals'])/float(row['total_length']), axis=1)
 df['num_words'] = df['question_text'].str.count('\S+')
 df['num_unique_words'] = df['question_text'].apply(lambda comment: len(set(comment.split())))
 df['words_vs_unique'] = df['num_unique_words'] / df['num_words']
return df[['caps_vs_length', 'words_vs_unique', 'num_words']]<load_pretrained>
for fold_num in range(5):
prefix = LD_inference.loc[fold_num].prefix
fname = '{}/{}_weights.h5'.format(pretrained_path, prefix)
 s_intercept, s_multiplier, s_power = eval(LD_inference.loc[fold_num].alt_sigma_param)
 f_sigma = get_sigma_function(s_intercept, s_multiplier, s_power)
 model = tf.keras.models.load_model(fname)
 P = pred_test(model, sigma_fn = f_sigma)
 PREDICTIONS['FVC_LD{}'.format(fold_num)] = P['FVC_hat']
PREDICTIONS['Confidence_LD{}'.format(fold_num)] = P['sigma']
del P, fold_num, fname, model
class Embeddings(nn.Module):
def __init__(self, config: Config, tokenizer, all_vocabs, embedding_weights = None):
super(Embeddings, self ).__init__()
self.embedding_map = {
'fasttext': self._load_fasttext,
'glove': self._load_glove,
'paragram': self._load_paragram
}
self.c = config
self.tokenizer = tokenizer
self.all_vocabs = all_vocabs
if embedding_weights is None:
embedding_weights = self._load_embeddings(self.c.embeddings)
 self.original_embedding_weights = embedding_weights
self.embeddings = nn.Embedding(self.c.vocab_size + 1, self.c.embedding_size, padding_idx=0)
 self.embeddings.weight = nn.Parameter(embedding_weights)
 self.embeddings.weight.requires_grad = False
self.embedding_dropout = nn.Dropout2d(self.c.embedding_dropout)
 def forward(self, x):
embedding = self.embeddings(x)
 if self.training:
embedding += torch.randn_like(embedding)* self.c.embedding_noise_var
return self.embedding_dropout(embedding.permute(0, 2, 1)).permute(0, 2, 1)
 def reset_weights(self):
self.embeddings.weight = nn.Parameter(self.original_embedding_weights)
 self.embeddings.weight.requires_grad = False
def _load_embeddings(self, embedding_list: list):
embedding_weights = np.zeros(( self.c.vocab_size, self.c.embedding_size))
pool = Pool(num_cores)
 embedding_weights = np.mean(pool.map(self._load_an_embedding, embedding_list), 0)
 pool.close()
pool.join()
return torch.tensor(embedding_weights, dtype=torch.float32)
 def _load_an_embedding(self, emb):
return self.embedding_map[emb](self.tokenizer.word_index)
 def _get_embeddings_pair(self, word, *arr):
return word, np.asarray(arr, dtype='float32')
 def _make_embeddings(self, embeddings_index, word_index, emb_mean, emb_std):
nb_words = min(self.c.vocab_size, len(word_index))
embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, self.c.embedding_size))
embedding_matrix[0] = np.zeros(self.c.embedding_size)
 for word, i in word_index.items() :
if i >= self.c.vocab_size:
continue
embedding_vector = embeddings_index.get(word)
 if embedding_vector is not None:
embedding_matrix[i] = embedding_vector
return embedding_matrix
def _load_glove(self, word_index):
print('loading glove')
 filepath = self.c.datadir / 'embeddings/glove.840B.300d/glove.840B.300d.txt'
embeddings_index = dict(
 self._get_embeddings_pair(*o.split(" "))
for o in open(filepath)
 if o.split(" ")[0] in word_index 
)
 emb_mean, emb_std = -0.005838499, 0.48782197
return self._make_embeddings(embeddings_index, word_index, emb_mean, emb_std)
 def _load_fasttext(self, word_index):
print('loading fasttext')
 filepath = self.c.datadir / 'embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec'
embeddings_index = dict(
 self._get_embeddings_pair(*o.split(" "))
for o in open(filepath)
 if len(o)> 100 and o.split(" ")[0] in word_index 
)
 emb_mean, emb_std = -0.0033469985, 0.109855495
return self._make_embeddings(embeddings_index, word_index, emb_mean, emb_std)
 def _load_paragram(self, word_index):
print('loading paragram')
 filepath = self.c.datadir / 'embeddings/paragram_300_sl999/paragram_300_sl999.txt'
embeddings_index = dict(
 self._get_embeddings_pair(*o.split(" "))
for o in open(filepath, encoding="utf8", errors='ignore')
 if len(o)> 100 and o.split(" ")[0] in word_index 
)
 emb_mean, emb_std = -0.0053247833, 0.49346462
return self._make_embeddings(embeddings_index, word_index, emb_mean, emb_std )<split>
QR_inference = pd.read_csv(pretrained_path + '/inference_quant_reg_2020Sep23.csv')
 QR_inference
num_cores = 2
@timer
def df_parallelize_run(df, func, num_cores=2):
df_split = np.array_split(df, num_cores)
 pool = Pool(num_cores)
 df = pd.concat(pool.map(func, df_split))
pool.close()
pool.join()
return df<prepare_x_and_y>
qr_features8 = ['fvc_init','week', 'sex_code', 'age', 'height', 'has_smoked', 'current_smoker', 'percent_init']
qr_features7 = ['fvc_init','week', 'sex_code', 'age', 'has_smoked', 'current_smoker', 'percent_init']
train_df, test_df = load_data(c.datadir)
 train_features = df_parallelize_run(train_df, add_features)
 test_features = df_parallelize_run(test_df, add_features)
 train_df = df_parallelize_run(train_df, clean)
 test_df = df_parallelize_run(test_df, clean)
 train_x, train_y = train_df['question_text'].values, train_df['target'].values
test_x = test_df['question_text'].values
tokenizer = prepare_tokenizer(train_x, c.vocab_size)
 train_x = tokenize_and_padding(train_x, tokenizer, c.max_length)
 test_x = tokenize_and_padding(test_x, tokenizer, c.max_length )<normalization>
for fold_num in range(5):
prefix = QR_inference.loc[fold_num].prefix
fname = '{}/{}_weights.h5'.format(pretrained_path, prefix)
 model = tf.keras.models.load_model(fname, compile = False)
 model.compile(loss='mae', optimizer='adam', metrics=['mae'])
 num_features = QR_inference.loc[fold_num].num_features
if num_features == 7: features = qr_features7
else: features = qr_features8
X = sub[features].copy()
preds = model.predict(X)
 PREDICTIONS['FVC_QR{}'.format(fold_num)] = preds[:,1]
PREDICTIONS['Confidence_QR{}'.format(fold_num)] = preds[:,2] - preds[:,0]
del X, fold_num, fname, model, prefix, num_features, features, preds
ss = StandardScaler()
ss.fit(np.vstack(( train_features, test_features)))
 train_features = ss.transform(train_features)
 test_features = ss.transform(test_features )<categorify>
QR_FVC_cols = [col for col in PREDICTIONS.columns if 'FVC_QR' in col]
LD_FVC_cols = [col for col in PREDICTIONS.columns if 'FVC_LD' in col]
QR_Conf_cols = [col for col in PREDICTIONS.columns if 'Confidence_QR' in col]
LD_Conf_cols = [col for col in PREDICTIONS.columns if 'Confidence_LD' in col]
PREDICTIONS['QR_FVC_mean'] = PREDICTIONS[QR_FVC_cols].mean(axis = 1)
 PREDICTIONS['QR_Conf_mean'] = PREDICTIONS[QR_Conf_cols].mean(axis = 1)
 PREDICTIONS['LD_FVC_mean'] = PREDICTIONS[LD_FVC_cols].mean(axis = 1)
 PREDICTIONS['LD_Conf_mean'] = PREDICTIONS[LD_Conf_cols].mean(axis = 1)
 PREDICTIONS['QR_LD_FVC_mean'] = PREDICTIONS[['QR_FVC_mean','LD_FVC_mean']].mean(axis = 1)
 PREDICTIONS['QR_LD_Conf_mean'] = PREDICTIONS[['QR_Conf_mean','LD_Conf_mean']].mean(axis = 1 )
start = time.time()
all_vocabs = get_all_vocabs(train_df['question_text'])
 print('all_vocabs: ', len(all_vocabs))
embeddings = Embeddings(c, tokenizer, all_vocabs)
 print(time.time() - start )<choose_model_class>
to_submit = PREDICTIONS[['Patient_Week','QR_LD_FVC_mean', 'QR_LD_Conf_mean']]
to_submit.columns = ['Patient_Week','FVC','Confidence']
to_submit
<choose_model_class><EOS> 
to_submit.to_csv('submission.csv', index=False )