首页 > 编程问答 >用两种类型的函数拟合数据

用两种类型的函数拟合数据

时间:2024-07-24 11:20:49浏览次数:6  
标签:python curve-fitting scipy-optimize least-squares scipy-optimize-minimize

我有数据 x 和 y ,想要将一个部分与 power_fit 相匹配,而另一部分与负 power_fit 最终稳定为零,并从一些 -20nm 开始,具有一些 5nF 值,并在最小值 agian 开始上升并变为零后下降。 |我在某些时候被零除。我使用了两个函数,一个在最小值之前,另一个在最小值之后。将 numpy 导入为 np 将 matplotlib.pyplot 导入为 plt 从 scipy.optimize 导入 curve_fit 将 pandas 导入为 pd  this is the plot for the x,y data, i want to fit this data plot using the best fitting , probabily using the power function as given in code

def fit_data(x, y): # 定义 x <= xmin 的模型函数 def model1(x, a, x0,ymin): n=13 返回 a / (x_adj**n) + ymin

def fit_data(x, y): # Define the model function for x <= xmin def model1(x, a, x0,ymin): n=13 return a / (x_adj**n) + ymin

def model2(x, b, xmin, y0):    # Define the model function for x > xmin
    m=7
    x_adj = x - xmin
    return -b / (x_adj**m) + y0
x_data = np.array(x)
y_data = np.array(y)
ymin = np.min(y_data)
xmin = x_data[np.argmin(y_data)]
mask1 = x_data <= xmin
mask2 = x_data > xmin

x_data1 = x_data[mask1]
y_data1 = y_data[mask1]

x_data2 = x_data[mask2]
y_data2 = y_data[mask2]

# Initial parameter guesses
initial_guess1 = [1e-9, x_data1[0], ymin] # a, x0,ymin
initial_guess2 = [1e-9, xmin, 0]  # y0 will be optimized: b, xmin, y0

# Perform the curve fitting for both regions
popt1, pcov1 = curve_fit(model1, x_data1, y_data1, p0=initial_guess1, bounds=bounds1)
popt2, pcov2 = curve_fit(model2, x_data2, y_data2, p0=initial_guess2, bounds=bounds2)

# Generate fitted y values for both regions
y_fitted1 = model1(x_data1, *popt1)
y_fitted2 = model2(x_data2, *popt2)

x_fitted = np.concatenate([x_data1, x_data2])
y_fitted = np.concatenate([y_fitted1, y_fitted2])

# Plot the original data and the fitted curve
plt.scatter(x_data, y_data, label='Data', color='red')
plt.plot(x_fitted, y_fitted, label='Fitted Curve', color='blue')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.title('Non-linear Fit')
plt.show()

# Print the fitted parameters
print(f'Fitted parameters for region 1: a = {popt1[0]}, x0 = {popt1[1]},  ymin = {popt1[2]}')
print(f'Fitted parameters for region 2: b = {popt2[0]}, xmin = {popt2[1]}, y0 = {popt2[2]}')

以下是使用两个函数将数据拟合到的数据的细分方法:

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

# Sample data (replace with your actual data)
x_data = np.array([-20, -15, -10, -5, 0, 5, 10, 15, 20])
y_data = np.array([10, 6, 4, 3, 1, 3, 4, 5, 5.5]) 

# Define the model functions
def model1(x, a, n, x0, ymin):
    """Power function with an offset."""
    return a / ((x - x0)**n) + ymin

def model2(x, b, m, x1, y0):
    """Negative power function with an offset, asymptotically approaching zero."""
    return -b / ((x - x1)**m) + y0

# Find the index of the minimum y value
min_index = np.argmin(y_data)

# Split the data into two regions
x_data1 = x_data[:min_index + 1]
y_data1 = y_data[:min_index + 1]
x_data2 = x_data[min_index:]
y_data2 = y_data[min_index:]

# Initial parameter guesses
initial_guess1 = [1, 2, -5, 1]  # Adjust for model1
initial_guess2 = [1, 2, -5, 0]  # Adjust for model2

# Set bounds to prevent division by zero and guide the optimization
bounds1 = ([0, 0, -np.inf, -np.inf], [np.inf, np.inf, np.inf, np.inf])
bounds2 = ([0, 0, -np.inf, -np.inf], [np.inf, np.inf, np.inf, np.inf])

# Perform the curve fitting for both regions
popt1, pcov1 = curve_fit(model1, x_data1, y_data1, p0=initial_guess1, bounds=bounds1)
popt2, pcov2 = curve_fit(model2, x_data2, y_data2, p0=initial_guess2, bounds=bounds2)

# Generate fitted y values for both regions
y_fitted1 = model1(x_data1, *popt1)
y_fitted2 = model2(x_data2, *popt2)

# Combine fitted data for plotting
x_fitted = np.concatenate([x_data1, x_data2])
y_fitted = np.concatenate([y_fitted1, y_fitted2])

# Plot the original data and the fitted curves
plt.scatter(x_data, y_data, label='Data', color='red')
plt.plot(x_data1, y_fitted1, label='Fitted Curve 1', color='blue')
plt.plot(x_data2, y_fitted2, label='Fitted Curve 2', color='green')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.title('Non-linear Fit with Two Functions')
plt.show()

# Print the fitted parameters
print(f'Fitted parameters for region 1: {popt1}')
print(f'Fitted parameters for region 2: {popt2}')

说明:

  1. 导入: 导入必要的库 ( numpy , matplotlib.pyplot , scipy.optimize ).
  2. 示例数据: 替换为的实际 x_data y_data
  3. 模型函数:
  4. model1(x, a, n, x0, ymin) :这表示最小值之前的部分。它是一个具有偏移量的幂函数。调整 n 以控制曲线的陡度。
  5. model2(x, b, m, x1, y0) :这表示最小值之后的部分。它是一个负幂函数,随着 x 的增加而渐近地接近零。
  6. 数据拆分: 找到 y_data 中最小值的索引 ( min_index ),并使用它将数据拆分为两个区域。
  7. 初始猜测和边界:
  8. 为两个模型的拟合参数提供 initial_guess1 initial_guess2 。根据的数据调整这些猜测。
  9. bounds 有助于防止除以零的错误,并可以指导优化器获得良好的拟合。
  10. 曲线拟合: 使用 curve_fit 分别将每个模型拟合到相应的数据区域。
  11. 生成拟合数据: 使用拟合参数和模型函数生成拟合的 y 值。
  12. 绘图: 绘制原始数据、两个拟合曲线以及标签和标题。
  13. 打印参数: 打印两个区域的拟合参数。

提示:

  • 仔细选择初始猜测和边界对于获得良好的拟合至关重要。尝试不同的值,看看它们如何影响拟合。
  • 如果的数据嘈杂,可能需要考虑使用更稳健的拟合方法或对数据进行预处理以减少噪声。
  • 可以调整模型函数以更好地表示的数据。例如,可以尝试使用不同的函数形式或添加更多参数。

标签:python,curve-fitting,scipy-optimize,least-squares,scipy-optimize-minimize
From: 78785980

相关文章

  • 你能对 Python 类型注释进行模式匹配吗?
    你能在Python类型上进行模式匹配吗?我见过简单的例子:importbuiltinsmatchx:casebuiltins.str:print("matchedstr")casebuildins.int:print("matchedint")但我想在嵌套类型上进行模式匹配,比如Annotated[Optional[Literal["a",......
  • python Polars:替换嵌套列表的元素
    有谁知道是否可以有效地替换极坐标中嵌套列表的元素。例如:s=pl.Series('s',[[1,2,3],[3,4,5]])#replace3with10toget[[1,2,10],[10,4,5]]我已经尝试过s.to_frame().with_columns(pl.when(pl.col('s')==3)...)但是pl.when不喜欢List[bo......
  • Python 中的常量应该大写吗?
    在PEP8中,一般规则是在UPPER_CASE字符中声明常量。在现实生活中,可能有多种情况:#!envpythonDATABASE_HOST='localhost'app=Flask('myapp')base_two=partial(int,base=2)通常我们将字符串类型或数字类型变量视为不可变的,因此是常量,而不是对象或函数。问题是......
  • 多重处理会导致 Python 崩溃,并给出一个错误:调用 fork() 时可能已在另一个线程中进行
    我对Python比较陌生,并试图为我的for循环实现一个多处理模块。我在img_urls中存储了一个图像url数组,我需要下载并应用一些Google视觉。if__name__=='__main__':img_urls=[ALL_MY_Image_URLS]runAll(img_urls)print("---%sseconds---"%(......
  • Python编程时输入操作数错误
    我正在用Python编写下面的代码来模拟控制系统。但是,当我调试代码时,我面临以下问题:matmul:输入操作数1没有足够的维度(有0,gufunc核心,签名为(n?,k),(k,m?)->(n?,m?)需要1)文件“D:\ÁreadeTrabalho\GitHub\TCC\CódigosMarcela\SistemaSISO_tres_estados_new.py”,......
  • Python入门知识点 7--散列类型与字符编码
    1、初识散列类型(无序序列)数据类型分为3种:   前面已经学过了两种类型   1.数值类型:int/float/bool只能存储单个数据      2.序列类型:str/list/tuple,有序的存储多个数据--有序类型,有下标,可以进行索引切片步长操作          3.散列类型......
  • Python入门知识点 6--序列类型的方法
    1、初识序列类型方法序列类型的概念:数据的集合,在序列类型里面可以存放任意的数据也可以对数据进行更方便的操作这个操作就是叫增删改查(crud)(增加(Creat),读取查询(Retrieve),更新(Update),删除(Delete)几个单词的首字母简写)增删改查是操作数据最底层的操作(从本质......
  • Python项目流程图
    我有一个由多个文件夹组成的Python项目,每个文件夹包含多个脚本。我正在寻找一个Python库或软件/包,它们可以生成流程图,说明这些脚本如何互连并绘制出从开始到结束的整个过程。自动生成Python项目流程图确实是一个挑战,目前没有完美通用的解决方案。主要原因是:......
  • 使用 mypy 时Python中的继承和多态性不起作用
    我正在寻找用mypy做一些标准的多态性,我以前从未使用过它,而且到目前为止它并不直观。基类classContentPullOptions:passclassTool(Protocol):asyncdefpull_content(self,opts:ContentPullOptions)->str|Dict[str,Any]:...子类classGoogle......
  • Python函数获取匹配和错误记录
    我有一个以下格式的json文件:[{"type":"BEGIN","id":"XYZ123"},{"type":"END","id":"XYZ123",},{"type":&......