Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
运行时错误:在Python中使用曲线拟合_Python_Curve Fitting - Fatal编程技术网

运行时错误:在Python中使用曲线拟合

运行时错误:在Python中使用曲线拟合,python,curve-fitting,Python,Curve Fitting,我是Python新手,我正在尝试使用一个小数据帧并绘制它。但是我还想使用曲线拟合来获得一些参数的值 ######Fitting Using Data Frame###### import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit # Data into a dictionary data = {'keV':[22.16,32.19

我是Python新手,我正在尝试使用一个小数据帧并绘制它。但是我还想使用曲线拟合来获得一些参数的值

######Fitting Using Data Frame######

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

#   Data into a dictionary
data = {'keV':[22.16,32.19,8.05,17.48,13.39,44.47,5],'ToT':[31.68,39.87,10.67,26.38,21.4,53.56,0]}

#   Create dataframe and get only the values of arrays
df = pd.DataFrame(data)
xdata = df['keV'].values
ydata = df['ToT'].values

#   Main function for the mathematical method
def main_test(x, a, b,c,t):
    return a*x +b - c/(x-t)

#   Guess of the fit values
guess = [1,1,100,150]

n = len(xdata)
#   Empty np array that will get these values
y = np.empty(n)
#   Repeat in all these times

c, cov = curve_fit(main_test,xdata,ydata)
#    THE MOST IMPORTANT PART OF THE CODE. TO GET THE PARAMETERS VALUES.
print(c)

for sample in range(n):
#   Populating y with guess numbers = Prediction
   y[sample] = main_test(xdata[sample],a[0],b[1],c[2],t[3])

    plt.figure(figsize=(6,4))
    plt.scatter(xdata,ydata)
    plt.plot(xdata, y,'r.')
    plt.show()

RuntimeError:未找到最佳参数:函数调用数已达到maxfev=1000。

这是一个寻找良好启动参数的问题。这是一个使用数据和方程的图形解算器,使用scipy的微分进化遗传算法模块确定曲线拟合()的初始参数估计。该scipy模块使用拉丁超立方体算法来确保对参数空间的彻底搜索,需要搜索的范围。由于搜索范围非常宽泛,我首先尝试对所有参数使用+/-100.0的搜索范围,这很有效


尝试增加
maxfev
参数?@ItamarMushkin这是开始参数,请查看我对这个问题的答案。谢谢!它工作得非常好。。。现在,我将“解释”并尝试更好地理解您的代码。再次感谢你。最好的结果总是“成功了”。
import numpy, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.optimize import differential_evolution
import warnings

keV = [22.16,32.19,8.05,17.48,13.39,44.47,5]
ToT = [31.68,39.87,10.67,26.38,21.4,53.56,0]

# rename data to re-use previous example code
xData = numpy.array(keV)
yData = numpy.array(ToT)


# mathematical model
def func(x, a, b,c,t):
    return a*x +b - c/(x-t)


# 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():    
    parameterBounds = []
    parameterBounds.append([-100.0, 100.0]) # search bounds for a
    parameterBounds.append([-100.0, 100.0]) # search bounds for b
    parameterBounds.append([-100.0, 100.0]) # search bounds for c
    parameterBounds.append([-100.0, 100.0]) # search bounds for t

    # "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('keV') # X axis data label
    axes.set_ylabel('ToT') # Y axis data label

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

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