Kaggle competition: Traveling Santa 2018 - Prime Paths
<SOS> metric: TravelingSanta2 Kaggle data source: traveling-santa-2018-prime-paths<split>
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
def train_model(x_train, y_train, train_transforms):
num_epochs = 97
batch_size = 64
test_batch_size = 256
lr = 1e-3
eta_min = 1e-5
t_max = 10
num_classes = y_train.shape[1]
x_trn, x_val, y_trn, y_val = train_test_split(x_train, y_train, test_size=0.2, random_state=SEED)
 train_dataset = FATTrainDataset(x_train, y_train, train_transforms)
 valid_dataset = FATTrainDataset(x_val, y_val, train_transforms)
 train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
 valid_loader = DataLoader(valid_dataset, batch_size=test_batch_size, shuffle=False)
 model = Classifier(num_classes=num_classes ).cuda()
criterion = nn.BCEWithLogitsLoss().cuda()
optimizer = Adam(params=model.parameters() , lr=lr, amsgrad=False)
 scheduler = CosineAnnealingLR(optimizer, T_max=t_max, eta_min=eta_min)
 best_epoch = -1
best_lwlrap = 0.
 mb = master_bar(range(num_epochs))
for epoch in mb:
start_time = time.time()
model.train()
avg_loss = 0.
 for x_batch, y_batch in train_loader:
preds = model(x_batch.cuda())
 loss = criterion(preds, y_batch.cuda())
 optimizer.zero_grad()
loss.backward()
optimizer.step()
avg_loss += loss.item() / len(train_loader)
 model.eval()
valid_preds = np.zeros(( len(x_val), num_classes))
avg_val_loss = 0.
 ')
 for i,(x_batch, y_batch)in enumerate(valid_loader):
preds = model(x_batch.cuda() ).detach()
loss = criterion(preds, y_batch.cuda())
 preds = torch.sigmoid(preds)
 valid_preds[i * test_batch_size:(i+1)* test_batch_size] = preds.cpu().numpy()
avg_val_loss += loss.item() / len(valid_loader)
 score, weight = calculate_per_class_lwlrap(y_val, valid_preds)
 lwlrap =(score * weight ).sum()
scheduler.step()
if(epoch + 1)% 1 == 0:
elapsed = time.time() - start_time
mb.write(f'Epoch {epoch+1} - avg_train_loss: {avg_loss:.4f} avg_val_loss: {avg_val_loss:.4f} val_lwlrap: {lwlrap:.6f} time: {elapsed:.0f}s')
 if lwlrap > best_lwlrap:
best_epoch = epoch + 1
best_lwlrap = lwlrap
torch.save(model.state_dict() , 'weight_best.pt')
 ')
 return {
'best_epoch': best_epoch,
'best_lwlrap': best_lwlrap,
} 
<train_model>
K = 4
NUM_NEIGHBORS = 5
RADIUS = 0
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 )
result = train_model(x_train, y_train, transforms_dict['train'] )<predict_on_test>
@numba.jit('f8(i8, i8)', nopython=True, parallel=False)
 def euclidean_distance(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]
return sqrt(dx * dx + dy * dy)
 @numba.jit('f8(i8, i8, i8)', nopython=True, parallel=False)
 def cities_distance(offset, id_from, id_to):

 distance = euclidean_distance(id_from, id_to)
 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]
distance = euclidean_distance(id_from, id_to)
 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]
distance = euclidean_distance(id_from, id_to)
 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 )
test_preds = predict_model(test_df['fname'], x_test, transforms_dict['test'], num_classes, tta=35 )<save_to_csv>
path = pd.read_csv('.. /input/santatour1515602/1515602.86080513.csv', squeeze=True ).values
initial_score = score_path(path)
 print("Initial tour distance(score): {:.2f}".format(initial_score))
test_df[labels] = test_preds.values
test_df.to_csv('submission.csv', index=False)
 test_df.head()<set_options>
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])
 for _ in range(1):
for ids in tqdm(candidates):
idx = sorted(path_index[ids])
 head, tail = path[idx[0] - 1], path[idx[-1] + 1]
chunks = [path[idx[0]:idx[0]+1]]
for i in range(len(idx)- 1):
chunks.append(path[idx[i]+1:idx[i+1]])
 chunks.append(path[idx[i+1]:idx[i+1]+1])
 chunks = [chunk for chunk in chunks if len(chunk)]
scores = [chunk_scores(chunk)for chunk in chunks]
default_score = score_compound_chunk(idx[0]-1, head, chunks, tail, scores)
 best_score = default_score
for indexes_permutation in not_trivial_indexes_permutations(len(chunks)) :
score = score_compound_chunk(idx[0]-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[idx[0]-1:idx[-1]+2] = best_chunk
path_index = np.argsort(path[:-1])
 improvement = True
def seed_everything(seed):
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 = 999
seed_everything(SEED )<categorify>
final_score = score_path(path)
 print("Final score is {:.2f}, improvement: {:.2f}".format(final_score, initial_score - final_score))
<define_variables><EOS> 
def make_submission(name, path):
pd.DataFrame({'Path': path} ).to_csv(f'{name}.csv', index=False)
 make_submission(score_path(path), path )