在pytorch中分配变量

时间:2017-11-13 19:00:52

标签: gpu assign pytorch

我想知道是否可以使用以下代码,但现在使用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()

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

出现以下消息: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 :(得分: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()