2

I need to iterate through the elements in a numpy array so I can treat any zero elements separately. The code below works for straighforward evaluations, but not when used with scipy.optimize.curve_fit(). Is there a way to make this work with the 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()
1
  • 1
    Please do always specify what "it doesn't work" means. What's the error message you get when you use this with curve_fit()? Please provide the full traceback. Dec 16, 2011 at 12:01

2 Answers 2

3

To make the larsmans' answer actually work, you will also need to convert your data samples to NumPy arrays:

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)

(Converting y_meas is not strictly necessary.)

Here is larsmans' code with my suggestions incorporated:

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
2
  • 1
    Thanks for the answer. This works. Actually, by just changing x_meas and y_meas to numpy array types allows my original my_func() to work. This code should be faster though. One point - it's probably better to use y = np.zeros_like(x, float) because the default data type for zeros_like is int64.
    – mr_js
    Dec 16, 2011 at 12:57
  • @user602117: The default for zeros_like() isn't int64, but rather the same datatype as the parameter. If the parameter is a Python list, the list will first be converted to a NumPy array using the usual rules. If this list happens to contain only int values, an integer data type is used. That's why I added dtype parameters in the definitions of x_meas and y_meas. Dec 16, 2011 at 15:11
1

I need to iterate through the elements in a numpy array so I can treat any zero elements separately.

No you don't; this should be a lot faster and work everywhere:

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
1
  • 1
    The code will be faster if you drop the call to np.where() and simply use nonzero = x != 0. Moreover, y = np.zeros_like(x) would always give y the correct data type, even if x consists of, say, complex numbers. Dec 16, 2011 at 12:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.