猿问

用已知指数拟合幂律并在 Python 中提取系数

我有一个数据集,我知道它适合以下形式的曲线:

y = a x²

我想提取a.

在 Python(使用 scipy 等)中解决这个问题的最佳方法是什么?


不负相思意
浏览 199回答 1
1回答

慕的地6264312

这是使用 scipy 的 curve_fit() 的图形拟合器示例:import numpy, scipy, matplotlibimport matplotlib.pyplot as pltfrom scipy.optimize import curve_fitxData = numpy.array([1.1, 2.2, 3.3, 4.4, 5.0, 6.6, 7.7])yData = numpy.array([1.1, 20.2, 30.3, 60.4, 50.0, 60.6, 70.7])def func(x, a):    return (a * numpy.square(x))# same as the scipy defaultinitialParameters = numpy.array([1.0])# curve fit the test datafittedParameters, pcov = curve_fit(func, xData, yData, initialParameters)modelPredictions = func(xData, *fittedParameters) absError = modelPredictions - yDataSE = numpy.square(absError) # squared errorsMSE = numpy.mean(SE) # mean squared errorsRMSE = numpy.sqrt(MSE) # Root Mean Squared Error, RMSERsquared = 1.0 - (numpy.var(absError) / numpy.var(yData))print('Parameters:', fittedParameters)print('RMSE:', RMSE)print('R-squared:', Rsquared)print()########################################################### graphics output sectiondef 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 pyplotgraphWidth = 800graphHeight = 600ModelAndScatterPlot(graphWidth, graphHeight)
随时随地看视频慕课网APP

相关分类

Python
我要回答