Можем ли мы найти значение конкретного подходящего параметра из квадратного уравнения? - PullRequest
1 голос
/ 24 октября 2019

В следующем коде я хочу найти значение подгоночного параметра v. Я знаю, что степенное отношение должно сохраняться для моих точек данных. Но я лучше всего подхожу к своим точкам данных, когда подхожу к квадратному уравнению. Но в квадратном уравнении, что будет v? Если я подхожу к степенному закону, тогда ошибка велика, что мне делать в такой ситуации? Fitting Quadratic equation Fitting a power law

`import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import math
import scipy 
from scipy import optimize

fig = plt.figure()
ax= fig.add_subplot(111)

x_data = np.array([21,42,63,84]) 
y_data= np.array([0.14829848, 0.08196068, 0.04347054, 0.03137703])

def power_law(L,v):
    return (L**(-1/v))

def ff(L,a,b,Ec):
    return (a*(L)**2 + b*L +Ec) 

ax2.scatter(x_data, y_data, marker='s',s=4**2,)


pfit,pcov = optimize.curve_fit(ff,x_data,y_data)
print("pfit: ",pfit)
print("pcov: ",pcov.shape)
#print(pcov)
perr = np.sqrt(np.diag(pcov))
x=np.linspace(20,85,1000)

ax2.plot(x,ff(x,*pfit),color='red')`

1 Ответ

1 голос
/ 24 октября 2019

Квадратичное уравнение в вашем коде имеет смещение. Уравнение степенного закона также нуждается в смещении. Вот графический установщик Python, использующий ваши данные и степенной закон из вашего кода плюс смещение.

plot

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


xData = numpy.array([21,42,63,84], dtype=float) 
yData= numpy.array([0.14829848, 0.08196068, 0.04347054, 0.03137703])


def func(L, v, offset):
    return (L**(-1.0/v)) + offset


# these are the 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)
...