分配torch.cuda.FloatTensor

时间:2017-11-13 15:16:37

标签: numpy gpu pytorch

我想知道如何执行以下代码,但现在使用pytorch, 其中dtype = torch.cuda.FloatTensor 。代码是直接python(使用numpy):

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 (position):
    return  position**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]
    print(best)  

我最好将变量定义为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)

以上代码在pytorch 0.2中正常工作。让我分析一下你的代码,以便找出问题所在。

x= (xmax-xmin)*torch.rand(pop, 1).type(dtype)+xmin
y = fit(x)

此处,xy是形状30x1的二维张量。在下一行:

[miny, indexmin] = torch.min(y,0)

返回的张量miny是2d张量的形状30x1indexmin是1d张量的大小1。所以,当你执行:

best = x[indexmin]

它(可能)给出错误(在旧的pytorch版本中),因为x是2d张量的形状30x1indexmin是1d张量的大小1。要解决此错误,您只需执行以下操作:

best = x.squeeze()[indexmin] # x.squeeze() returns a 1d tensor of size `30`

请注意,形状30x1的2d张量与尺寸30的1d张量相同。因此,您可以按如下方式修改程序。

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)
    minz, indexmin = y.min(0)
    best = x[indexmin]
    print(best)

main()