python使用curve_fit拟合任意分布
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | import matplotlib.pyplot as plt from scipy.optimize import curve_fit import numpy as np def func(x, a, b, c): # 拟合的方程 return a * np.exp( - b * x) + c def get_data(): xdata: np.ndarray = np.linspace( 0 , 4 , 50 ) # x值 y = func(xdata, 2.5 , 1.3 , 0.5 ) rng = np.random.default_rng() y_noise = 0.2 * rng.normal(size = xdata.size) ydata: np.ndarray = y + y_noise # y值 return xdata, ydata if __name__ = = '__main__' : x_value, y_value = get_data() popt, pcov = curve_fit(func, x_value, y_value) # 绘图 plt.plot(x_value, y_value, 'b-' , label = 'data' ) plt.plot(x_value, func(x_value, * popt), 'r-' , label = 'fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple (popt)) # 给拟合参数加一个限定范围:0 <= a <= 2.5, 0 <= b <= 1 and 0 <= c <= 0.4 popt_2, pcov_2 = curve_fit(func, x_value, y_value, bounds = ([ 0 , 0 , 0 ], [ 2.5 , 1. , 0.4 ])) plt.plot(x_value, func(x_value, * popt_2), 'g--' , label = 'fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple (popt_2)) plt.xlabel( 'x' ) plt.ylabel( 'y' ) plt.legend() plt.show() |
2.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | def func(x, a, b, c, d): # 拟合的方程 return a * x[:, 0 ] + b * x[:, 1 ] - c * x[:, 0 ] * x[:, 1 ] + d def get_data(): xdata: np.ndarray = np.random.randint( 1 , 5 ,size = ( 100 , 2 )) # x值 y = func(xdata, 2.5 , 1.3 , 0.5 , 2 ) y_noise = 0.2 * np.random.normal(size = xdata.shape[ 0 ]) ydata = y + y_noise # y值 return xdata, ydata if __name__ = = '__main__' : x_value, y_value = get_data() popt, pcov = curve_fit(func, x_value, y_value) # 绘图 plt.plot(y_value, 'b-' , label = 'data' ) plt.plot(func(x_value, * popt), 'r-.' , label = 'fit: a=%4.2f, b=%4.2f, c=%4.2f, d=%4.2f' % tuple (popt)) plt.xlabel( 'x' ) plt.ylabel( 'y' ) plt.legend() plt.show() |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人