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.3 kB

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