{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\nFit Using differential_evolution Algorithm\n==========================================\n\nThis example compares the \"leastsq\" and \"differential_evolution\" algorithms on\na fairly simple problem.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nimport lmfit\n\nnp.random.seed(2)\nx = np.linspace(0, 10, 101)\n\n# Setup example\ndecay = 5\noffset = 1.0\namp = 2.0\nomega = 4.0\n\ny = offset + amp*np.sin(omega*x) * np.exp(-x/decay)\nyn = y + np.random.normal(size=y.size, scale=0.450)\n\n\ndef resid(params, x, ydata):\n decay = params['decay'].value\n offset = params['offset'].value\n omega = params['omega'].value\n amp = params['amp'].value\n\n y_model = offset + amp * np.sin(x*omega) * np.exp(-x/decay)\n return y_model - ydata\n\n\nparams = lmfit.Parameters()\nparams.add('offset', 2.0, min=0, max=10.0)\nparams.add('omega', 3.3, min=0, max=10.0)\nparams.add('amp', 2.5, min=0, max=10.0)\nparams.add('decay', 1.0, min=0, max=10.0)\n\no1 = lmfit.minimize(resid, params, args=(x, yn), method='leastsq')\nprint(\"# Fit using leastsq:\")\nlmfit.report_fit(o1)\n\no2 = lmfit.minimize(resid, params, args=(x, yn), method='differential_evolution')\nprint(\"\\n\\n# Fit using differential_evolution:\")\nlmfit.report_fit(o2)\n\nplt.plot(x, yn, 'ko', lw=2)\nplt.plot(x, yn+o1.residual, 'r-', lw=2)\nplt.plot(x, yn+o2.residual, 'b--', lw=2)\nplt.legend(['data', 'leastsq', 'diffev'], loc='upper left')\nplt.show()" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.6" } }, "nbformat": 4, "nbformat_minor": 0 }