我想根据条件替换值。
NumPy 版本会像这样
intensity=np.where(
np.abs(intensity)<1e-4,
1e-4,
intensity)
但是 TensorFlow 对 tf.where() 的用法有点不同
当我尝试这个时
intensity=tf.where(
tf.math.abs(intensity)<1e-4,
1e-4,
intensity)
我收到这个错误
ValueError: Shapes must be equal rank, but are 0 and 4 for 'Select' (op: 'Select') with input shapes: [?,512,512,1], [], [?,512,512,1].
这是否意味着我应该为 1e-4
使用 4 维张量?
最佳答案
以下代码传递了错误
# Create an array which has small value (1e-4),
# whose shape is (2,512,512,1)
small_val=np.full((2,512,512,1),1e-4).astype("float32")
# Convert numpy array to tf.constant
small_val=tf.constant(small_val)
# Use tf.where()
intensity=tf.where(
tf.math.abs(intensity)<1e-4,
small_val,
intensity)
# Error doesn't occur
print(intensity.shape)
# (2, 512, 512, 1)
关于python - 如何使用 tf.where() 根据条件替换特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55393557/