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
learn = cnn_learner(data, models.resnet18, pretrained=False, metrics=[lwlrap])
 learn.unfreeze()
learn.lr_find() ; learn.recorder.plot()<train_model>
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.fit_one_cycle(5, 1e-1)
 learn.fit_one_cycle(10, 1e-2 )<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 )
learn.fit_one_cycle(20, 3e-3 )<train_model>
kdt = KDTree(XY )
learn.fit_one_cycle(20, 1e-3 )<train_model>
path = np.array(pd.read_csv('.. /input/santa-2018/submission_1515572.48.csv' ).Path)
 initial_score = score_path(path )
learn.fit_one_cycle(50, slice(1e-3, 3e-3))<train_model>
path_index = np.argsort(path[:-1])
 total_score = initial_score
print(f'Total score is {total_score:.2f}.')
 for _ in range(5):
for step,(id1, id2)in enumerate(pairs[:10**6], 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] )
learn.fit_one_cycle(10, slice(1e-4, 1e-3))<save_model>
print(f'Total improvement is {initial_score - total_score:.2f}.' )
learn.save('fat2019_fastai_cnn2d_stage-2')
 learn.export()<load_from_csv>
def make_submission(name, path):
pd.DataFrame({'Path': path} ).to_csv(f'{name}.csv', index=False )
<save_to_csv><EOS> 
make_submission(score_path(path), path )