你如何在 Python 中使用 curve_fit?

How Do You Use curve_fit in Python?

我正在使用 curve_fit(来自 scipy.optimze)来解决以下问题:

我的 y 轴是

si = np.log([426.0938, 259.2896, 166.8042, 80.9248])

我的 x 轴是

b = np.array([50,300,600,1000])

我正在记录 y 轴,因为我的原始方程是

si = exp(b * a) 

我想计算 a 但我假设它是曲线的斜率?

def fun(x,a):
 return np.dot(x,a)

popt, pcov = curve_fit(func,b,si)
print(popt)
[1.]

我真的不明白如何在我的方程中使用从 curve_fit 获得的 popt 数据。

我不明白你在做什么,但是popt基本上是a的估计值。在您的情况下,它是从 0 开始的线性函数的斜率值(没有截距值):

f(x) = a*x

因为不能正确拟合数据,最好使用带截距的线性函数:

f(x) = a*x + b

定义如下:

def fun(x,a,b):
    return a * x + b

基本上,在 运行 您的示例之后,您将获得适合您的示例数据的线性函数的最佳参数(a 斜率和 b 截距)。 下面是带有结果的完整示例:

from scipy.optimize import curve_fit
import numpy as np

# e^(a * b)
e_exp_a_x_b = [426.0938, 259.2896, 166.8042, 80.9248]
# a * b
a_x_b = np.log(e_exp_a_x_b)
# b
b = np.array([50,300,600,1000])

def fun(x,a_slope,b_intercept):
    return a_slope * x + b_intercept

import matplotlib.pyplot as plt
plt.figure(figsize=(6, 4))
x_data = b
y_data = a_x_b

popt, pcov = curve_fit(fun, b, a_x_b)
plt.scatter(x_data, y_data, label='Data')
plt.plot(x_data, fun(x_data, popt[0], popt[1]),
         label='Fitted function')
plt.legend(loc='best')
plt.show()

如果您首先目视检查要传递给 curve_fit() 的数据的散点图,您会看到(如@Nikaido 的回答)数据似乎位于一条直线上。这是一个类似于@Nikaido 提供的图形 Python 钳工:

import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

# the "dtype=float" ensures floating point numbers,
# otherwise this would be a numpy array of integers
b = numpy.array([50,300,600,1000], dtype=float)

# these are already floating point numbers
si = numpy.log([426.0938, 259.2896, 166.8042, 80.9248])

# alias data names to match previous example code
xData = b
yData = si

def func(x, slope, offset):
    return slope * x + offset


# same as the scipy defaults
initialParameters = numpy.array([1.0, 1.0])

# curve fit the test data
fittedParameters, pcov = curve_fit(func, xData, yData, initialParameters)

modelPredictions = func(xData, *fittedParameters) 

absError = modelPredictions - yData

SE = numpy.square(absError) # squared errors
MSE = numpy.mean(SE) # mean squared errors
RMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))

print('Parameters:', fittedParameters)
print('RMSE:', RMSE)
print('R-squared:', Rsquared)

print()


##########################################################
# graphics output section
def ModelAndScatterPlot(graphWidth, graphHeight):
    f = plt.figure(figsize=(graphWidth/100.0, graphHeight/100.0), dpi=100)
    axes = f.add_subplot(111)

    # first the raw data as a scatter plot
    axes.plot(xData, yData,  'D')

    # create data for the fitted equation plot
    xModel = numpy.linspace(min(xData), max(xData))
    yModel = func(xModel, *fittedParameters)

    # now the model as a line plot
    axes.plot(xModel, yModel)

    axes.set_xlabel('X Data') # X axis data label
    axes.set_ylabel('Y Data') # Y axis data label

    plt.show()
    plt.close('all') # clean up after using pyplot

graphWidth = 800
graphHeight = 600
ModelAndScatterPlot(graphWidth, graphHeight)