问题描述
我正在分析一些数据,需要进行对数曲线拟合。我试图使用scipy.optimize.curve_fit()函数,但是它不起作用。我在做什么错了?
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
a1 = [0.156,0.250,0.294,0.377,0.474,0.582,0.600,0.650,0.800,0.708]
a2 = [0.274,0.242,0.402,0.424,0.540,0.564,0.707,0.728,0.866,0.582]
t1 = [30,80.53,120,180,270,360,450,600,1200,1813]
t2 = [85.37,460,900,1800]
x1 = np.array(t1)
x2 = np.array(t2)
y1 = np.array(a1)
y2 = np.array(a2)
plt.scatter(x1,y1,label= 'Parallel 1',color='black')
plt.scatter(x2,y2,label= 'Parallel 2',color='green')
def logaritmic(x,a,b,c):
return (a+b*np.log(x) + c)
x_reg = np.linspace(0,2000,50)
popt1,pcov1 = curve_fit(logaritmic,x1,y1)
popt2,pcov2 = curve_fit(logaritmic,x2,y2)
plt.plot(x_reg,logaritmic(x_reg,*popt1),color='gray')
plt.plot(x_reg,*popt2),color='lightblue')
plt.legend()
plt.show()
解决方法
函数curve_fit
不是numpy的一部分,因此请确保从scipy导入并直接调用(而不是np.curve_fit
)。
from scipy.optimize import curve_fit
popt1,pcov1 = curve_fit(logaritmic,x1,y1) # Instead of np.curve_fit
popt2,pcov2 = curve_fit(logaritmic,x2,y2)