当我尝试绘制它时,我试图将我的数据拟合到某个函数,我总是得到双线,如下图所示。这是我使用的代码:
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import warnings
from scipy.optimize import differential_evolution
# bounds on parameters are set in generate_Initial_Parameters() below
def func_original(x,a,b,c):
return a/(x**2)+b/x+c
# bounds on parameters are set in generate_Initial_Parameters() below
def func_recommended(x,a,b,c):
return 1/(a*x**2+b*x+c)
# select peak function here
#func = func_original
func = func_recommended
# function for genetic algorithm to minimize (sum of squared error)
# bounds on parameters are set in generate_Initial_Parameters() below
def sumOfSquaredError(parameterTuple):
warnings.filterwarnings("ignore") # do not print warnings by genetic algorithm
return np.sum((yData - func(xData, *parameterTuple)) ** 2)
def generate_Initial_Parameters():
# data min and max used for bounds
maxX = max(xData)
minX = min(xData)
maxY = max(yData)
minY = min(yData)
minSearch = min([minX, minY])
maxSearch = max([maxX, maxY])
parameterBounds = []
parameterBounds.append([minSearch, maxSearch]) # parameter bounds for a
parameterBounds.append([minSearch, maxSearch]) # parameter bounds for b
parameterBounds.append([minSearch, maxSearch]) # parameter bounds for c
# "seed" the numpy random number generator for repeatable results
result = differential_evolution(sumOfSquaredError, parameterBounds, seed=3)
return result.x
# load data from text file
data=np.loadtxt('gammaoh.txt')
use=np.transpose(data)
yData=use[0]
xData=use[2]
# generate initial parameter values
initialParameters = generate_Initial_Parameters()
# curve fit the data
fittedParameters, niepewnosci = curve_fit(func, xData, yData, initialParameters)
# create values for display of fitted peak function
a, b, c = fittedParameters
y_fit = func(xData, a, b, c)
plt.plot(xData, yData, 'bo', label='Puntos experimentais $\gamma_{OH}$', markersize=5)
plt.plot(xData, (1/(xData**2*0.5998-2.29255*xData+1.7988)) , 'b-',label='Axuste $\gamma_{OH}$')
plt.title('Axustes coeficientes de actividade ')
plt.xlabel('$\chi_{H_2O}$ ')
plt.ylabel('$\gamma$')
plt.grid(True)
plt.legend(loc=2)
plt.savefig('gammaoh.png')
如果有人能告诉我如何解决这个问题,我将非常感激,谢谢你提前。此外,如果有人知道更好的方法将数据拟合到给定的函数,那么如果你能告诉我那将是很好的。
答案 0 :(得分:2)
我对你正在解决的问题没有更深入的了解,但为了避免绘图中的额外行,如果列表按照x排序,它就有效。我这样做了:
xData.sort()
tt = (1/(xData**2*0.5998-2.29255*xData+1.7988))
plt.plot(xData, tt , 'b-',label='Axuste $\gamma_{OH}$')