在我的数据中,第一列是
x
值,第二列是 y
值。我想用三参数威布尔函数拟合数据来描述分布。
我尝试通过多次搜索来找到解决方案,但Stack Overflow 上的类似帖子似乎仅适用于单列数据。我也尝试过使用库
scipy.stats.exponweib
和scipy.stats.weibull_min
,但由于同样的问题而失败。
所以我尝试定义函数并用
scipy.optimize.curve_fit
来拟合数据。以下是我使用的代码。 data.txt
文件可以通过这个链接下载。
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
# Load data
poresize, psd, psd_std = np.loadtxt("data.txt", unpack=True)
# Define the Weibull distribution function with the requested form
def weibull_func(x, a, b, c):
return a * b * (x - c) ** (b - 1) * np.exp(-a * (x - c) ** b)
# Perform curve fitting
popt, pcov = curve_fit(weibull_func, poresize, psd, p0=[1, 1, 1])
# Plot the original data and the fitted curve
plt.scatter(poresize, psd, label='Data')
x_range = np.linspace(min(poresize), max(poresize), 100)
plt.plot(x_range, weibull_func(x_range, *popt), 'r-', label='Fitted curve (Weibull)')
plt.xlabel('Particle Size')
plt.ylabel('PSD')
plt.title('Fitting Weibull Distribution')
plt.legend()
plt.grid(True)
plt.show()
# Display the optimized parameters
a_opt, b_opt, c_opt = popt
print("Optimized Parameters:")
print("a:", a_opt)
print("b:", b_opt)
print("c:", c_opt)
函数形式改编自 Matlab 的 Weibull 分布,但
x
被替换为 x-c
。
问题是我尝试了很多 p0
的初始猜测值的组合,但没有一个能给我满意的结果。
您能告诉我代码是否存在根本性错误吗?或者我怎样才能快速得到正确的初步猜测?
数据文件有100行,所以它不包含在这篇文章中,但如果需要,我会尝试附加数据。
拟合函数时的两条建议:
x < c
不是整数时,b
是未定义的。 (这是因为您有 (x-c)^(b-1)
。如果 x < c
,则 x - c < 0
。如果 b
不是整数,那么您将采用负数的小数幂,从而产生复数。)x = 2
和 x = 5
之间,并且峰值达到 y = 1
。知道这一点后,我制作了这个 Desmos 模型并使用变量,直到得到像样的东西。这里是可以处理的固定函数
x < c
:
def weibull_func(x, a, b, c):
res = np.zeros_like(x)
cond = x > c
xcond = x[cond]
res[cond] = a*b*(xcond - c)**(b - 1)*np.exp(-a*(xcond - c)**b)
return res
我提供了
curve_fit
调用以及我使用 Desmos 得到的猜测:
popt, pcov = curve_fit(weibull_func, poresize, psd, p0=[1.4, 1.93, 2.4])
调整后的参数为:
a: 1.1172264863332277
b: 2.2231297860177226
c: 2.301372954142873
结果图: