Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimizing python function that has numpy array as argument

I'm new to python, and I have the following problem: I am trying to minimize a python function that has a numpy array as one of its arguments. When I use scipy.optimize.fmin, it turns my array into a list (which results in the function failing to evaluate). Is there an optimization function that does accept numpy arrays as function arguments?

Thanks in advance!

-MB

Edit: Here is an example of what I'm talking about, courtesy of @EOL:

import scipy.optimize as optimize
import numpy as np

def rosen(x):
    print x
    x=x[0]
    """The Rosenbrock function"""
    return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)
x0 = np.array([[1.3, 0.7, 0.8, 1.9, 1.2]])
xopt = optimize.fmin(rosen, x0, xtol=1e-8, disp=True)
#[ 1.3  0.7  0.8  1.9  1.2]
#(note that this used to be a numpy array of length 0, 
#now it's "lost" a set of brackets")
like image 223
MBB Avatar asked Oct 10 '22 16:10

MBB


1 Answers

Here is an example using optimize.fmin which comes from the scipy tutorial:

import scipy.optimize as optimize
def rosen(x):
    """The Rosenbrock function"""
    return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)
x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
xopt = optimize.fmin(rosen, x0, xtol=1e-8, disp=True)
# Optimization terminated successfully.
#          Current function value: 0.000000
#          Iterations: 339
#          Function evaluations: 571
print(xopt)
# [ 1.  1.  1.  1.  1.]

Does this help? If not, can you modify this example to show what is turning into a list?

like image 129
unutbu Avatar answered Oct 12 '22 05:10

unutbu