Skip to content

Commit 6cc4969

Browse files
mrrykeveman
authored andcommitted
Improve exception message when TensorShape.with_rank() fails
Previously this would pass on the exception message from `TensorShape.merge_with()`, which is cryptic for users who don't (and shouldn't need to) understand how shape inference works. This would arise, for example, in the error message for `tf.matmul()` when passed a non-matrix, as noted here: http://stackoverflow.com/questions/34908033/tensorflow-exception-with-matmul Change: 112621185
1 parent 3ea0405 commit 6cc4969

3 files changed

Lines changed: 16 additions & 2 deletions

File tree

tensorflow/python/framework/tensor_shape.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -611,7 +611,10 @@ def with_rank(self, rank):
611611
Raises:
612612
ValueError: If `self` does not represent a shape with the given `rank`.
613613
"""
614-
return self.merge_with(unknown_shape(ndims=rank))
614+
try:
615+
return self.merge_with(unknown_shape(ndims=rank))
616+
except ValueError:
617+
raise ValueError("Shape %s must have rank %d" % (self, rank))
615618

616619
def with_rank_at_least(self, rank):
617620
"""Returns a shape based on `self` with at least the given rank.

tensorflow/python/kernel_tests/matmul_op_test.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,17 @@ def testMatMul_Inputs_Empty(self):
148148
self._testCpuMatmul(x, y)
149149
self._testGpuMatmul(x, y)
150150

151+
def testShapeErrors(self):
152+
a = tf.placeholder(tf.float32, [32, 37])
153+
b = tf.placeholder(tf.float32, [36, 2])
154+
c = tf.placeholder(tf.float32, [37])
155+
with self.assertRaisesRegexp(
156+
ValueError,
157+
r"Dimensions Dimension\(37\) and Dimension\(36\) are not compatible"):
158+
tf.matmul(a, b)
159+
with self.assertRaisesRegexp(ValueError, "must have rank 2"):
160+
tf.matmul(a, c)
161+
151162

152163
# TODO(zhifengc): Figures out how to test matmul gradients on GPU.
153164
class MatMulGradientTest(tf.test.TestCase):

tensorflow/python/kernel_tests/xent_op_test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def testRankTooLarge(self):
7070
np_labels = np.array(
7171
[[[0., 0., 0., 1.]], [[0., .5, .5, 0.]]]).astype(np.float32)
7272
self.assertRaisesRegexp(
73-
ValueError, "must have the same rank",
73+
ValueError, "must have rank 2",
7474
tf.nn.softmax_cross_entropy_with_logits, np_features, np_labels)
7575

7676
def testNpXent(self):

0 commit comments

Comments
 (0)