gpt4 book ai didi

python - 与 scipy.optimize.curve_fit 一起使用时遍历 python numpy 数组

转载 作者:行者123 更新时间:2023-11-28 23:03:24 24 4
gpt4 key购买 nike

我需要遍历 numpy 数组中的元素,这样我就可以分别处理任何零元素。下面的代码适用于直接评估,但不适用于 scipy.optimize.curve_fit()。有没有办法使它与 curve_fit fn 一起工作?

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

def my_fn(x_array, b, a):
y = []
for x in np.nditer(x_array): #This doesn't work with curve_fit()
if x == 0:
y.append(0)
else:
y.append(b*(1/np.tanh(x/a) - a/x))
return np.array(y)


x_meas = [0, 5, 20, 50, 100, 200, 600]
y_meas = [0, 0.275, 1.22, 1.64, 1.77, 1.84, 1.9]
xfit = np.linspace(0,600,601)
yfit2 = my_fn(xfit, 1.95, 8.2) #manual fit

#Not working
#popt, pcov = curve_fit(my_fn, x_meas, y_meas, p0=[1.95, 8.2])
#yfit1 = my_fn(xfit, *popt) #auto fit

figure(1)
plot(x_meas, y_meas, 'o', xfit, yfit2)
show()

最佳答案

制作larsmans' answer实际上,您还需要将数据样本转换为 NumPy 数组:

x_meas = numpy.array([0, 5, 20, 50, 100, 200, 600], float)
y_meas = numpy.array([0, 0.275, 1.22, 1.64, 1.77, 1.84, 1.9], float)

(转换 y_meas 并非绝对必要。)

这是 larsmans 的代码,其中包含我的建议:

def my_fn(x, b, a):
y = np.zeros_like(x)
nonzero = x != 0
x = x[nonzero]
y[nonzero] = b*(1/np.tanh(x/a) - a/x)
return y

关于python - 与 scipy.optimize.curve_fit 一起使用时遍历 python numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8533765/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com