与scipy.optimize.curve_fit一起使用时迭代python numpy数组

时间:2011-12-16 11:51:24

标签: python numpy scipy

我需要遍历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()

2 个答案:

答案 0 :(得分:3)

要使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

答案 1 :(得分: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