在使用scipy.optimize.curve_fit时遍历numpy数组
我需要遍历一个numpy数组里的元素,这样我就可以单独处理那些值为零的元素。下面的代码在简单的计算中可以正常工作,但在使用scipy.optimize.curve_fit()时就不行了。有没有办法让这个在curve_fit函数中也能正常工作呢?
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()
2 个回答
1
我需要遍历一个numpy数组里的元素,这样我就可以单独处理任何零元素。
其实你不需要这样做;这样做会更快,并且在任何地方都能用:
def my_fn(x, b, a):
y = np.zeros(x.shape)
nonzero = np.where(x != 0)
x = x[nonzero]
y[nonzero] = b*(1/np.tanh(x/a) - a/x)
return y
3
为了让 larsmans 的回答 真正有效,你还需要把你的数据样本转换成 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