1
我在使用curve_fit函數時遇到了問題。任務是解決象徵性的三次方程,然後在擬合函數中使用這個解。將curve_fit函數用於sympy函數時出錯
import numpy as np
import pylab
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from sympy import *
from sympy.utilities.lambdify import lambdify
a, b, c, d, L, k1, k2, E1, E2, x, C0, E0 = symbols("a b c d L k1 k2 E1 E2 x C0 E0", real=True)
sol = solve(Eq(a*L**3 + b*L**2 + c*L + d),L)
sol1 = sol[2].subs({a: k1*k2, b: (k1 + 2*k1*k2*x), c: (1 + k1*x - k1*C0), d: -C0,})
intensity = E0*L + E1*k1*L*x/(1 + k1*L + k1*k2*L**2) \
+ E2*k1*k2*L**2*x/(1 + k1*L + k1*k2*L**2)
E0r=1000.0
C0r=1E-4
function_sym = intensity.subs(L,sol1).subs(E0, E0r).subs(C0, C0r)
funct = lambdify([E1, E2, k1, k2, x],function_sym)
x_exp = np.array([0,1E-5,2E-5,3E-5,4E-5,6E-5,8E-5,1.3E-4])
y_exp = np.array([0,0.081,0.1936,0.264,0.297,0.3567,0.396,0.452])
popt, pcov = curve_fit(funct, x_exp, y_exp, (1000, 1000, 100000, 100000))
它導致錯誤:
ValueError: array must not contain infs or NaNs
我試圖通過獲取function_sym的實部和擬合函數的另一種定義的方式來解決這個問題:
function_re = re(function_sym)
def fit_func(E1r, E2r, k1r, k2r, xr):
return function_re.subs(E1, E1r).subs(E2, E2r).subs(k1, k1r).subs(k2,k2r).subs(x, xr).evalf()
popt, pcov = curve_fit(fit_func, x_exp, y_exp, (1000, 1000, 100000, 100000))
而且它會導致另一個錯誤:
TypeError: unhashable type: 'numpy.ndarray'