Rosenbrock function with D dimension using PyTorch
How can I implement the Rosenbrock function with D dimension, using PyTorch? 


  Create the variables, where D is the number of dimensions and N is the number of elements.  


x = (xmax - xmin)*torch.rand(N,D).type(dtype) + xmin



  Function : 





  Using straight Python I'd do something like this: 


fit = 0
for i in range(D-1):
    term1 = x[i + 1] - x[i]**2
    term2 = 1 - x[i]
    fit = fit + 100 * term1**2 + term2**2



  My attempt using Pytorch:


def Rosenbrock(x):
    return torch.sum(100*(x - x**2)**2 + (x-1)**2)



  I just do not know how to do the x[i+1] without using a for loop. 
  How can I deal with it? 
  Thank you!


Numpy has the function roll which I think can be really helpful.
Unfortunately, I am not aware of any function similar to numpy.roll for pytorch. 

In my attempt, x is a numpy array in the form DxN. First we use roll to move the items in the first dimension (axis=0) one position to the left. Like this, everytime we compare x_1[i] is like if we do x[i+1]. Then, since the function takes only D-1 elements for the sum, we remove the last column slicing the pytorch tensor with [:-1, :]. Then the summation is really similar to the code you posted, just changing x for x_1 at the correct place.

def Rosenbrock(x):
    x_1 = torch.from_numpy(np.roll(x, -1, axis=0)).float()[:-1, :]
    x = torch.from_numpy(x).float()[:-1, :]

    return torch.sum(100 * (x_1 - x ** 2) ** 2 + (x - 1) ** 2, 0)


Similarly, by using roll you could remove you for loop in the numpy version
