Medulla Oblongata
Medulla Oblongata

Reputation: 3961

Using Levenberg-Marquardt method in scipy's least_squares function

I'm trying to solve a (nonlinear least squares) toy problem by using the scipy.optimize.least_squares function in Python.

import numpy as np
from scipy.optimize import least_squares

a = 2
b = -1

def myfun(x,a,b):
    return [a*x[0]-x[1]-np.exp(-x[0]), b*x[0]+2*x[1]-np.exp(-x[1])]

x0 = [-5,-5]
sol = least_squares(myfun,x0,method='lm',ftol=1e-9,xtol=1e-9, \
                    max_nfev=1e6,args=(a,b))

print(sol)

'''
method='trf' solution:  x = array([0.56714329,0.56714329])
'''

If I use the Levenberg-Marquardt method method='lm' then I get an error TypeError: integer argument expected, got float. Am I missing an input argument for least_squares? I don't have any further information for the problem, e.g. Jacobian matrix, so I'm not sure if this method particularly suitable for the problem.

Upvotes: 2

Views: 8422

Answers (1)

MB-F
MB-F

Reputation: 23637

You need to write max_nfev=1000000, or max_nfev=int(1e6) if you prefer exponential notation.

1e9 is a floating point literal but max_nfev should be an integer. Apparently, the LM algorithm checks this, while other algorithms may silently accept a float.

Note the difference between value and data type:

1 is an integer with value one, 1.0 is a float with value one. Mathematically, both have the same value but they are not the same thing because they have different data types.

Upvotes: 3

Related Questions