TensorFlow SYMMETRIC/REFLECT填充报错:填充值超维度大小
问题与解决:TensorFlow SYMMETRIC/REFLECT模式填充报错
问题场景
需要将形状为(1, 5, 256)的Tensor填充为(1, 128, 256):
- 使用CONSTANT模式填充0的代码可正常运行:
tensor = tf.expand_dims(image_output, axis=1) logg = tf.constant([ [0, 0] , [62, 61], [0, 0] ]) new_tensor = tf.pad(tensor, logg, mode ='CONSTANT', constant_values=0)
- 切换为SYMMETRIC或REFLECT模式时,代码:
tensor = tf.expand_dims(image_output, axis=1) logg = tf.constant([[0, 0], [62, 61], [0, 0]]) new_tensor = tf.pad(image_embeddings, logg, mode ='SYMMETRIC')
触发报错,翻译后内容为:
节点: 'MirrorPad' 填充值不得超过维度大小:62、61 大于 5 [[{{node MirrorPad}}]] [Op:__inference_train_function_463079]
报错原因
SYMMETRIC和REFLECT模式的填充逻辑依赖原Tensor的现有数据进行镜像/反射生成填充内容,因此单个方向的填充长度不能超过对应维度的原始大小。
原Tensor第二维度长度仅为5,但代码中试图在该维度左侧填充62、右侧填充61,均远大于5,违反了该模式的限制规则,导致报错。而CONSTANT模式填充固定值,无此限制。
解决方法
要实现目标形状的SYMMETRIC/REFLECT填充,需先扩展原Tensor的维度至接近目标长度,再进行小范围镜像填充:
方法1:先重复原Tensor再填充
通过tf.tile重复原Tensor,让第二维度长度接近128,再用SYMMETRIC模式补充剩余长度:
tensor = tf.expand_dims(image_output, axis=1) # shape (1,5,256) # 重复25次,得到(1, 125, 256) tiled_tensor = tf.tile(tensor, multiples=[1,25,1]) # 剩余需要填充的长度:128-125=3,左右分配为1和2 pad_log = tf.constant([[0,0], [1,2], [0,0]]) new_tensor = tf.pad(tiled_tensor, pad_log, mode='SYMMETRIC')
方法2:分多次迭代填充
如果需要严格基于原始数据镜像(不重复整个Tensor),可以通过多次填充逐步扩展维度,每次填充长度不超过当前维度大小:
tensor = tf.expand_dims(image_output, axis=1) # shape (1,5,256) target_dim = 128 current_dim = tf.shape(tensor)[1] while current_dim < target_dim: # 计算当前可填充的最大长度(不超过当前维度大小) pad_left = min(current_dim, (target_dim - current_dim) // 2) pad_right = min(current_dim, target_dim - current_dim - pad_left) pad_log = tf.constant([[0,0], [pad_left, pad_right], [0,0]]) tensor = tf.pad(tensor, pad_log, mode='SYMMETRIC') current_dim = tf.shape(tensor)[1] new_tensor = tensor
内容的提问来源于stack exchange,提问作者user19686684
相关产品推荐
相关产品推荐

