pythonnumpyscipyderivativeminima

Is there a way to calculate minima of a function


I have a function similar to square error. It goes till n (n ~ 1000)

f(s) = (d1 - sd'1)**2 + (d2 - sd'2)**2 + .... + (dn - sd'n)**2

I have 2 lists

d = [0.0322, 0.245, 0.85 ..... n]
d' = [56, 200, 340 ..... n] 

I want to calculate the global minima of this function(find s ?). I know I can try scipy optimizer(http://scipy-lectures.org/intro/scipy/auto_examples/plot_optimize_example2.html) to calculate this but I am not able to form the function like they did on their documentation like below.

def f(x):
    return x**2 + 10*np.sin(x)

How do I can form this f(x) based on my function? If there is any more optimize way to do this please mention it.


Solution

  • You can use this code:

    from scipy.optimize import minimize_scalar
    
    def f(s,d1,d2):
        return sum([(d1[i]-s*d2[i])**2 for i in range(len(d1))])
    
    d1_list = [0.0322, 0.245, 0.85]
    d2_list = [56, 200, 340]
    
    res = minimize_scalar(f, args=(d1_list,d2_list))
    print(res.x)
    

    Output:

    0.0021406813829251007