.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/10_mlops/plot_38_export.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code or to run this example in your browser via Binder. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_10_mlops_plot_38_export.py: Exporting equations to code, spreadsheets and PMML ================================================== A discovered equation is small enough to run anywhere: in a PLC, a spreadsheet, a simulator or a scoring engine. :mod:`eqdisco.export` writes it as Python, C, MATLAB/Octave or Julia source, as an Excel formula, as LaTeX, and as a PMML 4.4 document. With ``protected=True`` the code reproduces the protected operators of eqdisco exactly; this example verifies that the generated Python and NumPy code predict the same values as the equation itself. .. GENERATED FROM PYTHON SOURCE LINES 12-25 .. code-block:: Python import matplotlib.pyplot as plt import numpy as np import eqdisco as eq from eqdisco import export rng = np.random.default_rng(0) X = rng.uniform(0.5, 3, (200, 2)) y = 2.5 * X[:, 0] * np.exp(-0.3 * X[:, 1]) - np.log(X[:, 1]) + 0.01 * rng.normal(size=200) model = eq.SymbolicRegressor(population_size=300, generations=25, functions=("add", "sub", "mul", "div", "exp", "log"), optimize="lm", feature_names=["flow", "time"], random_state=0).fit(X, y) eqn = eq.simplify.simplify(model.equation_, X, y, refit=True) .. GENERATED FROM PYTHON SOURCE LINES 26-28 Source code and formulas ------------------------ .. GENERATED FROM PYTHON SOURCE LINES 28-34 .. code-block:: Python print(export.to_python(eqn, name="yield_model")) print(export.to_c(eqn, name="yield_model")) print(export.to_excel(eqn, {"flow": "B2", "time": "C2"})) print(export.to_latex(eqn, lhs="Y")) pmml = export.to_pmml(eqn, target="yield") print(pmml.count(" 1e-10 else 1.0 def _plog(a): return math.log(abs(a)) if abs(a) > 1e-300 else 0.0 def _ppow(a, b): return abs(a) ** b if a != 0 else 0.0 def yield_model(flow, time): return -0.16363091785454678 * ((time - flow + (-3.6982947133137816)) * (_plog(time + 0.5838449022547934 * flow + 1) + _plog(1.5468294899394592 * _pdiv(flow, time))) + (-1.3840376375425658 * time + 7.020953136898399) * (time - flow) + time - _plog(-3.405173958607722 * (time + 0.6800228429502003) + 0.4777947390726642 * (math.exp(min(time, 100.0))))) + 0.9566686418082396 #include static double pdiv(double a, double b) { return fabs(b) > 1e-10 ? a / b : 1.0; } static double plog(double a) { return fabs(a) > 1e-300 ? log(fabs(a)) : 0.0; } double yield_model(double flow, double time) { return -0.16363091785454678 * ((time - flow + (-3.6982947133137816)) * (plog(time + 0.5838449022547934 * flow + 1.0) + plog(1.5468294899394592 * pdiv(flow, time))) + (-1.3840376375425658 * time + 7.020953136898399) * (time - flow) + time - plog(-3.405173958607722 * (time + 0.6800228429502003) + 0.4777947390726642 * (exp(fmin(time, 100.0))))) + 0.9566686418082396; } =-0.163630917854547*((C2-B2+(-3.69829471331378))*((IF(ABS((C2+0.583844902254793*B2+1))>0,LN(ABS((C2+0.583844902254793*B2+1))),0))+(IF(ABS((1.54682948993946*(IF(ABS(C2)>1E-10,B2/C2,1))))>0,LN(ABS((1.54682948993946*(IF(ABS(C2)>1E-10,B2/C2,1))))),0)))+(-1.38403763754257*C2+7.0209531368984)*(C2-B2)+C2-(IF(ABS((-3.40517395860772*(C2+0.6800228429502)+0.477794739072664*(EXP(MIN(C2,100)))))>0,LN(ABS((-3.40517395860772*(C2+0.6800228429502)+0.477794739072664*(EXP(MIN(C2,100)))))),0)))+0.95666864180824 Y = - 0.1636 time - 0.1636 \left(7.021 - 1.384 time\right) \left(- flow + time\right) - 0.1636 \left(\log{\left(\frac{1.547 flow}{time} \right)} + \log{\left(0.5838 flow + time + 1 \right)}\right) \left(- flow + time - 3.698\right) + 0.1636 \log{\left(- 3.405 time + 0.4778 e^{time} - 2.316 \right)} + 0.9567 52 Apply elements in the PMML document .. GENERATED FROM PYTHON SOURCE LINES 35-37 Verifying the generated code ---------------------------- .. GENERATED FROM PYTHON SOURCE LINES 37-51 .. code-block:: Python namespace = {} exec(export.to_python(eqn, name="f_py"), namespace) # code written by eqdisco itself exec(export.to_python(eqn, name="f_np", numpy=True), namespace) ref = eqn.predict(X) py = np.array([namespace["f_py"](*row) for row in X]) vec = namespace["f_np"](X[:, 0], X[:, 1]) print(f"largest difference from eqdisco: Python {np.max(np.abs(py - ref)):.1e}, NumPy {np.max(np.abs(vec - ref)):.1e}") fig, ax = plt.subplots(figsize=(4.5, 3.2)) ax.semilogy(np.sort(np.abs(py - ref) + 1e-17), color="#285780", label="Python (math)") ax.semilogy(np.sort(np.abs(vec - ref) + 1e-17), color="#D55E00", label="NumPy") ax.set_xlabel("sample (sorted by error)") ax.set_ylabel("|generated code - eqdisco|") ax.legend(frameon=False, fontsize=8) .. image-sg:: /auto_examples/10_mlops/images/sphx_glr_plot_38_export_001.png :alt: plot 38 export :srcset: /auto_examples/10_mlops/images/sphx_glr_plot_38_export_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none largest difference from eqdisco: Python 0.0e+00, NumPy 0.0e+00 .. GENERATED FROM PYTHON SOURCE LINES 52-56 Parameter study: protected or plain operators --------------------------------------------- Plain operators give the textbook formula; they differ from eqdisco only where a protected operator acts (division by ~0, logarithm of a negative number). .. GENERATED FROM PYTHON SOURCE LINES 56-68 .. code-block:: Python Xbad = np.column_stack([np.linspace(-1, 3, 50), np.linspace(-1, 3, 50)]) ns_plain = {} exec(export.to_python(eqn, name="g", protected=False, numpy=True), ns_plain) with np.errstate(all="ignore"): plain = ns_plain["g"](Xbad[:, 0], Xbad[:, 1]) print("rows where plain and protected operators differ:", int(np.sum(~np.isclose(plain, eqn.predict(Xbad), equal_nan=False))), "of", len(Xbad)) fig, ax = plt.subplots(figsize=(4.5, 3.2)) ax.plot(Xbad[:, 1], eqn.predict(Xbad), color="#285780", lw=2, label="protected (eqdisco)") ax.plot(Xbad[:, 1], plain, color="#D55E00", ls="--", label="plain operators") ax.set_xlabel("time (also outside the data range)") ax.legend(frameon=False, fontsize=8) plt.show() .. image-sg:: /auto_examples/10_mlops/images/sphx_glr_plot_38_export_002.png :alt: plot 38 export :srcset: /auto_examples/10_mlops/images/sphx_glr_plot_38_export_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none rows where plain and protected operators differ: 50 of 50 .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 8.788 seconds) .. _sphx_glr_download_auto_examples_10_mlops_plot_38_export.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/ComplexSystemsIntelligence/eqdisco/main?urlpath=lab/tree/notebooks/auto_examples/10_mlops/plot_38_export.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_38_export.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_38_export.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_38_export.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_