如何在未知尺寸的张量上正确使用tf.slice并解决形状推断错误?
Hey there, let's break down what's going wrong with your code and get it working correctly:
1. First, Fix the Syntax Mistake in Your tf.slice Call
Looking at your code, there's a syntax error that's causing the slice dimensions to be calculated incorrectly:
a=tf.slice(sim_matrix,[0,0,0],tf.stack([tf.shape(sim_matrix[0],tf.shape(sim_matrix)[1],3]))
You missed a closing parenthesis for tf.shape(sim_matrix)[0], and incorrectly nested the second dimension argument inside the first tf.shape call. The corrected line should be:
a = tf.slice(sim_matrix, [0, 0, 0], tf.stack([tf.shape(sim_matrix)[0], tf.shape(sim_matrix)[1], 3]))
Even with this fix, though, you might still run into shape inference issues because tf.shape returns a dynamic tensor, which doesn't help TensorFlow lock in the static shape of the output.
2. Resolve the "Input size must be accessible via shape inference" Error
That error pops up because downstream operations need to know the size of the last dimension (3) at graph construction time, but using dynamic shape operations like tf.stack with tf.shape doesn't expose this statically. Here are two cleaner, more reliable solutions:
Option 1: Use Python-Style Slicing (The Easiest Fix)
TensorFlow supports standard Python slicing for tensors, which makes your code simpler and helps TensorFlow infer the correct static shape:
# Keep all elements in the first two dimensions, take the first 3 elements in the third a = sim_matrix[:, :, :3]
This will immediately set the static shape of a to (?, ?, 3) (assuming your original tensor's third dimension is at least 3), so downstream operations can see the fixed last dimension size.
Option 2: Explicitly Set the Static Shape
If you need to stick with tf.slice for some reason, you can explicitly tell TensorFlow the shape of the output tensor after slicing:
a = tf.slice(sim_matrix, [0, 0, 0], tf.stack([tf.shape(sim_matrix)[0], tf.shape(sim_matrix)[1], 3])) # Declare the static shape: first two dimensions can be dynamic (None), last is fixed at 3 a.set_shape((None, None, 3))
This overrides the default shape inference and lets TensorFlow know the last dimension is guaranteed to be 3, which will resolve the "None" error in your downstream code.
3. Check the Result
After applying either fix, printing a.shape should show (?, ?, 3) instead of (?, ?, ?), and your subsequent operations should run without that shape inference error.
内容的提问来源于stack exchange,提问作者Qi He

