python - 在强制曲线形状的同时拟合数据点
问题描述
我正在尝试用多项式曲线拟合 2D 数据点;见下图。蓝点是数据。蓝色的虚线是拟合这些点的二阶多项式。我想强制我的拟合具有与黑线完全相同的形状,并且我想计算新拟合与黑色曲线的 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
正如您在文档中看到的那样,您可以使用适合的参数定义自己的函数。拟合完成后,您可以计算 y 偏移量(相对于原点?),只需计算x=0
. 下面我向您展示了一个示例代码,其中我使用了根函数(这就是您的黑色曲线的样子):
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))
我没有足够的声誉来发布这个情节,但只是运行代码来看看自己。
推荐阅读
- python - 如何使用 \w+ 将单词与数字分开(不使用 A-Ba-b 或 \d)?
- zip - 在 Google Colab 中解压缩图像目录不会解压缩整个内容
- spring-boot - 如何使用spring data jpa仅选择那些大于修改时间的行
- spring-boot - 无法在 Spring Boot JPA 中使用 org.springframework.data.util.Pair
- python - 如何获取此 Python 代码以将字符串 email_one 中出现的 lst1 中的所有项目替换为 lst2 中的相应索引元素?
- python - 从 __init__ 获取文件名
- angular - 我将如何组合来自两个 Observable 的结果,但如果一个 observable 的返回比另一个更快,我将如何使用它的结果?
- python - Python:为什么 0.01.as_integer_ratio() 返回 5764607523034235/576460752303423488
- excel - VBA For Next 循环无法正常工作的问题
- python - 错误:TypeError:不能将序列乘以“numpy.float64”类型的非整数