0

Look at this simple optimization problem which had just a bit of complexity (penalty function): enter image description here

I checked scipy and pulp library documentation in Python. I know that I can use "def" for my objective but it doesnt work even in a simple problem - I'm confused and don't know which solver or method should be used to solve it. Even I try the easiest form of penalty function as shown below, a problem which just should try 4 given numbers instead of the y variable to minimize penalty function as objective (the answer is clearly y=-2 and the obj function will be -4):

from scipy.optimize import minimize
import numpy as np

def f(y):
    if y>=0:
        return y
    else:
        return 2*y

y = np.array([1,-1,2,-2])

res = minimize(f(y),args = [y])     

But I am faced with this error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Please help me to know how I should code this penalty function, and which other library or method I should use.

1 Answer 1

1

Your function here is a scalar function and minimize takes a vector function as input.

In your case, you'd prefer using minimize_scalar which takes a scalar function as input:

from scipy.optimize import minimize_scalar

def f(y):
    if y >= 0:
        return y
    else:
        return 2 * y 
    
minimize_scalar(f, bounds=(-2, 1), method='bounded')

#     fun: -3.9999930649182844
# message: 'Solution found.'
#    nfev: 28
#  status: 0
# success: True
#       x: -1.9999965324591422
Sign up to request clarification or add additional context in comments.

2 Comments

i have just tried to make my problem simpler but my real problem had inputs as vector(7 dimensional vector). i guess error was related to how i define y values and as you correct ,it is about method and mention to being scaler. it seems this way of defining function in objective works ,so it may solve my higher dimensional problem too. thanks
Glad to help! If it doesn't work, you can ask a new question with a function which matches your problem better :)

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.