test_fast_dict.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """ Test fast_dict.
  2. """
  3. import numpy as np
  4. from numpy.testing import assert_allclose, assert_array_equal
  5. from sklearn.utils._fast_dict import IntFloatDict, argmin
  6. def test_int_float_dict():
  7. rng = np.random.RandomState(0)
  8. keys = np.unique(rng.randint(100, size=10).astype(np.intp))
  9. values = rng.rand(len(keys))
  10. d = IntFloatDict(keys, values)
  11. for key, value in zip(keys, values):
  12. assert d[key] == value
  13. assert len(d) == len(keys)
  14. d.append(120, 3.0)
  15. assert d[120] == 3.0
  16. assert len(d) == len(keys) + 1
  17. for i in range(2000):
  18. d.append(i + 1000, 4.0)
  19. assert d[1100] == 4.0
  20. def test_int_float_dict_argmin():
  21. # Test the argmin implementation on the IntFloatDict
  22. keys = np.arange(100, dtype=np.intp)
  23. values = np.arange(100, dtype=np.float64)
  24. d = IntFloatDict(keys, values)
  25. assert argmin(d) == (0, 0)
  26. def test_to_arrays():
  27. # Test that an IntFloatDict is converted into arrays
  28. # of keys and values correctly
  29. keys_in = np.array([1, 2, 3], dtype=np.intp)
  30. values_in = np.array([4, 5, 6], dtype=np.float64)
  31. d = IntFloatDict(keys_in, values_in)
  32. keys_out, values_out = d.to_arrays()
  33. assert keys_out.dtype == keys_in.dtype
  34. assert values_in.dtype == values_out.dtype
  35. assert_array_equal(keys_out, keys_in)
  36. assert_allclose(values_out, values_in)