extend Melu code to perform different meta algorithms and hyperparameters
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

hyper_testing.py 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import random
  2. from torch.nn import L1Loss
  3. import numpy as np
  4. from fast_adapt import fast_adapt
  5. from sklearn.metrics import ndcg_score
  6. def hyper_test(embedding,head, total_dataset, adaptation_step):
  7. test_set_size = len(total_dataset)
  8. random.shuffle(total_dataset)
  9. a, b, c, d = zip(*total_dataset)
  10. losses_q = []
  11. ndcgs11 = []
  12. ndcgs33=[]
  13. for iterator in range(test_set_size):
  14. try:
  15. supp_xs = a[iterator].cuda()
  16. supp_ys = b[iterator].cuda()
  17. query_xs = c[iterator].cuda()
  18. query_ys = d[iterator].cuda()
  19. except IndexError:
  20. print("index error in test method")
  21. continue
  22. learner = head.clone()
  23. temp_sxs = embedding(supp_xs)
  24. temp_qxs = embedding(query_xs)
  25. evaluation_error,predictions = fast_adapt(learner,
  26. temp_sxs,
  27. temp_qxs,
  28. supp_ys,
  29. query_ys,
  30. adaptation_step,
  31. get_predictions=True)
  32. l1 = L1Loss(reduction='mean')
  33. loss_q = l1(predictions.view(-1), query_ys)
  34. losses_q.append(float(loss_q))
  35. predictions = predictions.view(-1)
  36. y_true = query_ys.cpu().detach().numpy()
  37. y_pred = predictions.cpu().detach().numpy()
  38. ndcgs11.append(float(ndcg_score([y_true], [y_pred], k=1, sample_weight=None, ignore_ties=False)))
  39. ndcgs33.append(float(ndcg_score([y_true], [y_pred], k=3, sample_weight=None, ignore_ties=False)))
  40. del supp_xs, supp_ys, query_xs, query_ys, predictions, y_true, y_pred, loss_q
  41. # calculate metrics
  42. try:
  43. losses_q = np.array(losses_q).mean()
  44. except:
  45. losses_q = 100
  46. try:
  47. ndcg1 = np.array(ndcgs11).mean()
  48. ndcg3 = np.array(ndcgs33).mean()
  49. except:
  50. ndcg1 = 0
  51. ndcg3 = 0
  52. return losses_q,ndcg1,ndcg3