|
18 | 18 | import numpy as np
|
19 | 19 | import tensorflow as tf
|
20 | 20 | from tensorflow_addons.activations import softshrink
|
| 21 | +from tensorflow_addons.activations.softshrink import _softshrink_py |
21 | 22 | from tensorflow_addons.utils import test_utils
|
22 | 23 |
|
23 | 24 |
|
@@ -53,6 +54,30 @@ def test_theoretical_gradients(self, dtype):
|
53 | 54 | theoretical, numerical = tf.test.compute_gradient(softshrink, [x])
|
54 | 55 | self.assertAllCloseAccordingToType(theoretical, numerical, atol=1e-4)
|
55 | 56 |
|
| 57 | + @parameterized.named_parameters(("float32", np.float32), ("float64", np.float64)) |
| 58 | + def test_same_as_py_func(self, dtype): |
| 59 | + np.random.seed(1234) |
| 60 | + for _ in range(20): |
| 61 | + self.verify_funcs_are_equivalent(dtype) |
| 62 | + |
| 63 | + def verify_funcs_are_equivalent(self, dtype): |
| 64 | + x_np = np.random.uniform(-10, 10, size=(4, 4)).astype(dtype) |
| 65 | + x = tf.convert_to_tensor(x_np) |
| 66 | + lower = np.random.uniform(-10, 10) |
| 67 | + upper = lower + np.random.uniform(0, 10) |
| 68 | + |
| 69 | + with tf.GradientTape(persistent=True) as t: |
| 70 | + t.watch(x) |
| 71 | + y_native = softshrink(x, lower, upper) |
| 72 | + y_py = _softshrink_py(x, lower, upper) |
| 73 | + |
| 74 | + self.assertAllCloseAccordingToType(y_native, y_py, atol=1e-4) |
| 75 | + |
| 76 | + grad_native = t.gradient(y_native, x) |
| 77 | + grad_py = t.gradient(y_py, x) |
| 78 | + |
| 79 | + self.assertAllCloseAccordingToType(grad_native, grad_py, atol=1e-4) |
| 80 | + |
56 | 81 |
|
57 | 82 | if __name__ == "__main__":
|
58 | 83 | tf.test.main()
|
0 commit comments