如何高效在一维Torch张量的奇数索引后插入元素以扩容?
高效实现张量插入操作(PyTorch/NumPy)
PyTorch 实现
场景1:按示例要求(每两个原元素后插入值,最终长度576)
直接利用张量的reshape和cat操作批量完成,完全规避Python循环:
import torch # 原张量示例 x = torch.randn(384) # 定义要插入的数值(可替换为任意值或张量) insert_val = 0 # 步骤:拆分原张量为每2个元素一组,拼接插入值组后展平 result = torch.cat( [x.reshape(192, 2), torch.full((192, 1), insert_val, dtype=x.dtype, device=x.device)], dim=1 ).flatten() # result.shape → torch.Size([576])
场景2:实现最终维度768(每个元素后插入值)
如果需要将张量长度翻倍,只需调整分组方式:
import torch x = torch.randn(384) insert_val = 0 # 每个原元素单独成组,与插入值拼接后展平 result = torch.cat( [x.reshape(-1, 1), torch.full_like(x.reshape(-1, 1), insert_val)], dim=1 ).flatten() # result.shape → torch.Size([768])
NumPy 实现
场景1:每两个元素后插入值
import numpy as np x = np.random.randn(384) insert_val = 0 result = np.concatenate( [x.reshape(192, 2), np.full((192, 1), insert_val, dtype=x.dtype)], axis=1 ).flatten() # result.shape → (576,)
场景2:每个元素后插入值(长度768)
import numpy as np x = np.random.randn(384) insert_val = 0 result = np.concatenate( [x.reshape(-1, 1), np.full_like(x.reshape(-1, 1), insert_val)], axis=1 ).flatten() # result.shape → (768,)
扩展:插入动态计算的值
如果插入值不是固定值,而是基于原张量的计算结果(比如原奇数索引元素的一半),同样可以高效实现:
# PyTorch示例 x = torch.randn(384) # 提取原奇数索引的元素并计算插入值 insert_vals = x[1::2] / 2 result = torch.cat([x.reshape(192, 2), insert_vals.reshape(192, 1)], dim=1).flatten()
这些方法均基于底层的批量张量/数组操作,执行效率远高于Python循环,适合处理大规模张量的批量任务。
内容的提问来源于stack exchange,提问作者ORC
相关产品推荐
相关产品推荐

