Registry / ai-ml / lmfit
library1.3.4pypypi✓ verified 22d ago

LMFit is a Python library providing a high-level interface for non-linear least-squares minimization and curve fitting. It extends and builds upon `scipy.optimize` by introducing `Parameter` objects, which simplify the process of defining, constraining, and managing fitting variables. Currently at version 1.3.4, `lmfit` maintains an active development cycle with regular releases addressing bug fixes, new features, and dependency updates.

pip install lmfit
INSTALL
IMPORT
SIG · LMFIT
L
lmfit
ai-mlpythonv1.3.4
Install
7.7s avg
Import
2532ms
Disk
232MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.3.4 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 2.594s · 232.8MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 7.7s · import 2.470s · 224MB
232MB installed
● package 232MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Model
from lmfit import Model
Parameters
from lmfit import Parameters
minimize
from lmfit import minimize

This quickstart demonstrates fitting an exponential decay model to noisy data using `lmfit.Model`. It covers defining the model function, creating `Model` and `Parameters` objects, setting initial guesses and constraints, performing the fit, and reporting the results.

import numpy as np from lmfit import Model # 1. Generate some data x = np.linspace(0, 10, 100) y_true = 3.0 * np.exp(-0.5 * x) + 2.0 np.random.seed(0) y_data = y_true + np.random.normal(0, 0.2, x.shape) # 2. Define your model function def exponential_decay(x, amplitude, decay, offset): return amplitude * np.exp(-decay * x) + offset # 3. Create a Model instance from your function exp_model = Model(exponential_decay) # 4. Create initial parameters with guess() or manually # guess() method often requires x and y data for good initial estimates params = exp_model.make_params(amplitude=5., decay=0.1, offset=1.) # Or, for more refined control: # params = exp_model.guess(y_data, x=x) # Optionally set bounds or fix parameters params['amplitude'].set(min=0.0) params['decay'].set(min=0.0) # 5. Fit the model to the data result = exp_model.fit(y_data, params, x=x) # 6. Print the fitting report print(result.fit_report()) # You can also access best-fit parameters, statistics, etc. # print(f"Best-fit amplitude: {result.params['amplitude'].value:.3f}") # print(f"Reduced Chi-square: {result.redchi:.3f}")
Debug
Known issues
breakingSince version 1.0.3, the `guess()` method of `lmfit.Model` (and built-in models) now explicitly requires the `x` (independent variable) argument, even if it worked without it in older versions. Scripts not providing `x` will raise an error.
fix
Ensure `x` (independent variable data) is always passed to `Model.guess(data, x=x_data)`.
affects: >=1.0.3
gotchaFit procedures will stop if `NaN` values are encountered in the objective function or model output. If `NaN`s are present in your input data and are meant to represent missing values, they must be explicitly handled.
fix
Use the `nan_policy='omit'` argument when creating a `Model` or calling `Model.fit()` / `lmfit.minimize()` if `NaN`s in data should be ignored. Alternatively, preprocess data to remove or impute `NaN`s.
affects: All
gotchaParameters can sometimes get 'stuck' at their initial values or fail to converge if small changes to their values do not significantly affect the residual (e.g., discrete steps in the model, or initial guesses are extremely far from the true minimum).
fix
Provide reasonable initial guesses for parameters. For models with discrete-like transitions, consider using smoother functions (e.g., error functions for steps) or a 'brute' force method for initial scanning. Review the `fit_report` to check for parameters with zero standard error or very small changes.
affects: All
deprecatedOlder Python versions are no longer supported. For instance, `lmfit` version 1.2.0 dropped support for Python 3.6, and version 1.3.3 dropped support for Python 3.8. The current minimum required Python version is 3.9.
fix
Upgrade your Python environment to 3.9 or newer to use current `lmfit` versions.
affects: <1.2.0 (Python 3.6), <1.3.3 (Python 3.8)
gotchaWhen using `lmfit.minimize` directly (rather than `Model.fit`), the `Parameters` object passed as an argument can be modified in-place by the minimization routine. Reusing the same `Parameters` object for multiple fits without explicit copying can lead to unexpected results.
fix
Always pass a `copy.deepcopy()` of the `Parameters` object to `minimize()` if you intend to reuse the original `Parameters` for subsequent fits or if a `Minimizer` instance is reused across multiple fits without re-initialization.
affects: <=0.9.x (potentially older, though modern docs imply better handling)
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'lmfit'
The `lmfit` package is not installed in the Python environment being used, or the Python environment where it's installed is not the one running the script.
fix
Install `lmfit` using pip: `pip install lmfit` or if using Anaconda: `conda install -c conda-forge lmfit`
AttributeError: 'Model' object has no attribute 'params'
The `params` attribute is not directly available on an `lmfit.Model` object until parameters are either explicitly created using `model.make_params()` or a fit has been performed which populates the parameters in the `result.params` object.
fix
Initialize parameters using `params = model.make_params()` before accessing or modifying them, or access them from the `result` object after fitting: `result = model.fit(...)` then `result.params`.
ImportError: cannot import name 'GaussianModel' from 'lmfit.model'
Built-in `lmfit` models like `GaussianModel` are located within the `lmfit.models` submodule (plural), not `lmfit.model` (singular).
fix
Correct the import statement to `from lmfit.models import GaussianModel`.
ValueError: The input contains nan values
The objective function or input data contains `NaN` (Not a Number) values, which `lmfit`'s optimization routines cannot handle by default.
fix
Ensure your data and model function outputs do not produce `NaN` values, or handle missing data by providing `nan_policy='omit'` or `nan_policy='propagate'` to `lmfit.minimize()` or `Model.fit()`.
TypeError: 'NoneType' object is not callable
This error often occurs when a variable expected to hold a function or callable object, such as the `Model` instance or the objective function in `minimize()`, is actually `None`, typically because it was not properly initialized or returned `None` when a callable was expected.
fix
Verify that your `lmfit.Model` instance is correctly created with a callable function, and that the function passed to `lmfit.minimize()` is properly defined and accessible, ensuring no assignment results in `None` where a callable is expected.
Upgrade
Version history
1.3.4latest on PyPI · released Jul 19, 2025
Audit
Dependencies
numpyrequiredCore numerical operations and data structures.
scipyrequiredUnderlying optimization algorithms.
astevalrequiredExpression evaluation for parameter constraints.
numdifftoolsoptionalImproved estimation of parameter uncertainties and correlations for non-Levenberg-Marquardt solvers.
uncertaintiesoptionalFor handling transparent calculations with uncertainties and `ModelResult.uvars` output.
dilloptionalFor pickling complex objects, including models and results.
Agent activity
11 hits · last 30 days
node
8
Resources
lmfit — pip install lmfit · libregistry