You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并两个Tensor?实现指定拼接结果的方法咨询

嘿,看来你需要把两个一维Tensor按顺序拼接成一个更长的一维Tensor对吧?从你想要的结果c = [1, 2, 3, 4, 5, 6]来看,直接用框架自带的拼接函数就能搞定,下面分两种常用深度学习框架给你具体实现方法:

PyTorch 实现方案

如果你用的是PyTorch,torch.cat()就是专门用来拼接Tensor的工具,只需要指定拼接的维度就行:

  • 假设你的a和b是一维Tensor:
    import torch
    a = torch.tensor([1, 2, 3])
    b = torch.tensor([4, 5, 6])
    # dim=0表示沿着第一个维度(一维Tensor的唯一维度)拼接
    c = torch.cat((a, b), dim=0)
    print(c)  # 输出: tensor([1, 2, 3, 4, 5, 6])
    
  • 如果你的a、b是高维Tensor,但需要先展平再拼接,可以先用flatten()或者view(-1)处理:
    # 示例:2x3的高维Tensor
    a = torch.tensor([[1,2,3],[7,8,9]])
    b = torch.tensor([[4,5,6],[10,11,12]])
    c = torch.cat((a.flatten(), b.flatten()), dim=0)
    print(c)  # 输出: tensor([ 1,  2,  3,  7,  8,  9,  4,  5,  6, 10, 11, 12])
    
TensorFlow 实现方案

要是用TensorFlow,对应的拼接函数是tf.concat(),用法和PyTorch类似:

  • 一维Tensor的情况:
    import tensorflow as tf
    a = tf.constant([1, 2, 3])
    b = tf.constant([4, 5, 6])
    # axis=0对应一维Tensor的拼接维度
    c = tf.concat([a, b], axis=0)
    print(c.numpy())  # 输出: [1 2 3 4 5 6]
    
  • 高维Tensor展平拼接的情况,用tf.reshape()或者tf.flatten()处理:
    # 示例:2x3的高维Tensor
    a = tf.constant([[1,2,3],[7,8,9]])
    b = tf.constant([[4,5,6],[10,11,12]])
    c = tf.concat([tf.reshape(a, [-1]), tf.reshape(b, [-1])], axis=0)
    print(c.numpy())  # 输出: [ 1  2  3  7  8  9  4  5  6 10 11 12]
    

内容的提问来源于stack exchange,提问作者guorui

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:35:53