Kaggle competition: Traveling Santa 2018 - Prime Paths
<SOS> metric: TravelingSanta2 Kaggle data source: traveling-santa-2018-prime-paths<choose_model_class>
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, permutations
from functools import lru_cache
learn = Learner(data, model,
loss_func=FocalLoss() ,
metrics=[accuracy, KappaScore(weights="quadratic")],
callback_fns=[BnFreeze,
partial(SaveModelCallback, monitor='kappa_score', name='best_kappa')] 
)
 learn.split(lambda m:(model._conv_head,))
learn.freeze()
learn.model_dir = '/tmp/'<load_pretrained>
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 )
learn.freeze()
learn.lr_find(start_lr=1e-5, end_lr=1e1, wd=5e-3)
 learn.recorder.plot(suggestion=True )<train_model>
@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)
 @numba.jit
def chunk_scores(chunk):
scores = np.zeros(10)
 pure_distance = 0
for i in numba.prange(chunk.shape[0] - 1):
id_from, id_to = chunk[i], chunk[i+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 is_not_prime[id_from]:
scores[9-i%10] += distance
scores *= 0.1
scores += pure_distance
return scores
def score_compound_chunk(offset, head, chunks, tail, scores, indexes_permutation=None):
if indexes_permutation is None:
indexes_permutation = range(len(chunks))
score = 0.0
last_city_id = head
for index in indexes_permutation:
chunk, chunk_scores = chunks[index], scores[index]
score += cities_distance(offset % 10, last_city_id, chunk[0])
 score += chunk_scores[(offset + 1)% 10]
last_city_id = chunk[-1]
offset += len(chunk)
 return score + cities_distance(offset % 10, last_city_id, tail)
learn.fit_one_cycle(1, max_lr=3e-3, pct_start=0.1, div_factor=10, final_div=30, wd=5e-3, moms=(0.9, 0.8))
learn.save('stage-1')
 learn.recorder.plot_losses()<train_model>
kdt = KDTree(XY )
learn.fit_one_cycle(3, max_lr=slice(1e-4, 1e-3), div_factor=50, final_div=100, wd=1e-3, moms=(0.9, 0.8))
learn.save('stage-2')
 learn.recorder.plot_losses()
learn.recorder.plot_lr(show_moms=True )<train_model>
path = np.array(pd.read_csv('.. /input/better-input-for-aka-2-opt/1515905.0538262606.csv' ).Path )
tta_params = {'beta':0.12, 'scale':1.0}<load_from_csv>
def not_trivial_permutations(iterable):
perms = permutations(iterable)
 next(perms)
 yield from perms
@lru_cache(maxsize=None)
 def not_trivial_indexes_permutations(length):
return np.array([list(p)for p in not_trivial_permutations(range(length)) ])
 path_index = np.argsort(path[:-1])
 print(f'Total score is {score_path(path):.2f}.')
 for _ in range(3):
for ids in tqdm(triplets):
i, j, k = sorted(path_index[ids])
 head, tail = path[i-1], path[k+1]
chunks = [path[i:i+1], path[i+1:j], path[j:j+1], path[j+1:k], path[k:k+1]]
chunks = [chunk for chunk in chunks if len(chunk)]
scores = [chunk_scores(chunk)for chunk in chunks]
default_score = score_compound_chunk(i-1, head, chunks, tail, scores)
 best_score = default_score
for indexes_permutation in not_trivial_indexes_permutations(len(chunks)) :
score = score_compound_chunk(i-1, head, chunks, tail, scores, indexes_permutation)
 if score < best_score:
permutation = [chunks[i] for i in indexes_permutation]
best_chunk = np.concatenate([[head], np.concatenate(permutation), [tail]])
 best_score = score
if best_score < default_score:
path[i-1:k+2] = best_chunk
path_index = np.argsort(path[:-1])
 print(f'New total score is {score_path(path):.2f}.Permutating path at indexes {i}, {j}, {k}.')
 triplets = triplets[:10**6]
sample_df = pd.read_csv('.. /input/aptos2019-blindness-detection/sample_submission.csv')
 sample_df.head()<define_variables>
print(f'Final score is {score_path(path):.2f}.' )
learn.data.add_test(ImageList.from_df(
 sample_df, PATH,
folder='test_images',
suffix='.png' 
))<choose_model_class>
def make_submission(name, path):
pd.DataFrame({'Path': path} ).to_csv(f'{name}.csv', index=False )
<prepare_output><EOS> 
make_submission(score_path(path), path )