Demaunt
Demaunt

Reputation: 1243

python scipy brute optimization

I want to find some_arg value that would minimize the function.

1) imports

from scipy import optimize
import math as m

2) calculating original 2*sin(t) data

time_steps = list(range(0,20))

def my_sin(time_steps):   
    sin_data = list()
    for time_step in time_steps:
        sin_data.append(2*m.sin(time_step))
    return sin_data

my_sin_data = my_sin(time_steps)

3) setting error i want to minimize

def fun_to_brute(z, *params):
    some_argument = z
    sum_of_errors = 0
    for time_step in params[0]:
        sum_of_errors = sum_of_errors + some_argument*m.sin(time_step) - params[1][time_step]
    return sum_of_errors

4) Finally starting brute

rranges = [slice(-4, 4, 0.25)]
params = (time_steps, my_sin_data)
resbrute = optimize.brute(fun_to_brute, rranges, args = params, full_output=True)

But the results I get are wrong. I want brute force to make some_arg value 2, in this case sum_of_errors_must be equal zero.

But resbrute[0] returns some strange value

Upvotes: 1

Views: 3253

Answers (1)

Benjamin
Benjamin

Reputation: 11860

If I'm reading this right, you are just trying to recover the scaling factor of 2 that you applied in your original data.

You can simplify things a bit. Note that the range and args parameters ask for tuples. Note also that the thing you are looking for is what should be the main parameter of the function you are calling.

Normally you would minimize the sum of squared residuals or some other error measure by comparing the difference between the model, as it is calculated using your parameter_of_interest, and as it is in your experimental data:

import numpy
import scipy
from scipy import optimize

def f(param_of_interest, *args):

    sin_data = args[0]
    time_steps = args[1]

    model = param_of_interest * numpy.sin(time_steps)
    ssq_residuals = numpy.sum((model - sin_data) ** 2)
    return ssq_residuals

# Your input data
time_steps = numpy.arange(20)
factor = 2
sin_data = factor * numpy.sin(time_steps)

result= scipy.optimize.brute(f,
                             (slice(-4, 4, 0.25),),
                             args=(sin_data, time_steps),
                             full_output=True)
print(result) # Gives expected answer of 2.

Upvotes: 2

Related Questions