繁体   English   中英

在强制曲线形状的同时拟合数据点

[英]Fitting data points while forcing the shape of the curve

我正在尝试用多项式曲线拟合二维数据点; 见下图。 蓝点是数据。 蓝色,虚线是一个2多项式拟合到这些点。 我想强制我的拟合具有与黑线完全相同的形状,并且我想从黑色曲线计算新拟合的 y 偏移量。 关于这如何可能的任何想法? 提前致谢。

x = np.linspace(6.0,12.0,num=100)

a = -0.0864
b = 11.18
c = 9.04
fit_y = a*(x - b)**2 + c # black line

z = np.polyfit(data_x,data_y,2)

zfit=z[2]+z[1]*x+z[0]*x**2

fig, ax = plt.subplots()
ax.plot(data_x,data_y,'.',color='b')
ax.plot(x,fit_y,color='black') #curve of which we want the shape
ax.plot(x,zfit,color='blue',linestyle='dashed') #polynomial fit
ax.set_xlim([6.5,11.0])
ax.set_ylim([6.5,10.5])
plt.show()

数据点和所需的拟合形状

编辑:这是我的问题的解决方案:

x = np.linspace(6.0,12.0,num=100)

# We want to keep a and b fixed to keep the same shape
# a = -0.0864     
# b = 11.18
c = 9.04

#Only c is a variable because we only want to shift the plot on the y axis
def f(x, c):
    return -0.0864*(x - 11.18)**2 + c

popt, pcov = curve_fit(f, data_x, data_y)  # popt are the fitted parameters

plt.plot(data_x, data_y,'.') #blue data points
plt.plot(x,f(x, c),'black') #black line, this is the shape we want our fit to have

plt.plot(x, f(x, *popt), 'red')  # new fitted line to the data (with same shape as black line)

plt.xlim([6.5,11.0])
plt.ylim([6.5,10.5])

plt.show()

print("y offset:", popt[0] - c)

y 偏移量:0.23492393887717355

解决方案

您想使用scipy.optimize.curve_fit 正如您在文档中看到的那样,您可以使用要拟合的参数定义自己的函数fit_y 拟合完成后,您可以简单地计算x=0的函数来计算 y 偏移量(相对于原点?)。 下面我将向您展示我使用根函数的示例代码(这是您的黑色曲线的样子):

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

def f(x, a, b, c):
    return a * np.power(x, b) + c


x_data = np.arange(100)
noise = np.random.normal(size=100)
y_data = np.power(x_data, 0.5) + noise
y = f(x_data, 1, 2, 0.3)  # random values to initialize the fit
popt, _ = curve_fit(f, x_data, y_data)  # popt are the fitted parameters

plt.scatter(x_data, y_data)
plt.plot(x_data, f(x_data, *popt), 'r')  # fitted line
plt.show()

print("y offset:", f(0, *popt))

我没有足够的声誉来发布情节,但只需运行代码即可查看自己。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM