我试图用matplotlib绘制一些可视化效果,在我的一个函数中,我检查波是否是对数的。这是我当前的工作版本:
import numpy as np
def is_logarithmic(waves):
def expfunc(x, a, b, c):
return a*np.exp(b*x) + c
wcopy = list(waves)
wcopy.sort()
# If the ratio of x-max : x-min < 10, don't use a logarithmic scale
# (at least in matplotlib)
if (wcopy[-1] / wcopy[0]) < 10:
return False
# Take a guess at whether it is logarithmic by seeing how well the x-scale
# fits an exponential curve
diffs = []
for ii in range(len(wcopy) - 1):
diffs.append(wcopy[ii + 1] - wcopy[ii])
# Fit the diffs to an exponential curve
x = np.arange(len(wcopy)-1)
try:
popt, pcov = curve_fit(expfunc, x, diffs)
except Exception as e:
print e
popt = [0.0, 0.0, 0.0]
pcov = np.inf
# If a > 0.5 and covsum < 1000.0
# use a logarithmic scale.
if type(pcov) == float:
# It's probably np.inf
covsum = pcov
else:
covsum = pcov.diagonal().sum()
res = (covsum < 1000.0) & (popt[0] > 0.5)
return res
我正试图找到一个替代scipy的curve_fit()
,因为我不想安装这么大的库来使用这个函数。还有什么我可以使用的,或者其他函数的组合,从理想情况下只使用numpy和matplotlib来获得类似的结果吗?在
您还可以使用
lmfit.models
库,它有很多预定义的模型。在https://lmfit.github.io/lmfit-py/
https://lmfit.github.io/lmfit-py/builtin_models.html#exponential-and-power-law-models
它还支持自定义函数。在
Numpy可以进行线性(
numpy.linalg.lstsq
)和多项式拟合(numpy.polyfit
)。一般来说,您需要scipy来适应您自己定义的函数(scipy使用fortran minpack,而numpy只使用C构建)。在但是,对于您的例子,您可以使用类似的方法来处理this问题来拟合一个经验值。基本上,取方程两边的对数算法并使用
numpy.polyfit
。在相关问题 更多 >
编程相关推荐