将张量向量附加到张量矩阵

时间:2021-02-21 06:26:35

标签: python pytorch

我有一个张量矩阵,我只想将一个张量向量作为另一列附加到它上面。

例如:

    X = torch.randint(100, (100,5))
    x1 = torch.from_numpy(np.array(range(0, 100)))

我已经尝试使用 torch.cat([x1, X)axis 的各种数字 dim 但它总是说尺寸不匹配。

3 个答案:

答案 0 :(得分:2)

您还可以使用 torch.hstack 组合和 unsqueeze 进行重塑 reducer

x1

答案 1 :(得分:1)

X 的形状是 [100, 5],而 X1 的形状是 100。对于串联,除了我们试图串联的轴之外,炬管的所有轴都需要相似的形状。

因此,您首先需要

X1 = X1[:, None] # change the shape from 100 to [100, 1]
Xc = torch.cat([X, X1], axis=-1) /# tells the torch that we need to concatenate over the last dimension

Xc.shape 应该是 [100, 6]

答案 2 :(得分:0)

将两个答案组合成一个pytorch 1.6兼容版本:

torch.cat((X, x1.unsqueeze(1)), dim = 1)