【发布时间】:2021-05-24 18:23:35
【问题描述】:
我无法用方程式来拟合我的观点。 它绘制一条水平线。 我的印象是它来自初始参数,但我不知道该放什么。 我从另一个论坛获取了这段代码。 一开始一切正常,但是当我输入新数据时,出现了问题。
有人可以帮帮我吗?
***import numpy as np, scipy, matplotlib
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from scipy.optimize import differential_evolution
import warnings
xData = np.array([.26, .35, .36, .37, .42, .46, .48, .54, .59, .72, .74, .83, .88, 1.04, 1.10, 1.12, 1.48])
yData = np.array([27.40, 29.96, 27.50, 28.20, 32.47, 31.52, 31.00, 34.93, 32.80, 35.84, 39.50, 40.00, 41.35, 41.50, 42.79, 41.71, 46.23])
def func(x, a, b, Offset): # Sigmoid A With Offset from zunzun.com
return 1.0 / (1.0 + np.exp(-a * (x-b))) + Offset
# 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 np.sum((yData - val) ** 2.0)
# generate initial parameter values
geneticParameters = [0,0,0]
# curve fit the test data
fittedParameters, pcov = curve_fit(func, xData, yData, geneticParameters)
print('Parameters', fittedParameters)
modelPredictions = func(xData, *fittedParameters)
absError = modelPredictions - yData
SE = np.square(absError) # squared errors
MSE = np.mean(SE) # mean squared errors
RMSE = np.sqrt(MSE) # Root Mean Squared Error, RMSE
Rsquared = 1.0 - (np.var(absError) / np.var(yData))
print('RMSE:', RMSE)
print('R-squared:', Rsquared)
##########################################################
# 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 = np.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 = 400
graphHeight = 300
ModelAndScatterPlot(graphWidth, graphHeight)***
【问题讨论】:
-
你的适合度很可能不会收敛。尝试找到更好的启动参数
-
您的主要问题是拟合函数的幅度仅为 1,而数据跨度约为 20。您缺少幅度参数。
标签: python line curve data-fitting