如何用Keras重复张量特定元素并在最后轴插入零向量?
解决方案
一、仅重复最后一维的最后10个元素,得到形状(N, 2, 127, 114)的张量
要实现这个需求,需将原张量拆分为两部分分别处理后拼接:
- 拆分原张量:把最后一维的前42个元素和最后10个元素分开
- 按需重复:前42个元素重复2次(和你之前全量重复的逻辑一致),最后10个元素重复3次(总长度为
42*2 + 10*3 = 114) - 拼接结果:沿最后一维拼接两部分重复后的张量
代码实现:
import tensorflow as tf # 替换为你的实际张量 tensor = tf.random.normal((32, 2, 127, 52)) # 拆分前42个元素与最后10个元素 tensor_front = tensor[:, :, :, :42] tensor_last_10 = tensor[:, :, :, 42:] # 按需求重复元素 tensor_front_repeated = tf.keras.backend.repeat_elements(tensor_front, 2, axis=3) tensor_last_repeated = tf.keras.backend.repeat_elements(tensor_last_10, 3, axis=3) # 拼接得到目标张量 tensor_114 = tf.concat([tensor_front_repeated, tensor_last_repeated], axis=3) print(tensor_114.shape) # 输出 (32, 2, 127, 114)
二、在最后一维中间插入零向量,得到形状(N, 2, 127, 115)的张量
基于上面得到的114维张量,在最后一维的中间位置插入全零向量:
- 创建零向量:形状与张量前三维匹配,最后一维长度为1
- 拆分张量:在最后一维的中间位置(第57个索引处)拆分原114维张量
- 插入拼接:将零向量插入到拆分后的两部分之间
代码实现:
# 创建与前三维匹配的零向量 zero_col = tf.zeros_like(tensor_114[:, :, :, :1]) # 确定中间拆分位置 split_idx = tensor_114.shape[3] // 2 # 拆分并插入零向量 tensor_left = tensor_114[:, :, :, :split_idx] tensor_right = tensor_114[:, :, :, split_idx:] tensor_115 = tf.concat([tensor_left, zero_col, tensor_right], axis=3) print(tensor_115.shape) # 输出 (32, 2, 127, 115)
若你所说的“中间”指其他位置(比如原张量最后一维的中间),只需调整拆分索引即可,但从目标形状115来看,基于114维张量插入是最合理的实现方式。
内容的提问来源于stack exchange,提问作者Oscar Moreno
相关产品推荐
相关产品推荐

