'How to use the least_square function from Scipy

I am trying to understand how the least_square function works. I have checked the documentation and the following link (example least_sqr) which gives me a step-by-step process that I can follow. However, I cannot get my code to fit some data. The error I am getting is that the arrays are from different sizes. I am quite sure the true issue is that I don't understand what the function is doing.

Summary of what I know: with a residual function the leastsqr should calculate the difference from the data to the fitting, and return parameters which that best fit the data

What I can't understand: in general we give to the leastsqr (1.function; 2. x0 = array of initial values, 3. args = (xdata, ydata)).

However, the error I am getting is saying that the arrays are not the same size, but they should not be the same size, if I have an intial values array of len(2) and xdata(1000) and ydata(1000)

What I have tried so far:

def func(w,coeffs):   
    ln = 2*(coeffs[0] + (coeffs[1]/w**2))
    ld = (coeffs[0] + (coeffs[1]/w**2) +1 )
    l  = ln/ld

    r  = (2/(1+(coeffs[0]+(coeffs[1]/w**2))))

    res = (l*r)**2
    return res

def residuals(coeffs, y, x):
    return y - func(x, coeffs)

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import leastsq

x = np.linspace(1,10,1000)
y = -3*np.exp(-x)
x0 = np.array([1.5, 6800], dtype=float)
x2, flag = leastsq(residuals, x0, args = (x,y))

Error Message: ValueError: operands could not be broadcast together with shapes (2,) (1000,)

If anyone could explain to me how this function works, I would appreaciate it.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source