分配 torch.cuda.FloatTensor

Assign torch.cuda.FloatTensor

我想知道如何执行以下代码,但现在使用的是 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)  

我将变量 best 定义为索引等于 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

以上代码在 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 是形状为 30x1 的二维张量,indexmin 是大小为 1 的一维张量。所以,当你执行:

best = x[indexmin]

它(可能)给出错误(在旧的 pytorch 版本中),因为 x 是形状为 30x1 的二维张量,而 indexmin 是大小为 [=22= 的一维张量].要解决此错误,您只需执行以下操作:

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

请注意,形状为 30x1 的二维张量与大小为 30 的一维张量相同。所以,你可以修改你的程序如下。

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