.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/05_probabilistic/plot_21_llm_proposals.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_05_probabilistic_plot_21_llm_proposals.py: Language models as proposal generators ====================================== Large language models know many scientific laws and can propose plausible equation skeletons from a description of the variables; a numerical optimizer then fits the constants (Merler et al., 2024; Shojaee et al., 2025). eqdisco supports this through a *proposer*: any function that maps a prompt to text. Here the proposer is offline -- :class:`~eqdisco.TemplateProposer` answers with templates of enzyme kinetics -- so the example runs anywhere; a real model is plugged in the same way (see the last section). Proposals are parsed by a whitelist parser and are never executed. .. GENERATED FROM PYTHON SOURCE LINES 14-25 .. code-block:: Python import matplotlib.pyplot as plt import numpy as np import eqdisco as eq rng = np.random.default_rng(6) S = np.sort(rng.uniform(0.05, 5, 30)) v = 2.0 * S / (0.6 + S) * (1 + 0.02 * rng.normal(size=30)) X = S.reshape(-1, 1) .. GENERATED FROM PYTHON SOURCE LINES 26-28 An offline proposer and the guided loop --------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 28-49 .. code-block:: Python templates = ["c0*x0", "c0*x0/(c1 + x0)", "c0*(1 - exp(-c1*x0))", "c0*x0^c1", "c0*log(1 + c1*x0)", "c0*x0^2/(c1 + x0^2)", "c0*x0/(c1 + x0 + c2*x0^2)"] proposer = eq.TemplateProposer(templates, n=3, random_state=1) llm = eq.LLMGuidedRegressor(proposer, n_iterations=5, n_proposals=3, feature_names=["S"], description="initial rate of an enzyme reaction as a function of the substrate concentration", variable_descriptions={"S": "substrate concentration, mmol/L"}) llm.fit(X, v) print(llm.equation_) print(llm.prompts_[0][:500]) fig, axs = plt.subplots(1, 2, figsize=(10, 3.4)) axs[0].step(llm.history_["iteration"], llm.history_["best_mse"], where="post", color="#285780") axs[0].set_yscale("log") axs[0].set_xlabel("iteration") axs[0].set_ylabel("best MSE in the pool") s = np.linspace(0, 5, 200).reshape(-1, 1) axs[1].scatter(S, v, color="#6B7785", s=15, label="data") for k, e in enumerate(llm.pareto_front_[-3:]): axs[1].plot(s, e.predict(s), color=eq.viz.OKABE_ITO[k], lw=1.4, label=str(e)[:34]) axs[1].legend(frameon=False, fontsize=7) axs[1].set_xlabel("S") fig.tight_layout() .. image-sg:: /auto_examples/05_probabilistic/images/sphx_glr_plot_21_llm_proposals_001.png :alt: plot 21 llm proposals :srcset: /auto_examples/05_probabilistic/images/sphx_glr_plot_21_llm_proposals_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none 1.993 * S / (S + 0.5868) You are helping to discover a mathematical equation y = f(x) from data. Task: initial rate of an enzyme reaction as a function of the substrate concentration Variables: S: substrate concentration, mmol/L Data summary: S: min 0.09403, max 4.938, mean 2.422 y: min 0.2775, max 1.806, mean 1.44 Sample rows (inputs -> y): 0.09403 -> 0.2775 0.6553 -> 1.063 1.077 -> 1.279 1.904 -> 1.494 2.714 -> 1.651 3.388 -> 1.702 4.144 -> 1.739 4.938 -> 1.806 Propose 3 new candidate equations f .. GENERATED FROM PYTHON SOURCE LINES 50-54 Combining proposals with genetic programming -------------------------------------------- The same proposer can feed a genetic-programming run: every ``llm_interval`` generations its proposals are fitted and injected into the population. .. GENERATED FROM PYTHON SOURCE LINES 54-57 .. code-block:: Python sr = eq.SymbolicRegressor(population_size=150, generations=10, llm_proposer=proposer, llm_interval=3, feature_names=["S"], random_state=0).fit(X, v) print("GP with proposals:", sr.equation_) .. rst-class:: sphx-glr-script-out .. code-block:: none GP with proposals: -0.002234 + 1.994 * S / (S + 0.585) .. GENERATED FROM PYTHON SOURCE LINES 58-69 Plugging in a real language model --------------------------------- Any client works; for example with the Anthropic SDK (not run here):: import anthropic client = anthropic.Anthropic() def proposer(prompt): msg = client.messages.create(model="claude-sonnet-5-5", max_tokens=400, messages=[{"role": "user", "content": prompt}]) return msg.content[0].text eq.LLMGuidedRegressor(proposer, n_iterations=10).fit(X, v) .. GENERATED FROM PYTHON SOURCE LINES 71-73 Parameter study: proposals per iteration ---------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 73-83 .. code-block:: Python fig, ax = plt.subplots(figsize=(4.5, 3)) for k, n in enumerate((1, 3, 6)): m = eq.LLMGuidedRegressor(eq.TemplateProposer(templates, n=n, random_state=3), n_iterations=6, n_proposals=n).fit(X, v) print(f"{n} proposals per iteration: final best MSE {m.history_['best_mse'].iloc[-1]:.2e}") ax.step(m.history_["iteration"], m.history_["best_mse"], where="post", color=eq.viz.OKABE_ITO[k], label=f"{n} per iteration") ax.set_yscale("log") ax.set_xlabel("iteration") ax.set_ylabel("best MSE") ax.legend(frameon=False, fontsize=8) plt.show() .. image-sg:: /auto_examples/05_probabilistic/images/sphx_glr_plot_21_llm_proposals_002.png :alt: plot 21 llm proposals :srcset: /auto_examples/05_probabilistic/images/sphx_glr_plot_21_llm_proposals_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none 1 proposals per iteration: final best MSE 7.07e-04 3 proposals per iteration: final best MSE 6.93e-04 6 proposals per iteration: final best MSE 6.93e-04 .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 1.267 seconds) .. _sphx_glr_download_auto_examples_05_probabilistic_plot_21_llm_proposals.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/05_probabilistic/plot_21_llm_proposals.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_21_llm_proposals.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_21_llm_proposals.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_21_llm_proposals.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_