tf.concat fails with type mismatch

Viewed 84
t1 = tf.linalg.diag([1.0, 2.0, 3.0])
t2 = tf.constant([1.0, 2.0, 3.0])
tf.concat(t1, t2)

All I trying to do is concat an extra row [1.0, 2.0, 3.0] to the matrix [[1.0, 0.0, 0.0], [0.0, 2.0, 0.0], [0.0, 0.0, 3.0]].

They are all float types. But it is failing with

/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/ops.py in convert_to_tensor(value, dtype, name, as_ref, preferred_dtype, dtype_hint, ctx, accepted_result_types)
   1588       raise ValueError(
   1589           "Tensor conversion requested dtype %s for Tensor with dtype %s: %r" %
-> 1590           (dtype.name, value.dtype.name, value))
   1591     return value
   1592 

ValueError: Tensor conversion requested dtype int32 for Tensor with dtype float32: <tf.Tensor: shape=(1, 3), dtype=float32, numpy=array([[1., 2., 3.]], dtype=float32)>

Edit: The diag output is actually a float even without casting:

<tf.Tensor: shape=(3, 3), dtype=float32, numpy=
array([[1., 0., 0.],
       [0., 2., 0.],
       [0., 0., 3.]], dtype=float32)>

also even after casting to float it doesn't work and gives the same error

t0 = tf.linalg.diag([1.0, 2.0, 3.0])
t1 = tf.cast(t0, tf.float32)
t2 = tf.constant([[1.0, 2.0, 3.0]])
tf.concat(t1, t2)
2 Answers

Looks like your first tensor is of type int32. If you are going to do floating point operations, just cast it to float:

t1 = tf.cast(tf.linalg.diag([1.0, 2.0, 3.0]), tf.float32)

Otherwise, you can define the constant with int32 type:

t2 = tf.constant([1.0, 2.0, 3.0], dtype=tf.int32)

The error is misleading, because it does not have anything to do with the data types of the tensors. Try something like this and do not forget to use square brackets and set the axis parameter of tf.concat:

import tensorflow as tf

t1 = tf.linalg.diag([1.0, 2.0, 3.0])
t2 = tf.constant([1.0, 2.0, 3.0])
t2 = tf.expand_dims(t2, axis=0)

print(tf.concat([t1, t2], axis=0))
[[1. 0. 0.]
 [0. 2. 0.]
 [0. 0. 3.]
 [1. 2. 3.]], shape=(4, 3), dtype=float32)
Related