首页 文章

在pytorch中分配变量

提问于
浏览
0

I'd like to know if it is possble to the following code, but now using pytorch, where dtype = torch.cuda.FloatTensor. There's the code straight python (using 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]

This is my attempt to do it:

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

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

The following messenge appears: RuntimeError:

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

1 回答

  • 0

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

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

相关问题