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


This is my attempt to do it:

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)  


The last part where I define the variable best as the value of x with index equal to indexmin it doesn't work. What am I doing wrong here. 

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


The above code works fine in pytorch 0.2. Let me analyze your code so that you can identify the problem.

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


Here, x and y is a 2d tensor of shape 30x1. In the next line: 

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


The returned tensor miny is a 2d tensor of shape 30x1 and indexmin is a 1d tensor of size 1. So, when you execute:

best = x[indexmin]


It (probably) gives error (in old pytorch version) because x is a 2d tensor of shape 30x1 and indexmin is a 1d tensor of size 1. To resolve this error, you can simply do:

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


Please note, a 2d tensor of shape 30x1 is same as a 1d tensor of size 30. So, you can modify your program as follows.

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

