【问题标题】:Add a constant variable to a cuda.FloatTensor将常量变量添加到 cuda.FloatTensor
【发布时间】:2018-04-26 16:45:35
【问题描述】:

我有两个问题:

1) 我想知道如何将大小为 1 的常量 torch.FloatTensor 添加/减去大小为 30 的 torch.FloatTensor 的所有元素。

2) 我如何将大小为 30 的 torch.FloatTensor 的每个元素乘以一个随机值(每个元素不同或不同)。

我的代码:

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

但它没有工作。乘法也不起作用。

RuntimeError:张量大小不一致

感谢大家的帮助!

【问题讨论】:

    标签: gpu pytorch


    【解决方案1】:

    1) 如何将大小为 1 的常量 torch.FloatTensor 添加/减去大小为 30 的 torch.FloatTensor 的所有元素?

    您可以直接在 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) 如何将大小为 30 的 torch.FloatTensor 的每个元素乘以一个随机值(每个元素不同或不同)?

    在 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多