能在torch(lua)中连接张量而不失去引用吗?

th> x = torch.rand(2)
                                                                  [0.4943s]
th> y = torch.rand(2)
                                                                  [0.0001s]
th> x
 0.6115
 0.4986
[torch.DoubleTensor 的大小为 2]
                                                                  [0.0002s]
th> z = torch.cat(x,y)
                                                                  [0.0003s]
th> z
 0.6115
 0.4986
 0.5171
 0.1785
[torch.DoubleTensor 的大小为 4]

                                                                  [0.0001s]
th> z [1] = 3
                                                                  [0.0001s]
th> z [1]
 3
                                                                  [0.0001s]
th> x [1]
 0.61146148154512

修改 z 不会 修改 x。有没有一种连接 x 和 y 的方法,使得修改 z 会修改 x?

点赞
用户2658050
用户2658050

您可以实现这种行为,但相反操作。您应该从更大的张量开始,这是您的主要“存储器”,然后您可以创建子张量,这些子张量将共享内部状态。

特别是请参阅 torch 中的 :sub 方法(以下代码示例取自Torch文档

x = torch.Tensor(5, 6):zero()
> x
 0 0 0 0 0 0
 0 0 0 0 0 0
 0 0 0 0 0 0
 0 0 0 0 0 0
 0 0 0 0 0 0
[torch.DoubleTensor of dimension 5x6]

y = x:sub(2,4):fill(1) -- y是x的子张量:
> y                    -- 子张量第一维从索引2开始,到索引4结束
 1  1  1  1  1  1
 1  1  1  1  1  1
 1  1  1  1  1  1
[torch.DoubleTensor of dimension 3x6]

> x                    -- x已经被修改了!
 0  0  0  0  0  0
 1  1  1  1  1  1
 1  1  1  1  1  1
 1  1  1  1  1  1
 0  0  0  0  0  0
[torch.DoubleTensor of dimension 5x6]

正如您所看到的,您有一个实际上是 x 一部分的 y 变量,并且更改其值 - 也更改了 x 的值。这是非常通用的方式,因此您可以共享张量的多个部分。

因此,在您的情况下,它将是这样的

z = torch.Tensor(4):zero()
x = z:sub(1, 2)
y = z:sub(3, 4)
x[1] = 2
y[2] = 8
print(z)

打印

 2
 0
 0
 8
[torch.DoubleTensor of size 4]

就像期望的一样。

2016-02-07 22:25:00