fnprior
- fnprior:
Priors on functions for symbolic regression from n-gram language models
- Authors:
Deaglan J. Bartlett, Harry Desmond
- Homepage:
- Documentation:
About
Symbolic regression algorithms attempt to find analytic expressions which accurately fit a given data set. In many cases, one wants these to be interpretable and thus one tries to find the simplest possible expression which can accurately fit the data. Even if an expression is simple, if one is seeking a physical law, one may discard an expression because it does not look like the kind of expression one would expect in this context. To automate this process, we produce a prior on functions based on an n-gram language model of the operators in a function’s tree: by studying a corpus of previously used equations in a given field, the model returns a probability for each function based on the order of operators appearing in the function. The conditional probabilities are smoothed with interpolated Kneser-Ney by default, or with the Katz back-off model of the original paper.
Installation
fnprior is installed from PyPI with
pip install fnprior
The prior itself needs only NumPy, SciPy, pandas and SymPy: equations are converted to trees by fnprior.tree_parser, which reproduces the parser of the ESR Package, so the prior can be used with any symbolic regression method. SymPy 1.14 or later is required: older versions parse a few corpus equations differently (a numeric factor is taken out of a square root), which changes the prior by up to a few nats for some functions.
ESR and mpi4py are needed only to score ESR function libraries with fnprior.esr_prior and to run the ESR tests. ESR is not on PyPI, so install it from GitHub; pip install fnprior[esr] installs mpi4py. To install both from source in a new virtual environment, run
python3 -m venv fnprior_env
source fnprior_env/bin/activate
git clone https://github.com/DeaglanBartlett/ESR.git
pip install -e ESR
git clone https://github.com/DeaglanBartlett/fnprior.git
pip install -e "fnprior[esr]"
Example
To generate a prior with n = 2 from the equations of the AI Feynman database (Udrescu & Tegmark 2020), which are included in fnprior (data_path gives the path of an included corpus), and evaluate it on some trial functions, run the code below. The standardised equations are written to NewFeynman.csv. Here n is the number of symbols from which each symbol is predicted, so n = 2 gives a 3-gram model (in general, n gives an (n+1)-gram model):
from fnprior import data_path
from fnprior.prior import FunctionPrior
n = 2
basis_functions = [["a", "x"],
["sqrt", "exp", "log", "sin", "cos", "arcsin", "tanh"],
["+", "-", "*", "/", "pow"]]
kp = FunctionPrior(n, basis_functions, data_path('FeynmanEquations.csv'), 'NewFeynman.csv')
for eq in ['x0**2', 'sin(x0) + sin(x1)', 'sin(sin(x0+x1))']:
p = kp.logprior(eq)
print(eq, p)
Smoothing and representation options
By default (smoothing='kn') the conditional probabilities are estimated with interpolated Kneser-Ney smoothing, with a single absolute discount D = 0.8 at all orders. This assigns a non-zero probability to every operator of the basis set in every context and is less sensitive to the choice of n than the Katz model. The default discount was chosen on the physics corpus, so for other corpora tune the discounts by cross-validation with tune_discounts(). They can also be set with smoothing_kwargs={'discounts': D}, or estimated with the Chen-Goodman formulae (smoothing_kwargs={'discounts': 'mkn'}, not recommended for corpora of fewer than ~100 equations). tune_discounts(method='count') tunes separate discounts for n-grams seen once and n-grams seen more than once (modified Kneser-Ney), which improves on a single tuned discount by ~0.1 nats per equation for n >= 4. smoothing='katz' gives the Katz back-off model of Bartlett et al. (2023), with conditional probabilities normalised by default (normalise=True); smoothing='katz', root_context=False, normalise=False gives the Katz model of version 0.2.1 (see version 0.3.0 in the changelog).
The root and the nodes near it are conditioned on an explicit start-of-tree context (root_context=True, the default). This gives the largest improvement in held-out tests, but makes single-leaf functions considerably less probable, since no corpus equation is a bare leaf; root_context=False restores the original representation, in which the root is predicted from the distribution of all first children. code_constants=True codes constants and parameters as a rather than as variables (by default they are treated like variables, as physical constants are in the corpus, so e.g. pow(x0, a0) and pow(a0, x0) have the same prior).
# the physics corpus also needs arccos; this is the basis of ESR's core_maths library
basis_functions = [["a", "x"],
["sqrt", "exp", "log", "sin", "cos", "arcsin", "arccos", "tanh", "inv"],
["+", "-", "*", "/", "pow"]]
kp = FunctionPrior(3, basis_functions, data_path('PhysicsEquations.csv'), 'NewPhysics.csv',
input_delimiter=';')
kp.tune_discounts()
print(kp.logprior('sin(x0) + sin(x1)'))
KatzPrior, the name of this class before version 0.4.0, is kept as an alias of FunctionPrior for backwards compatibility. fnprior.esr_prior.compute_logprior, which scores an ESR function library, names its output files after the prior configuration (e.g. kn_codelen_3_5.txt, kn_D0.6_codelen_3_5.txt, kn_tuned_codelen_3_5.txt, katz_noroot_unnorm_codelen_2_5.txt) and writes a JSON manifest of the configuration and corpus beside them; existing files are reused only if the manifest matches. With tune_discounts it tunes the discounts on the corpus before scoring and records the tuned values in the manifest:
from fnprior.esr_prior import compute_logprior, get_logconst
dirname = 'ESR/esr/function_library/core_maths'
get_logconst(5, dirname) # constant terms of the codelength, needed first
compute_logprior(5, 3, basis_functions, dirname,
data_path('PhysicsEquations.csv'), 'NewPhysics.csv',
input_delimiter=';', tune_discounts='single')
Changes
The changes in each version, including how to reproduce priors computed with earlier versions, are listed in the changelog.
Licence and Citation
Users are required to cite the paper:
@ARTICLE{2023arXiv2304.06333,
author = {{Bartlett}, D.~J. and {Desmond}, H. and {Ferreira}, P.~G.},
title = "{Priors for symbolic regression}",
journal = {arXiv e-prints},
keywords = {Computer Science - Machine Learning},
year = 2023,
month = apr,
eid = {arXiv:2304.06333},
pages = {arXiv:2304.06333},
archivePrefix = {arXiv},
eprint = {2304.06333},
primaryClass = {cs.LG},
url = {https://arxiv.org/abs/2304.06333},
}
Since fnprior uses code that originated in the ESR package, users are required to cite the ESR paper, for which the following BibTeX can be used:
@ARTICLE{2022arXiv2211.11461,
author = {{Bartlett}, D.~J. and {Desmond}, H. and {Ferreira}, P.~G.},
title = "{Exhaustive Symbolic Regression}",
journal = {arXiv e-prints},
keywords = {Astrophysics - Cosmology and Nongalactic Astrophysics},
year = 2022,
month = nov,
eid = {arXiv:2211.11461},
pages = {arXiv:2211.11461},
archivePrefix = {arXiv},
eprint = {2211.11461},
primaryClass = {astro-ph.CO},
url = {https://arxiv.org/abs/2211.11461},
}
The software is available under the MIT licence:
Copyright (c) 2023-2026 Deaglan J. Bartlett and Harry Desmond
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Contributors
Below is a list of contributors to this repository.
Documentation
The documentation for this project can be found at this link.
Metadata
Release files for fnprior 0.5.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fnprior-0.5.0.tar.gz | 65.0 kB | With provenance | Details for fnprior-0.5.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fnprior-0.5.0-py3-none-any.whl | Python 3 | none | any | Details for fnprior-0.5.0-py3-none-any.whl |
Total release size: 112.3 kB
Release files / fnprior-0.5.0.tar.gz
| Download URL | fnprior-0.5.0.tar.gz |
|---|---|
| Size | 65.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
071ca12be2c1bcf9f65ab79c5d326cc96f122c8709340b79cec0326423f11d29
|
|
BLAKE2b-256 checksum How to use checksums |
accfbeb6f9c929cce534b8a61e6e0869fe1e5c4b3fe896f183482e7168699387
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.
Transparency logRelease files / fnprior-0.5.0-py3-none-any.whl
| Download URL | fnprior-0.5.0-py3-none-any.whl |
|---|---|
| Size | 47.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
9248134b337b4fd0a33b9ed915b410e9155568e3fa03403905ee3aa731defec2
|
|
BLAKE2b-256 checksum How to use checksums |
6d320493c08b87aa49b1e7059aa4cb504c24f65e663d105252225d12541f9c95
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.
Transparency logSecurity for fnprior 0.5.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for fnprior-0.5.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 16, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.