Kaggle competition: Traveling Santa 2018 - Prime Paths
<SOS> metric: TravelingSanta2 Kaggle data source: traveling-santa-2018-prime-paths<compute_test_metric>
import numpy as np
import pandas as pd
import numba
from sympy import isprime, primerange
from math import sqrt
from sklearn.neighbors import KDTree
from tqdm import tqdm
from itertools import combinations
y_pred_all = np.mean(np.array([y_pred_glove,y_pred_paragram,y_pred_wiki]),axis=0)
 print(y_pred_all.shape)
 final_thresh = optim_thres(y_val,y_pred_all )<save_to_csv>
cities = pd.read_csv('.. /input/traveling-santa-2018-prime-paths/cities.csv', index_col=['CityId'])
 XY = np.stack(( cities.X.astype(np.float32), cities.Y.astype(np.float32)) , axis=1)
 is_not_prime = np.array([0 if isprime(i)else 1 for i in cities.index], dtype=np.int32 )
final_pred = np.mean(np.array([pred_glove,pred_paragram,pred_wiki]),axis=0)
 sub_pred =(final_pred > final_thresh ).astype(int)
 sub = pd.DataFrame({"qid":df_test["qid"].values})
 sub['prediction'] = sub_pred
sub.to_csv("submission.csv", index=False )<load_from_csv>
@numba.jit('f8(i8, i8, i8)', nopython=True, parallel=False)
 def cities_distance(offset, id_from, id_to):
xy_from, xy_to = XY[id_from], XY[id_to]
dx, dy = xy_from[0] - xy_to[0], xy_from[1] - xy_to[1]
distance = sqrt(dx * dx + dy * dy)
 if offset % 10 == 9 and is_not_prime[id_from]:
return 1.1 * distance
return distance
@numba.jit('f8(i4, i8[:])', nopython=True, parallel=False)
 def score_chunk(offset, chunk):
pure_distance, penalty = 0.0, 0.0
penalty_modulo = 9 - offset % 10
for path_index in numba.prange(chunk.shape[0] - 1):
id_from, id_to = chunk[path_index], chunk[path_index+1]
xy_from, xy_to = XY[id_from], XY[id_to]
dx, dy = xy_from[0] - xy_to[0], xy_from[1] - xy_to[1]
distance = sqrt(dx * dx + dy * dy)
 pure_distance += distance
if path_index % 10 == penalty_modulo and is_not_prime[id_from]:
penalty += distance
return pure_distance + 0.1 * penalty
@numba.jit('f8(i8[:])', nopython=True, parallel=False)
 def score_path(path):
return score_chunk(0, path )
train_df = pd.read_csv(".. /input/train.csv")
 test_df = pd.read_csv(".. /input/test.csv")
 print("Train shape : ",train_df.shape)
 print("Test shape : ",test_df.shape )<split>
kdt = KDTree(XY )
%%time
train_df, val_df = train_test_split(train_df, test_size=0.1, random_state=2018)
 embed_size = 300
max_features = 100000
maxlen = 70
train_X = train_df["question_text"].fillna("_na_" ).values
val_X = val_df["question_text"].fillna("_na_" ).values
test_X = test_df["question_text"].fillna("_na_" ).values
tokenizer = Tokenizer(num_words=max_features)
 tokenizer.fit_on_texts(list(train_X))
train_X = tokenizer.texts_to_sequences(train_X)
 val_X = tokenizer.texts_to_sequences(val_X)
 test_X = tokenizer.texts_to_sequences(test_X)
 train_X = pad_sequences(train_X, maxlen=maxlen)
 val_X = pad_sequences(val_X, maxlen=maxlen)
 test_X = pad_sequences(test_X, maxlen=maxlen)
 train_y = train_df['target'].values
val_y = val_df['target'].values<train_model>
path = np.array(pd.read_csv('.. /input/gpu-shuffle-numba-cuda/submission.csv' ).Path)
 initial_score = score_path(path )
model.fit(train_X, train_y, batch_size=512, epochs=3, validation_data=(val_X, val_y))<predict_on_test>
path_index = np.argsort(path[:-1])
 total_score = initial_score
print(f'Total score is {total_score:.2f}.')
 for _ in range(3):
for step,(id1, id2)in enumerate(tqdm(pairs), 1):
if step % 10**6 == 0:
new_total_score = score_path(path)
 print(f'Score: {new_total_score:.2f}; improvement over last 10^6 steps: {total_score - new_total_score:.2f}; total improvement: {initial_score - new_total_score:.2f}.')
 total_score = new_total_score
i, j = path_index[id1], path_index[id2]
i, j = min(i, j), max(i, j)
 chunk, reversed_chunk = path[i-1:j+2], np.concatenate([path[i-1:i], path[j:i-1:-1], path[j+1:j+2]])
 chunk_score, reversed_chunk_score = score_chunk(i-1, chunk), score_chunk(i-1, reversed_chunk)
 if j - i > 2:
chunk_abc = np.concatenate([path[i-1:i+1], path[j:i:-1], path[j+1:j+2]])
 chunk_acb = np.concatenate([path[i-1:i], path[j:j+1], path[i:j], path[j+1:j+2]])
 chunk_abcb = np.concatenate([path[i-1:i+1], path[j:j+1], path[i+1:j], path[j+1:j+2]])
 abc_score, acb_score, abcb_score = map(lambda chunk: score_chunk(i-1, chunk), [chunk_abc, chunk_acb, chunk_abcb])
 for chunk, score, name in zip(( chunk_abc, chunk_acb, chunk_abcb),(abc_score, acb_score, abcb_score),('abc', 'acb', 'abcb')) :
if score < chunk_score:
path[i-1:j+2] = chunk
path_index = np.argsort(path[:-1])
 chunk_score = score
if reversed_chunk_score < chunk_score:
path[i-1:j+2] = reversed_chunk
path_index = np.argsort(path[:-1] )
pred_noemb_val_y = model.predict([val_X], batch_size=1024, verbose=1)[:,0]<compute_test_metric>
print(f'Total improvement is {initial_score - total_score:.2f}.' )
thresh = 0.50
pred_noemb_val_y_int = pred_noemb_val_y > thresh
print('ค่า accuracy เท่ากับ %.4f' %(sum(pred_noemb_val_y_int == val_y)/len(val_y)))
 print('ค่า F1 เท่ากับ %.4f' %(metrics.f1_score(val_y,(pred_noemb_val_y>thresh ).astype(int))))<compute_test_metric>
def make_submission(name, path):
pd.DataFrame({'Path': path} ).to_csv(f'{name}.csv', index=False )
<filter><EOS> 
make_submission(score_path(path), path )