5

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

1 Answer 1

4

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?

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your reply! My problem is that I need (well, it has been convenient so far) to use a numpy array as the input to my function. If I understand the lingo correctly, your function uses a list. I've changed your code to demonstrate what happens to me: 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) print(xopt)
Sorry, that looks insane! I'll reformat and add an edit to my original post.
I think the problem occurs if you modify the shape of the input x. If you need to modify x, instead may a copy: y=x.copy(). Then do the computations on y.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.