Kaggle competition: Recruit Restaurant Visitor Forecasting
%%time
with multiprocessing.Pool(processes=2)as pool:
sequences = np.array(pool.map(convert_line_gpt2, test.comment_text))
lengths = np.argmax(sequences == 0, axis=1)
 lengths[lengths == 0] = sequences.shape[1]
sequences = torch.from_numpy(sequences)
 lengths = torch.from_numpy(lengths)
 test_dataset = data.TensorDataset(sequences, lengths)
 test_loader = data.DataLoader(test_dataset, batch_size=64, collate_fn=clip_to_max_len )<load_pretrained>
print(dirname+'/sample_submission.csv')
 test_df = pd.read_csv(dirname+'/sample_submission.csv')
 test_df.head(20)
%%time
GPT2CNN_MODELS = [
"BERT_exp_GPT2_CNN_epoch_1",
"BERT_exp_GPT2_CNN_seed_epoch_1",
]
for path in GPT2CNN_MODELS:
model = GPT2CNN(GPT2Config() , num_labels=18)
 model.load_state_dict(
 torch.load(f".. /input/toxic-models-zoo/{path}.bin", map_location="cpu")
)
 for p in model.parameters() :
p.requires_grad = False
model = model.eval()
model = model.cuda()
preds = apply_gpt(model, test_loader)
 STORE[path] = sophisticated_magic(preds )<create_dataframe>
test_df['store_id'] = test_df['id'].str[:20]
test_df['visit_date'] = test_df['id'].str[21:]
test_df.drop(['visitors'],axis=1,inplace=True)
 test_df['visit_date'] = pd.to_datetime(test_df['visit_date'])
 test_df.info()
test_df.head()
df = pd.DataFrame(STORE )<define_variables>
air_data = pd.read_csv(dirname+'/air_visit_data.csv',parse_dates=['visit_date'])
 air_data.shape
air_data.head()
final_preds =(
 4.5 * df["lstm"] +
df["BERT_exp_BERT_3_decay_5_epoch_1"] +
df["BERT_exp_BERT_3_cased_decay_epoch_1"] +
2 * df["BERT_exp_GPT2_CNN_epoch_1"] +
2 * df["BERT_exp_GPT2_CNN_seed_epoch_1"] +
df["final-pipe1-raw_1"] +
df["final-pipe1-raw_2"] +
df["final-pipe1-raw_3"] +
df["final-pipe2-raw_1"] +
df["final-pipe2-raw_2"] +
df["final-pipe2-raw_3"] +
df["final-pipe2-cased_1"] +
df["final-pipe2-cased_2"] +
df["final-pipe2-cased_3"] +
df["final-pipe4-wiki_raw_1"] +
df["final-pipe4-wiki_raw_2"] +
df["final-pipe4-wiki_raw_3"] +
df["final-pipe5-wiki_cased_1"] +
df["final-pipe5-wiki_cased_2"] +
df["final-pipe5-wiki_cased_3"] +
df["final-pipe2-raw_4"] +
df["final-pipe2-cased_10"] +
df["BERT_exp_BERT_3_epoch_1"]
)<create_dataframe>
air_data['dow']=air_data['visit_date'].dt.dayofweek
train=air_data[air_data['visit_date']>'2017-01-28'].reset_index()
train['dow']=train['visit_date'].dt.dayofweek
test_df['dow']=test_df['visit_date'].dt.dayofweek
test_df.head()
train.head()
submission = pd.DataFrame({
'id': test['id'],
'prediction': final_preds,
} )<save_to_csv>
aggregation={'visitors':'median'}
agg_data=train.groupby(['air_store_id','dow'] ).agg(aggregation ).reset_index()
agg_data.colums=['air_store_id','dow','visitors']
agg_data['visitors']=agg_data['visitors']
agg_data.head(12 )
submission.to_csv('submission.csv', index=False )<save_to_csv>
marged=pd.merge(test_df,agg_data,how='left',left_on=['store_id','dow'],right_on=['air_store_id','dow'])
 marged.head()
final = marged[['id','visitors']]
final.head()
submission.to_csv('submission.csv', index=False )<find_best_params>
def missing_values_table(df):
mis_val = df.isnull().sum()
mis_val_percent=100*df.isnull().sum() /len(df)
 mis_val_table=pd.concat([mis_val,mis_val_percent],axis=1)
 mis_val_table_ren_columns=mis_val_table.rename(
 columns={0:'MisiingValues',1:'% of Total Values'})
 return mis_val_table_ren_columns
missing_values_table(final )
print(torch.cuda.max_memory_allocated(0)/ 1024 / 1024)
 print(torch.cuda.max_memory_cached(0)/ 1024 / 1024 )<set_options>
final.fillna(0,inplace=True)
 missing_values_table(final )
%reload_ext autoreload
%autoreload 2
%matplotlib inline
pd.set_option('max_colwidth',400)
 pd.set_option('max_columns', 50)
<string_transform>
dfs = { re.search('/([^/\.]*)\.csv', fn ).group(1):pd.read_csv(fn)for fn in glob.glob(dirname+'/*.csv')}
for k, v in dfs.items() : locals() [k] = v
print('data frames read:{}'.format(list(dfs.keys())))
def convert_lines(example, max_seq_length,tokenizer):
max_seq_length -=2
all_tokens = []
longer = 0
for text in tqdm(example):
tokens_a = tokenizer.tokenize(text)
 if len(tokens_a)>max_seq_length:
tokens_a = tokens_a[:max_seq_length]
longer += 1
one_token = tokenizer.convert_tokens_to_ids(["[CLS]"]+tokens_a+["[SEP]"])+[0] *(max_seq_length - len(tokens_a))
all_tokens.append(one_token)
 return np.array(all_tokens)
 def is_interactive() :
return 'SHLVL' not in os.environ
def seed_everything(seed=123):
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
def get_coefs(word, *arr):
return word, np.asarray(arr, dtype='float32')
 def load_embeddings(path):
emb_arr = KeyedVectors.load(path)
 return emb_arr
def build_matrix(word_index, path, dim=300):
embedding_index = load_embeddings(path)
 embedding_matrix = np.zeros(( max_features + 1, dim))
unknown_words = []
for word, i in word_index.items() :
if i <= max_features:
try:
embedding_matrix[i] = embedding_index[word]
except KeyError:
try:
embedding_matrix[i] = embedding_index[word.lower() ]
except KeyError:
try:
embedding_matrix[i] = embedding_index[word.title() ]
except KeyError:
unknown_words.append(word)
 return embedding_matrix, unknown_words
def sigmoid(x):
return 1 /(1 + np.exp(-x))
class SpatialDropout(nn.Dropout2d):
def forward(self, x):
x = x.unsqueeze(2)
 x = x.permute(0, 3, 2, 1)
 x = super(SpatialDropout, self ).forward(x)
 x = x.permute(0, 3, 2, 1)
 x = x.squeeze(2)
 return x
def handle_punctuation(x):
x = x.translate(remove_dict)
 x = x.translate(isolate_dict)
 return x
def handle_contractions(x):
x = tokenizer.tokenize(x)
 return x
def fix_quote(x):
x = [x_[1:] if x_.startswith("'")else x_ for x_ in x]
x = ' '.join(x)
 return x
def preprocess(x):
x = handle_punctuation(x)
 x = handle_contractions(x)
 x = fix_quote(x)
 return x
class SequenceBucketCollator() :
def __init__(self, choose_length, sequence_index, length_index, label_index=None):
self.choose_length = choose_length
self.sequence_index = sequence_index
self.length_index = length_index
self.label_index = label_index
def __call__(self, batch):
batch = [torch.stack(x)for x in list(zip(*batch)) ]
sequences = batch[self.sequence_index]
lengths = batch[self.length_index]
length = self.choose_length(lengths)
 mask = torch.arange(start=maxlen, end=0, step=-1)< length
padded_sequences = sequences[:, mask]
batch[self.sequence_index] = padded_sequences
if self.label_index is not None:
return [x for i, x in enumerate(batch)if i != self.label_index], batch[self.label_index]
return batch
class SoftmaxPooling(nn.Module):
def __init__(self, dim=1):
super(self.__class__, self ).__init__()
self.dim = dim
def forward(self, x):
return(x * x.softmax(dim=self.dim)).sum(dim=self.dim)
 class NeuralNet(nn.Module):
def __init__(self, embedding_matrix, num_aux_targets):
super(NeuralNet, self ).__init__()
embed_size = embedding_matrix.shape[1]
self.embedding = nn.Embedding(max_features, embed_size)
 self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32))
self.embedding.weight.requires_grad = False
self.embedding_dropout = SpatialDropout(0.3)
 self.lstm1 = nn.LSTM(embed_size, LSTM_UNITS, bidirectional=True, batch_first=True)
 self.lstm2 = nn.LSTM(LSTM_UNITS * 2, LSTM_UNITS, bidirectional=True, batch_first=True)
 self.linear_out = nn.Sequential(
 nn.Dropout(0.5),
nn.BatchNorm1d(DENSE_HIDDEN_UNITS),
nn.Linear(DENSE_HIDDEN_UNITS, 1)
)
 self.linear_aux_out = nn.Sequential(
 nn.Dropout(0.5),
nn.BatchNorm1d(DENSE_HIDDEN_UNITS),
nn.Linear(DENSE_HIDDEN_UNITS, num_aux_targets)
)
 self.softmaxpool = SoftmaxPooling()
def forward(self, x, lengths=None):
h_embedding = self.embedding(x.long())
 h_embedding = self.embedding_dropout(h_embedding)
 h_lstm1, _ = self.lstm1(h_embedding)
 h_lstm2, _ = self.lstm2(h_lstm1)
 avg_pool = torch.mean(h_lstm2, 1)
 max_pool, _ = torch.max(h_lstm2, 1)
 soft_pool = self.softmaxpool(h_lstm2)
 h_conc = torch.cat(( max_pool, avg_pool, soft_pool), 1)
 hidden = h_conc
result = self.linear_out(hidden)
 aux_result = self.linear_aux_out(hidden)
 out = torch.cat([result, aux_result], 1)
 return out
def custom_loss(data, targets):
bce_loss_1 = nn.BCEWithLogitsLoss(weight=targets[:,1:2] )(data[:,:1],targets[:,:1])
 bce_loss_2 = nn.BCEWithLogitsLoss()(data[:,1:],targets[:,2:])
 return(bce_loss_1 * loss_weight)+ bce_loss_2
def reduce_mem_usage(df):
start_mem = df.memory_usage().sum() / 1024**2
print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))
for col in df.columns:
col_type = df[col].dtype
if col_type != object:
c_min = df[col].min()
c_max = df[col].max()
if str(col_type)[:3] == 'int':
if c_min > np.iinfo(np.int8 ).min and c_max < np.iinfo(np.int8 ).max:
df[col] = df[col].astype(np.int8)
 elif c_min > np.iinfo(np.int16 ).min and c_max < np.iinfo(np.int16 ).max:
df[col] = df[col].astype(np.int16)
 elif c_min > np.iinfo(np.int32 ).min and c_max < np.iinfo(np.int32 ).max:
df[col] = df[col].astype(np.int32)
 elif c_min > np.iinfo(np.int64 ).min and c_max < np.iinfo(np.int64 ).max:
df[col] = df[col].astype(np.int64)
 else:
if c_min > np.finfo(np.float16 ).min and c_max < np.finfo(np.float16 ).max:
df[col] = df[col].astype(np.float16)
 elif c_min > np.finfo(np.float32 ).min and c_max < np.finfo(np.float32 ).max:
df[col] = df[col].astype(np.float32)
 else:
df[col] = df[col].astype(np.float64)
 else:
df[col] = df[col].astype('category')
 end_mem = df.memory_usage().sum() / 1024**2
print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))
print('Decreased by {:.1f}%'.format(100 *(start_mem - end_mem)/ start_mem))
return df
def ensemble_predictions(predictions, weights, type_="linear", axis=1):
assert np.isclose(np.sum(weights), 1.0)
 if type_ == "linear":
res = np.average(predictions, weights=weights, axis=axis)
 elif type_ == "harmonic":
res = np.average([1 / p for p in predictions], weights=weights, axis=axis)
 return 1 / res
elif type_ == "geometric":
numerator = np.average(
 [np.log(p)for p in predictions], weights=weights, axis=axis 
)
 res = np.exp(numerator / sum(weights))
return res
elif type_ == "rank":
res = np.average([rankdata(p)for p in predictions], weights=weights, axis=axis)
 return res /(len(res)+ 1)
 return res<define_variables>
weekend_hdays=date_info.apply(( lambda x:(x.day_of_week=='Sunday' or x.day_of_week=='Saturday')and x.holiday_flg==1),axis=1)
 date_info.loc[weekend_hdays, 'holiday_flg']=0
warnings.filterwarnings(action='once')
 device = torch.device('cuda')
 SEED = 1234
BATCH_SIZE = 512
np.random.seed(SEED)
 torch.manual_seed(SEED)
 torch.cuda.manual_seed(SEED)
 torch.backends.cudnn.deterministic = True
tqdm.pandas()
CRAWL_EMBEDDING_PATH = '.. /input/gensim-embeddings-dataset/crawl-300d-2M.gensim'
NUMBERBATCH_EMBEDDING_PATH = '.. /input/gensim-embeddings-dataset/numberbatch-en.gensim'
PARAGRAM_EMBEDDING_PATH = '.. /input/gensim-embeddings-dataset/paragram_300_sl999.gensim'
TWITTER_EMBEDDING_PATH = '.. /input/gensim-embeddings-dataset/glove.twitter.27B.200d.gensim'
if not is_interactive() :
def nop(it, *a, **k):
return it
tqdm = nop
fastprogress.fastprogress.NO_BAR = True
master_bar, progress_bar = force_console_behavior()
fastai.basic_train.master_bar, fastai.basic_train.progress_bar = master_bar, progress_bar
seed_everything()<define_variables>
date_info['weight']=(date_info.index+1)/len(date_info)
 date_info.head()
date_info.tail()
LSTM_UNITS = 128
DENSE_HIDDEN_UNITS = 768<load_from_csv>
visit_data=air_visit_data.merge(date_info,left_on='visit_date',right_on='calendar_date',how='left')
 visit_data.drop('calendar_date',axis=1,inplace=True)
 visit_data['visitors']=visit_data.visitors.map(pd.np.log1p)
 visit_data.head(10 )
tokenizer = TreebankWordTokenizer()
test_df = pd.read_csv(".. /input/jigsaw-unintended-bias-in-toxicity-classification/test.csv")
 test_df['comment_text'] = test_df['comment_text'].astype(str )<define_variables>
sample_submission['air_store_id']=sample_submission.id.map(
 lambda x:'_'.join(x.split('_')[:-1]))
sample_submission['calendar_date']=sample_submission.id.map(lambda x: x.split('_')[2])
 sample_submission.drop('visitors',axis=1,inplace=True)
 sample_submission=sample_submission.merge(date_info, on='calendar_date',how='left')
 sample_submission=sample_submission.merge(
 visitors, on=['air_store_id','day_of_week','holiday_flg'],how='left')
 sample_submission.head(10 )
symbols_to_isolate = '.,?!-;*"…:—() %
symbols_to_delete = '
🍕\r🐵😑\xa0\ue014\t\uf818\uf04a\xad😢🐶️\uf0e0😜😎👊\u200b\u200e😁عدويهصقأناخلىبمغر😍💖💵Е👎😀😂\u202a\u202c🔥😄🏻💥ᴍʏʀᴇɴᴅᴏᴀᴋʜᴜʟᴛᴄᴘʙғᴊᴡɢ😋👏שלוםבי😱‼\x81エンジ故障\u2009🚌ᴵ͞🌟😊😳😧🙀😐😕\u200f👍😮😃😘אעכח💩💯⛽🚄🏼ஜ😖ᴠ🚲‐😟😈💪🙏🎯🌹😇💔😡\x7f👌ἐὶήιὲκἀίῃἴξ🙄Ｈ😠\ufeff\u2028😉😤⛺🙂\u3000تحكسة👮💙فزط😏🍾🎉😞\u2008🏾😅😭👻😥😔😓🏽🎆🍻🍽🎶🌺🤔😪\x08‑🐰🐇🐱🙆😨🙃💕𝘊𝘦𝘳𝘢𝘵𝘰𝘤𝘺𝘴𝘪𝘧𝘮𝘣💗💚地獄谷улкнПоАН🐾🐕😆ה🔗🚽歌舞伎🙈😴🏿🤗🇺🇸мυтѕ⤵🏆🎃😩\u200a🌠🐟💫💰💎эпрд\x95🖐🙅⛲🍰🤐👆🙌\u2002💛🙁👀🙊🙉\u2004ˢᵒʳʸᴼᴷᴺʷᵗʰᵉᵘ\x13🚬🤓\ue602😵άοόςέὸתמדףנרךצט😒͝🆕👅👥👄🔄🔤👉👤👶👲🔛🎓\uf0b7\uf04c\x9f\x10成都😣⏺😌🤑🌏😯ех😲Ἰᾶὁ💞🚓🔔📚🏀👐\u202d💤🍇\ue613小土豆🏡❔⁉\u202f👠》कर्मा🇹🇼🌸蔡英文🌞🎲レクサス😛外国人关系Сб💋💀🎄💜🤢َِьыгя不是\x9c\x9d🗑\u2005💃📣👿༼つ༽😰ḷЗз▱ц￼🤣卖温哥华议会下降你失去所有的钱加拿大坏税骗子🐝ツ🎅\x85🍺آإشء🎵🌎͟ἔ油别克🤡🤥😬🤧й\u2003🚀🤴ʲшчИОРФДЯМюж😝🖑ὐύύ特殊作戦群щ💨圆明园קℐ🏈😺🌍⏏ệ🍔🐮🍁🍆🍑🌮🌯🤦\u200d𝓒𝓲𝓿𝓵안영하세요ЖљКћ🍀😫🤤ῦ我出生在了可以说普通话汉语好极🎼🕺🍸🥂🗽🎇🎊🆘🤠👩🖒🚪天一家⚲\u2006⚭⚆⬭⬯⏖新✀╌🇫🇷🇩🇪🇮🇬🇧😷🇨🇦ХШ🌐\x1f杀鸡给猴看ʁ𝗪𝗵𝗲𝗻𝘆𝗼𝘂𝗿𝗮𝗹𝗶𝘇𝗯𝘁𝗰𝘀𝘅𝗽𝘄𝗱📺ϖ\u2000үսᴦᎥһͺ\u2007հ\u2001ɩｙｅ൦ｌƽｈ𝐓𝐡𝐞𝐫𝐮𝐝𝐚𝐃𝐜𝐩𝐭𝐢𝐨𝐧Ƅᴨןᑯ໐ΤᏧ௦Іᴑ܁𝐬𝐰𝐲𝐛𝐦𝐯𝐑𝐙𝐣𝐇𝐂𝐘𝟎ԜТᗞ౦〔Ꭻ𝐳𝐔𝐱𝟔𝟓𝐅🐋ﬃ💘💓ё𝘥𝘯𝘶💐🌋🌄🌅𝙬𝙖𝙨𝙤𝙣𝙡𝙮𝙘𝙠𝙚𝙙𝙜𝙧𝙥𝙩𝙪𝙗𝙞𝙝𝙛👺🐷ℋ𝐀𝐥𝐪🚶𝙢Ἱ🤘ͦ💸ج패티Ｗ𝙇ᵻ👂👃ɜ🎫\uf0a7БУі🚢🚂ગુજરાતીῆ🏃𝓬𝓻𝓴𝓮𝓽𝓼☘﴾̯﴿₽\ue807𝑻𝒆𝒍𝒕𝒉𝒓𝒖𝒂𝒏𝒅𝒔𝒎𝒗𝒊👽😙\u200cЛ‒🎾👹⎌🏒⛸公寓养宠物吗🏄🐀🚑🤷操美𝒑𝒚𝒐𝑴🤙🐒欢迎来到阿拉斯ספ𝙫🐈𝒌𝙊𝙭𝙆𝙋𝙍𝘼𝙅ﷻ🦄巨收赢得白鬼愤怒要买额ẽ🚗🐳𝟏𝐟𝟖𝟑𝟕𝒄𝟗𝐠𝙄𝙃👇锟斤拷𝗢𝟳𝟱𝟬⦁マルハニチロ株式社⛷한국어ㄸㅓ니͜ʖ𝘿𝙔₵𝒩ℯ𝒾𝓁𝒶𝓉𝓇𝓊𝓃𝓈𝓅ℴ𝒻𝒽𝓀𝓌𝒸𝓎𝙏ζ𝙟𝘃𝗺𝟮𝟭𝟯𝟲👋🦊多伦🐽🎻🎹⛓🏹🍷🦆为和中友谊祝贺与其想象对法如直接问用自己猜本传教士没积唯认识基督徒曾经让相信耶稣复活死怪他但当们聊些政治题时候战胜因圣把全堂结婚孩恐惧且栗谓这样还♾🎸🤕🤒⛑🎁批判检讨🏝🦁🙋😶쥐스탱트뤼도석유가격인상이경제황을렵게만들지않록잘관리해야합다캐나에서대마초와화약금의품런성분갈때는반드시허된사용🔫👁凸ὰ💲🗯𝙈Ἄ𝒇𝒈𝒘𝒃𝑬𝑶𝕾𝖙𝖗𝖆𝖎𝖌𝖍𝖕𝖊𝖔𝖑𝖉𝖓𝖐𝖜𝖞𝖚𝖇𝕿𝖘𝖄𝖛𝖒𝖋𝖂𝕴𝖟𝖈𝕸👑🚿💡知彼百\uf005𝙀𝒛𝑲𝑳𝑾𝒋𝟒😦𝙒𝘾𝘽🏐𝘩𝘨ὼṑ𝑱𝑹𝑫𝑵𝑪🇰🇵👾ᓇᒧᔭᐃᐧᐦᑳᐨᓃᓂᑲᐸᑭᑎᓀᐣ🐄🎈🔨🐎🤞🐸💟🎰🌝🛳点击查版🍭𝑥𝑦𝑧ＮＧ👣\uf020っ🏉ф💭🎥Ξ🐴👨🤳🦍\x0b🍩𝑯𝒒😗𝟐🏂👳🍗🕉🐲چی𝑮𝗕𝗴🍒ꜥⲣⲏ🐑⏰鉄リ事件ї💊「」\uf203\uf09a\uf222\ue608\uf202\uf099\uf469\ue607\uf410\ue600燻製シ虚偽屁理屈Г𝑩𝑰𝒀𝑺🌤𝗳𝗜𝗙𝗦𝗧🍊ὺἈἡχῖΛ⤏🇳𝒙ψՁմեռայինրւդձ冬至ὀ𝒁🔹🤚🍎𝑷🐂💅𝘬𝘱𝘸𝘷𝘐𝘭𝘓𝘖𝘹𝘲𝘫کΒώ💢ΜΟΝΑΕ🇱♲𝝈↴💒⊘Ȼ🚴🖕🖤🥘📍👈➕🚫🎨🌑🐻𝐎𝐍𝐊𝑭🤖🎎😼🕷ｇｒｎｔｉｄｕｆｂｋ𝟰🇴🇭🇻🇲𝗞𝗭𝗘𝗤👼📉🍟🍦🌈🔭《🐊🐍\uf10aლڡ🐦\U0001f92f\U0001f92a🐡💳ἱ🙇𝗸𝗟𝗠𝗷🥜さようなら🔼'<define_variables>
missing_values_table(sample_submission )
isolate_dict = {ord(c):f' {c} ' for c in symbols_to_isolate}
remove_dict = {ord(c):f'' for c in symbols_to_delete}<init_hyperparams>
missings=sample_submission.visitors.isnull()
sample_submission.loc[missings,'visitors']=sample_submission[missings].merge(
 visitors[visitors.holiday_flg==0],on=('air_store_id','day_of_week'), how='left')['visitors_y'].values
missing_values_table(sample_submission )
x_test = test_df['comment_text'].progress_apply(lambda x:preprocess(x))
loss_weight = 3.209226860170181
max_features = 400000<string_transform>
missings=sample_submission.visitors.isnull()
sample_submission.loc[missings,'visitors']=sample_submission[missings].merge(
 visitors[['air_store_id','visitors']].groupby('air_store_id' ).mean().reset_index() ,on='air_store_id',how='left')['visitors_y'].values
missing_values_table(sample_submission )
tokenizer = text.Tokenizer(num_words = max_features, filters='',lower=False )<load_pretrained>
sample_submission['visitors']=sample_submission.visitors.map(pd.np.expm1)
 sample_submission=sample_submission[['id','visitors']]
final['visitors'][final['visitors']==0]=sample_submission['visitors'][final['visitors']==0]
sub_file=final.copy()
sub_file.head()
with open('.. /input/bilstm-crawl-paragram-0/tokenizer.pickle', 'rb')as handle:
tokenizer = pickle.load(handle)
 crawl_matrix, unknown_words_crawl = build_matrix(tokenizer.word_index, CRAWL_EMBEDDING_PATH)
 print('n unknown words(crawl): ', len(unknown_words_crawl))
paragram_matrix, unknown_words_paragram = build_matrix(tokenizer.word_index, PARAGRAM_EMBEDDING_PATH)
 print('n unknown words(paragram): ', len(unknown_words_paragram))
max_features = max_features or len(tokenizer.word_index)+ 1
max_features
embedding_matrix = np.concatenate([crawl_matrix, paragram_matrix], axis=-1)
 embedding_matrix.shape
del crawl_matrix
del paragram_matrix
gc.collect()<string_transform>
sub_file['visitors']=np.mean([final['visitors'],sample_submission['visitors']],axis=0)
 sub_file.to_csv('sub_math_mean_1.csv',index=False)
 sub_file['visitors']=(final['visitors']*sample_submission['visitors'])**(1/2)
 sub_file.to_csv('sub_geo_mean_1.csv',index=False)
 sub_file['visitors']=2/(1/final['visitors']+1/sample_submission['visitors'])
 sub_file.to_csv('sub_hrm_mean_1.csv',index=False)