1

I want to define a function :

enter image description here

And I want to find minimum with respect to (a,b) for points :

x = np.array([.2, .5, .8, .9, 1.3, 1.7, 2.1, 2.7])
y = f(x) + np.random.randn(len(x))

Using function : optimize.fmin_cg (you can find documentation here : https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fmin_cg.html)

My work so far

I managed to define a compute_error() function :

def compute_error(a,b):
    k=[0]*len(x)
    for i in range(0,len(x)):
        k[i]=(y[i]-(a*x[i]+b))**2
    return sum(k)

And I tried to minimize it using this optimize function, however I met some problems.

x_0=np.array((0,0))     #start optimization from point (0,0)
 
minimum = optimize.fmin_cg(compute_error,x_0)

TypeError: compute_error() missing 1 required positional argument: 'b'

1 Answer 1

3

I think compute_error should take a two-element array not two separate arguments

def compute_error(params_to_optimize):
    a = params_to_optimize[0]
    b = params_to_optimize[1]
    k=[0]*len(x)
    for i in range(0,len(x)):
        k[i]=(y[i]-(a*x[i]+b))**2
    return sum(k)

also, possibly related, x0 initialization looks a bit weird I would use a list not a tuple in the np.array constructor

x_0=np.array([0,0])
Sign up to request clarification or add additional context in comments.

1 Comment

Two style remarks: 1) you can write a, b = params_to_optimize to unpack the tuple, instead of the two first lines 2) instead of the for loop you can use vector form (for numpy it is generally faster) k = (y - (a*x + b))**2. This way your code will be more readable, concise and error prone.

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.