【问题标题】:Assign variable in pytorch在pytorch中分配变量
【发布时间】:2018-04-26 13:35:26
【问题描述】:

我想知道以下代码是否可行,但现在使用 pytorch,其中 dtype = torch.cuda.FloatTensor。有代码直接python(使用numpy):基本上我想得到产生适应度最小值的x值。

import numpy as np
import random as rand
xmax, xmin       = 5, -5
pop              = 30
x                = (xmax-xmin)*rand.random(pop,1)
y                = x**2
[minz, indexmin] = np.amin(y), np.argmin(y)  
best             = x[indexmin]  

这是我的尝试:

import torch
dtype = torch.cuda.FloatTensor 
def fit (x):
    return  x**2
def main():
    pop              = 30
    xmax, xmin       = 5, -5
    x                = (xmax-xmin)*torch.rand(pop, 1).type(dtype)+xmin
    y                = fit(x)
    [miny, indexmin] = torch.min(y,0)
    best             = x[indexmin] 
main()

我将变量最好定义为索引等于 indexmin 的 x 值的最后一部分不起作用。我在这里做错了什么。

出现如下信息:RuntimeError:

expecting vector of indices at /opt/conda/conda-bld/pytorch_1501971235237/work/pytorch-0.1.12/torch/lib/THC/generic/THCTensorIndex.cu:405

【问题讨论】:

    标签: gpu assign pytorch


    【解决方案1】:

    您可以简单地执行以下操作。

    import torch
    dtype = torch.cuda.FloatTensor 
    def main():
        pop, xmax, xmin  = 30, 5, -5
        x                = (xmax-xmin)*torch.rand(pop, 1).type(dtype)+xmin
        y                = torch.pow(x, 2)
        [miny, indexmin] = y.min(0)
        best             = x.squeeze()[indexmin] # squeeze x to make it 1d
    
    main()
    

    【讨论】:

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