TensorFlow中tf.concat()对同形同值的t1、t2输出不同结果的原因
tf.concat() return different results for a Python list and NumPy array with identical shape/values? Great question! The root cause here is how TensorFlow interprets Python nested lists vs. NumPy arrays when passed to tf.concat()—even if their shape and values look identical, the handling logic is totally different:
How
t1(Python list) is processed
When you pass the Python nested listt1totf.concat(), TensorFlow treats it as a list containing 2 separate tensors:- Each sub-list
[[0],[1],[2]]and[[3],[4],[5]]gets converted to a tensor with shape[3, 1] tf.concat(t1, 1)then concatenates these two[3,1]tensors along the 1st axis, resulting in a[3,2]tensor (the[[0 3],[1 4],[2 5]]you see)
- Each sub-list
How
t2(NumPy array) is processed
When you pass the NumPy arrayt2, TensorFlow first converts the entire array into a single 3D tensor with shape[2,3,1].
Now,tf.concat()expects its first argument to be a list/tuple of tensors. If you pass a single tensor, it automatically wraps it into a list with one element (liketf.concat([t2], 1)). Concatenating a list with only one tensor does nothing—you get back the original tensor, hence the output matchingt2's structure exactly.
If you want t2 to produce the same result as t1, you need to split it into the two [3,1] sub-tensors first, then pass them as a list to tf.concat():
print(sess.run(tf.concat([t2[0], t2[1]], 1)))
This will give you the same [3,2] output as the t1 case.
内容的提问来源于stack exchange,提问作者ji cocaer

