【问题标题】:scipy.optimize_curvefit gives bad resultsscipy.optimize_curvefit 给出了不好的结果
【发布时间】:2026-02-08 12:35:01
【问题描述】:

我正在尝试拟合材料模型(Carreau-Law)。一般来说,数据看起来非常好,但是(至少对我而言)不可能使用curve_fit 获得正确的模型数据和参数。我尝试设置合理的起始值等。

import numpy as np
import matplotlib.pyplot as plt

## Y-DATA
eta = np.array([7128.67, 6814, 6490, 6135.67, 5951.67,
        5753.67, 5350, 4929.33, 4499.33,4068.67, 3641.33,
        3225.33, 2827.33, 2451, 2104.67, 1788, 1503, 1251.33,
        1032.33, 434.199, 271.707, 134.532, 75.7034, 40.9144, 21.7112, 14.9206, 9.29772])


##X-DATA
gamma = np.array([0.1, 0.1426, 0.2034, 0.29, 0.4135, 0.5897, 0.8409, 1.199,
         1.71, 2.438, 3.477, 4.959, 7.071, 10.08, 14.38, 20.5,
         29.24, 41.7, 59.46, 135.438, 279.707, 772.93,
         1709.91, 3734.32, 8082.32, 12665.8, 22353.3])


carreaulaw = lambda x, eta_0, lam, a, n: eta_0 / (1 + (lam * x)**a)**((n-1)/a)

popt, pcov = sp.optimize.curve_fit(carreaulaw, gamma, eta, p0=[8000, 3000, 0.8, 0.1])

print(popt)

x = np.linspace(gamma.min(), gamma.max(), 500)
fig = plt.figure()
diagram = fig.add_axes([0.1, 0.1, 0.8, 0.8])
diagram.set_xlabel(r"$log\ \. \gamma_{true}\ (s^{-1})$", fontsize = 12)
diagram.set_ylabel(r"$log\ \eta_{true}\ (Pa*s)$",fontsize = 12)
#diagram.set_xscale("log")
#diagram.set_yscale("log")
diagram.plot(gamma, eta, "r*")
diagram.plot(x, carreaulaw(x, popt[0], popt[1], popt[2], popt[3]), "g-")

我不断收到错误:RuntimeWarning: invalid value encountered in power。我已经尝试了很多变体,现在非常卡住。

如果我没有给出任何起始值,我会得到:

RuntimeError: Optimal parameters not found: Number of calls to function has reached maxfev = 1000.

这是对数比例的数据图像:

我真的不知道我哪里错了!数据看起来不错,这就是为什么我永远不会用完maxfev

【问题讨论】:

    标签: python numpy scipy curve-fitting


    【解决方案1】:

    这是一个使用您的数据和方程式的图形拟合器。此示例代码使用 scipy 的差分进化遗传算法来确定 curve_fit() 的初始参数估计。这个 scipy 模块使用拉丁超立方算法来确保对参数空间的彻底搜索,这需要搜索范围。找到参数的范围比找到单个值要容易得多,在这里我尝试了不同的界限,直到拟合在视觉上看起来不错。你应该检查我使用的界限,看看它们是否合理。

    import numpy, scipy, matplotlib
    import matplotlib.pyplot as plt
    from scipy.optimize import curve_fit
    from scipy.optimize import differential_evolution
    import warnings
    
    xData = numpy.array([7128.67, 6814, 6490, 6135.67, 5951.67,
            5753.67, 5350, 4929.33, 4499.33,4068.67, 3641.33,
            3225.33, 2827.33, 2451, 2104.67, 1788, 1503, 1251.33,
            1032.33, 434.199, 271.707, 134.532, 75.7034, 40.9144, 21.7112, 14.9206, 9.29772])
    
    yData = numpy.array([0.1, 0.1426, 0.2034, 0.29, 0.4135, 0.5897, 0.8409, 1.199,
             1.71, 2.438, 3.477, 4.959, 7.071, 10.08, 14.38, 20.5,
             29.24, 41.7, 59.46, 135.438, 279.707, 772.93,
             1709.91, 3734.32, 8082.32, 12665.8, 22353.3])
    
    def carreaulaw(x, eta_0, lam, n, a):
        return eta_0 * (1.0+(lam*x)**a)**((n-1.0)/a)
    
    
    # function for genetic algorithm to minimize (sum of squared error)
    def sumOfSquaredError(parameterTuple):
        warnings.filterwarnings("ignore") # do not print warnings by genetic algorithm
        val = carreaulaw(xData, *parameterTuple)
        return numpy.sum((yData - val) ** 2.0)
    
    
    def generate_Initial_Parameters():
    
        parameterBounds = []
        parameterBounds.append([0.0, 50.0]) # search bounds for eta_0
        parameterBounds.append([0.0, 1.0]) # search bounds for lam
        parameterBounds.append([-1.0, 0.0]) # search bounds for n
        parameterBounds.append([-200.0, 0.0]) # search bounds for a
    
        # "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(carreaulaw, xData, yData, geneticParameters)
    print('Fitted parameters:', fittedParameters)
    print()
    
    modelPredictions = carreaulaw(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 = carreaulaw(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)
    

    【讨论】:

    • 非常感谢您的回答,但遗憾的是 x 和 y 数据被调高了!我对那个不清楚的代码输入不好,对不起!如果我改变 x 和 y,我碰巧得到与 curve_fit 相同的错误。但是,您的解释使我非常清楚如何获得正确的界限-谢谢!
    【解决方案2】:

    您需要做的就是通过curve_fit 中的界限。当没有定义边界时,您可以进行非实数运算,例如(在您的情况下)负数的浮点求幂。

    边界被简单地定义为具有上下界的两个列表/元组的列表:

    bounds = [(-np.inf, 0, 0, 0), [np.inf, np.inf, 1, 1]]   #upper np.inf or lower -np.inf means no bound
    popt, pcov = curve_fit(carreaulaw, gamma, eta, p0=[8000, 3000, 0.8, 0.1], bounds=bounds)
    

    输出:

    【讨论】:

    • 感谢您的帮助!但即使有边界,拟合对我来说也只是一条水平线,这真的很奇怪,因为起始参数应该有点接近好的值。
    • 奇怪,我得到了一个合理的匹配(见编辑 - 我用diagram.loglog(...)而不是diagram.plot绘制)
    • 谢谢你,我很抱歉,IDK 为什么我在那里犯了错误,Carruealaw 的正确公式是:eta_0 / (1 + (lam * x)**a)**((n-1)/a) 我得到一条直线,通常适合应该看起来像 @ 987654322@
    • NP,很高兴你修好了!如果您对答案满意,请标记为已解决
    • 遗憾的是,我仍然没有解决我的问题,因为适合使用 Carreaulaw 的“新”形式的 straight line,我真的开始觉得有点愚蠢。非常感谢您抽出时间@Mstaino
    最近更新 更多