将常量变量添加到 cuda.FloatTensor

Add a constant variable to a cuda.FloatTensor

我有两个问题:

1) I'd like to know how can I add/subtract a constante torch.FloatTensor of size 1 to all of the elemets of a torch.FloatTensor of size 30.

2) How can I multiply each element of a torch.FloatTensor of size 30 by a random value (different or not for each).

我的代码:

import torch
dtype = torch.cuda.FloatTensor 
def main():
     pop, xmax, xmin   = 30, 5, -5
     x                 = (xmax-xmin)*torch.rand(pop).type(dtype)+xmin
     y                 = torch.pow(x, 2)
     [miny, indexmin]  = y.min(0)
     gxbest            = x[indexmin] 
     pxbest            = x
     pybest            = y
     v = torch.rand(pop)
     vnext = torch.rand()*v + torch.rand()*(pxbest - x) + torch.rand()*(gxbest - x)

main()

最好的方法是什么?我想我应该如何将 gxbest 转换为大小为 30 的 torch.FloatTensor 但我该怎么做呢? 我尝试创建一个矢量:

Variable(torch.from_numpy(np.ones(pop)))*gxbest

但是没有用。乘法也不起作用。

运行时错误:张量大小不一致

谢谢大家的帮助!

1) How can I add/subtract a constant torch.FloatTensor of size 1 to all of the elements of a torch.FloatTensor of size 30?

在pytorch 0.2中可以直接做。

import torch

a = torch.randn(30)
b = torch.randn(1)
print(a-b)

如果由于大小不匹配而出现任何错误,您可以按如下方式进行小的更改。

print(a-b.expand(a.size(0))) # to make both a and b tensor of same shape

2) How can I multiply each element of a torch.FloatTensor of size 30 by a random value (different or not for each)?

在pytorch 0.2中,你也可以直接做。

import torch

a = torch.randn(30)
b = torch.randn(1)
print(a*b)

如果由于大小不匹配而出现错误,请执行以下操作。

print(a*b.expand(a.size(0)))

因此,在您的情况下,您可以简单地将 gxbest 张量的大小从 1 更改为 30,如下所示。

gxbest = gxbest.expand(30)