'Fit with some complicated function
I am trying to fit data with a complicated function which consists some special function and I have problem with it. It is formula presented here (imgur). To do this I use spicy.optimize.curve. But for simplicity here, I would skip special functions and I want to do a fit with a similiar function. My problem is that I want to fit my data with some functionm which is function of some s, but this s is also hidden in an integral.
Here, just for this post I generated some data with the normal distributions, it is not the good data for my plot, just to run the code. I got an error
only size-1 arrays can be converted to Python scalars
My code is presented below. Thus, the lambda parameter is the one I want to get from the fit.
import numpy as np
from scipy.optimize import curve_fit
import random
from scipy import integrate
def integrand(ξ, s, λ):
return np.exp(-ξ**2-2*ξ*λ)*np.cos(2*ξ*s)
def curve(s, ξ, λ):
return s/λ*np.exp(-s**2/λ**2)*integrate.quad(integrand, 0, np.infty, args=(s, λ))[0]
X = np.random.normal(0, 1, 10)
Y = np.random.normal(0, 1, 10)
X = np.array(X)
Y = np.array(Y)
params, cov = curve_fit(curve, X, Y)
Solution 1:[1]
The problem is that your function "curve" doesn't admit a numpy array or list as an input, but you can vectorize it:
from scipy.optimize import curve_fit
from scipy import integrate
import matplotlib.pyplot as plt
import numpy as np
import random
def integrand(?, s, ?):
return np.exp(-?**2-2*?*?)*np.cos(2*?*s)
@np.vectorize
def curve(s, ?):
return s/?*np.exp(-s**2/?**2)*integrate.quad(integrand, 0, np.infty, args=(s, ?))[0]
x = np.linspace(0,3, 100)
y = curve(x,1) + np.random.normal(0, 0.005, 100)
params, cov = curve_fit(curve, x, y, p0=[0.3])
plt.scatter(x,y, s=4)
plt.plot(x, curve(x,params[0]))
plt.show()
For more elegant ways of vectorizing, try to do your function array compatible, or take a look here:
https://numpy.org/doc/stable/reference/generated/numpy.vectorize.html
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
