|
14 | 14 | # ==============================================================================
|
15 | 15 | """Tests of power law entropy model."""
|
16 | 16 |
|
| 17 | +import numpy as np |
17 | 18 | import tensorflow as tf
|
18 | 19 | from tensorflow_compression.python.entropy_models.power_law import PowerLawEntropyModel
|
19 | 20 |
|
@@ -56,27 +57,26 @@ def test_compression_consistent_with_quantization(self):
|
56 | 57 |
|
57 | 58 | def test_penalty_is_proportional_to_code_length(self):
|
58 | 59 | em = PowerLawEntropyModel(coding_rank=1)
|
59 |
| - # Sample some values from a Laplacian distribution. |
60 |
| - u = tf.random.uniform((100, 1), minval=-1., maxval=1.) |
61 |
| - values = 100. * tf.math.log(abs(u)) * tf.sign(u) |
62 |
| - # Ensure there are some large values. |
63 |
| - self.assertGreater(tf.reduce_sum(tf.cast(abs(values) > 100, tf.int32)), 0) |
64 |
| - strings = em.compress(tf.broadcast_to(values, (100, 100))) |
| 60 | + x = tf.range(-20., 20.)[:, None] |
| 61 | + x += tf.random.uniform(x.shape, -.49, .49) |
| 62 | + strings = em.compress(tf.broadcast_to(x, (40, 100))) |
65 | 63 | code_lengths = tf.cast(tf.strings.length(strings, unit="BYTE"), tf.float32)
|
66 | 64 | code_lengths *= 8 / 100
|
67 |
| - penalties = em.penalty(values) |
68 |
| - self.assertAllInRange(penalties - code_lengths, 4, 7) |
| 65 | + penalties = em.penalty(x) |
| 66 | + # There are some fluctuations due to `alpha`, `floor`, and rounding, but we |
| 67 | + # expect a high degree of correlation between code lengths and penalty. |
| 68 | + self.assertGreater(np.corrcoef(code_lengths, penalties)[0, 1], .96) |
69 | 69 |
|
70 |
| - def test_penalty_is_differentiable(self): |
| 70 | + def test_penalty_is_nonnegative_and_differentiable(self): |
71 | 71 | em = PowerLawEntropyModel(coding_rank=1)
|
72 |
| - # Sample some values from a Laplacian distribution. |
73 |
| - u = tf.random.uniform((100, 1), minval=-1., maxval=1.) |
74 |
| - values = 100. * tf.math.log(abs(u)) * tf.sign(u) |
| 72 | + x = tf.range(-20., 20.)[:, None] |
| 73 | + x += tf.random.uniform(x.shape, -.49, .49) |
75 | 74 | with tf.GradientTape() as tape:
|
76 |
| - tape.watch(values) |
77 |
| - penalties = em.penalty(values) |
78 |
| - gradients = tape.gradient(penalties, values) |
79 |
| - self.assertAllEqual(tf.sign(gradients), tf.sign(values)) |
| 75 | + tape.watch(x) |
| 76 | + penalties = em.penalty(x) |
| 77 | + gradients = tape.gradient(penalties, x) |
| 78 | + self.assertAllGreaterEqual(penalties, 0) |
| 79 | + self.assertAllEqual(tf.sign(gradients), tf.sign(x)) |
80 | 80 |
|
81 | 81 | def test_compression_works_in_tf_function(self):
|
82 | 82 | samples = tf.random.stateless_normal([100], (34, 232))
|
|
0 commit comments