0

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.

Vdass
  • 3
  • 2

1 Answers1

2

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
Suneesh Jacob
  • 806
  • 1
  • 7
  • 15
  • Does it give local minima or global minima? I want to find global minima. – Vdass Aug 23 '21 at 18:18
  • The function is a quadratic functio in **s**. And so, if you set its derivative to zero, it would be a linear equation, which means there would be a single stationary point. And so, if it is an optimal point then it would be the only existing optimal point. So, even though the algorithm finds local optimum, the local optimum equals the global optimum in this particular case. – Suneesh Jacob Aug 23 '21 at 21:02
  • Thanks for the lucid explanation. – Vdass Aug 24 '21 at 09:15