Update make_tensor_proto to support nested nparray values when dtype is specified.

This removes an inconsistency between graph & eager mode.  In particular, prior to this CL, the following succeeds in eager mode but fails in graph mode:

  tf.convert_to_tensor([22, np.array(1)], dtype=tf.int32)

PiperOrigin-RevId: 310212356
Change-Id: Ib836171b7ebc6ef5974c364b8ded172503120eba
This commit is contained in:
Edward Loper 2020-05-06 13:04:40 -07:00 committed by TensorFlower Gardener
parent 4a9c9039a8
commit f17392238e
2 changed files with 19 additions and 2 deletions

View File

@ -260,8 +260,12 @@ def _check_quantized(values):
def _generate_isinstance_check(expected_types): def _generate_isinstance_check(expected_types):
def inner(values): def inner(values):
_ = [_check_failed(v) for v in nest.flatten(values) for v in nest.flatten(values):
if not isinstance(v, expected_types)] if not (isinstance(v, expected_types) or
(isinstance(v, np.ndarray) and
issubclass(v.dtype.type, expected_types))):
_check_failed(v)
return inner return inner
_check_int = _generate_isinstance_check( _check_int = _generate_isinstance_check(

View File

@ -713,6 +713,19 @@ class TensorUtilTest(test.TestCase):
self.assertAllEqual( self.assertAllEqual(
np.array([[(1 + 2j), (3 + 4j)], [(5 + 6j), (7 + 8j)]]), a) np.array([[(1 + 2j), (3 + 4j)], [(5 + 6j), (7 + 8j)]]), a)
def testNestedNumpyArrayWithoutDType(self):
t = tensor_util.make_tensor_proto([10.0, 20.0, np.array(30.0)])
a = tensor_util.MakeNdarray(t)
self.assertEqual(np.float32, a.dtype)
self.assertAllClose(np.array([10.0, 20.0, 30.0], dtype=np.float32), a)
def testNestedNumpyArrayWithDType(self):
t = tensor_util.make_tensor_proto([10.0, 20.0, np.array(30.0)],
dtype=dtypes.float32)
a = tensor_util.MakeNdarray(t)
self.assertEqual(np.float32, a.dtype)
self.assertAllClose(np.array([10.0, 20.0, 30.0], dtype=np.float32), a)
def testUnsupportedDTypes(self): def testUnsupportedDTypes(self):
with self.assertRaises(TypeError): with self.assertRaises(TypeError):
tensor_util.make_tensor_proto(np.array([1]), 0) tensor_util.make_tensor_proto(np.array([1]), 0)