python - Curve_Fit 的结果不正确

标签 python curve-fitting scipy-optimize

我试图使用非线性参数估计重现论文中的一些结果,但是问题是,当我使用curve_fit时,我得到的只是一个由 1 组成的数组,而不是任何接近我应该得到的结果。

我提供了一个最小的工作示例来说明我得到的结果以及实际结果:

import pandas as pd
import numpy as np
from scipy.optimize import curve_fit

xdata = np.array([0.00, 27.01,84.15,134.66,178.74,217.00,250.20,279.06,304.24, 
                  326.29,346.71,362.87,378.13,391.75,403.96,414.96])

ydata = np.array([0.00,440.00,933.00,1154.00,1226.00,1222.00,1185.00,
                 1134.00,1081.00,1031.00,984.00,942.00,904.00,870.00,840.00,814.00])

# Non-Linear Estimation Function
def func(V,A,d):
    return A*V*exp(-1*d*V)

popt, pcov = curve_fit(func,xdata,ydata)

popt
array([1., 1.])

我应该得到的实际结果如下:

param = estimate (standard err)
A = 17.6 (0.132)
d = 5.27 x 10^-3 (2.61 x 10^-5)

最佳答案

Scipy;s curve_fit() 例程使用所有 1.0 值进行初始参数估计(如果未提供)。如果 curve_fit() 无法对初始参数估计做出任何改进,它只会返回它们 - 这就是为什么你得到所有 1.0 的“拟合”参数值。这是一个包含数据和方程的图形 Python 拟合器,使用 scipy 的 Differential_evolution 遗传算法模块为非线性拟合器提供初始参数估计。该 scipy 模块使用拉丁超立方算法来确保对参数空间的彻底搜索,这需要在搜索范围内进行。在此示例中,这些界限是从数据最大值和最小值导出的。请注意,为参数提供范围比给出具体值要容易得多。

plot

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

x = [0.00, 27.01,84.15,134.66,178.74,217.00,250.20,279.06,304.24, 
                  326.29,346.71,362.87,378.13,391.75,403.96,414.96]

y = [0.00,440.00,933.00,1154.00,1226.00,1222.00,1185.00,
                 1134.00,1081.00,1031.00,984.00,942.00,904.00,870.00,840.00,814.00]

xData = numpy.array(x, dtype=float)
yData = numpy.array(y, dtype=float)


# Non-Linear Estimation Function
def func(V,A,d):
    return A*V*numpy.exp(-1.0*d*V)


# function for genetic algorithm to minimize (sum of squared error)
def sumOfSquaredError(parameterTuple):
    warnings.filterwarnings("ignore") # do not print warnings by genetic algorithm
    val = func(xData, *parameterTuple)
    return numpy.sum((yData - val) ** 2.0)


def generate_Initial_Parameters():
    # min and max used for bounds
    maxX = max(xData)
    minX = min(xData)
    #maxY = max(yData)
    #minY = min(yData)

    parameterBounds = []
    parameterBounds.append([minX, maxX/10.0]) # search bounds for A
    parameterBounds.append([minX, maxX/10.0]) # search bounds for d

    # "seed" the numpy random number generator for repeatable results
    result = differential_evolution(sumOfSquaredError, parameterBounds, seed=3)
    return result.x

# by default, differential_evolution completes by calling curve_fit() using parameter bounds
geneticParameters = generate_Initial_Parameters()

# now call curve_fit without passing bounds from the genetic algorithm,
# just in case the best fit parameters are aoutside those bounds
fittedParameters, pcov = curve_fit(func, xData, yData, geneticParameters)
print('Fitted parameters:', fittedParameters)
print()

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()
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)

关于python - Curve_Fit 的结果不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59851728/

相关文章:

python - 使用 PyODBC 从 Linux 连接到 SQL Server

Python Netcat 代码,模块 main()

python - 使用 Python 拟合 3D 多项式曲面

r - 在 r 的 S 形曲线上找到一个点

python - 使用 Scipy 在 Python 中进行曲线拟合

python - scipy.optimize.minimize_scalar() 在目标函数内向辅助函数结果添加约束?

python - Django 装置 : Importing Nested Models

python - 在 Scientific Linux 上激活 Anaconda 环境

Matlab:直方图数据与许多高斯和 AIC 评估的拟合

python-3.x - scipy.optimize.minimize : Iteration limit exceeded