You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_sampler.py 1.5 kB

7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import unittest
  2. import torch
  3. from fastNLP.core.sampler import convert_to_torch_tensor, SequentialSampler, RandomSampler, \
  4. k_means_1d, k_means_bucketing, simple_sort_bucketing
  5. class TestSampler(unittest.TestCase):
  6. def test_convert_to_torch_tensor(self):
  7. data = [[1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [1, 3, 4, 5, 2]]
  8. ans = convert_to_torch_tensor(data, False)
  9. assert isinstance(ans, torch.Tensor)
  10. assert tuple(ans.shape) == (3, 5)
  11. def test_sequential_sampler(self):
  12. sampler = SequentialSampler()
  13. data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
  14. for idx, i in enumerate(sampler(data)):
  15. assert idx == i
  16. def test_random_sampler(self):
  17. sampler = RandomSampler()
  18. data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
  19. ans = [data[i] for i in sampler(data)]
  20. assert len(ans) == len(data)
  21. for d in ans:
  22. assert d in data
  23. def test_k_means(self):
  24. centroids, assign = k_means_1d([21, 3, 25, 7, 9, 22, 4, 6, 28, 10], 2, max_iter=5)
  25. centroids, assign = list(centroids), list(assign)
  26. assert len(centroids) == 2
  27. assert len(assign) == 10
  28. def test_k_means_bucketing(self):
  29. res = k_means_bucketing([21, 3, 25, 7, 9, 22, 4, 6, 28, 10], [None, None])
  30. assert len(res) == 2
  31. def test_simple_sort_bucketing(self):
  32. _ = simple_sort_bucketing([21, 3, 25, 7, 9, 22, 4, 6, 28, 10])
  33. assert len(_) == 10