[英]How to convert a user input string into an equations which can be used to find the best fit to some data
I have some x and y data which I plot in a graph window. 我在图形窗口中绘制了一些x和y数据。 I would like a user to define an equation and then use something like SciPy to find the best values for that equation. 我希望用户定义一个方程,然后使用SciPy之类的东西为该方程找到最佳值。
As an example equation user input => y = ((m^2 / c^4) * 2)^0.5 例如,方程式用户输入=> y =((m ^ 2 / c ^ 4)* 2)^ 0.5
How can I put this string into curve_fitting or something similar and find the missing values please? 如何将这个字符串放入curve_fitting或类似的东西中,然后找到缺少的值? I thought I could use an anonymous function but that seems to not be working for me. 我以为可以使用匿名函数,但这似乎对我不起作用。
You might find lmfit ( http://lmfit.github.io/lmfit-py/ ) useful for this purpose. 您可能会发现lmfit( http://lmfit.github.io/lmfit-py/ )对于此目的很有用。 As part of its high-level approach to curve-fitting, it has an ExpressionModel
class that supports user-defined model functions taken from Python expressions. 作为高级曲线拟合方法的一部分,它具有ExpressionModel
类,该类支持从Python表达式获取的用户定义的模型函数。 More details can be found at http://lmfit.github.io/lmfit-py/builtin_models.html#user-defined-models . 可以在http://lmfit.github.io/lmfit-py/builtin_models.html#user-defined-models中找到更多详细信息。 As a simple example (taken from the example folder in the github repo): 作为一个简单的示例(取自github存储库中的example文件夹):
import numpy as np
import matplotlib.pyplot as plt
from lmfit.models import ExpressionModel
x = np.linspace(-10, 10, 201)
amp, cen, wid = 3.4, 1.8, 0.5
y = amp * np.exp(-(x-cen)**2 / (2*wid**2)) / (np.sqrt(2*np.pi)*wid)
y = y + np.random.normal(size=len(x), scale=0.01)
gmod = ExpressionModel('amp * exp(-(x-cen)**2 /(2*wid**2))/(sqrt(2*pi)*wid)')
result = gmod.fit(y, x=x, amp=5, cen=5, wid=1)
print(result.fit_report())
plt.plot(x, y, 'bo')
plt.plot(x, result.init_fit, 'k--')
plt.plot(x, result.best_fit, 'r-')
plt.show()
will print out the results of 将打印出结果
[[Model]]
Model(_eval)
[[Fit Statistics]]
# function evals = 54
# data points = 201
# variables = 3
chi-square = 0.019
reduced chi-square = 0.000
Akaike info crit = -1856.580
Bayesian info crit = -1846.670
[[Variables]]
amp: 3.40478705 +/- 0.005053 (0.15%) (init= 5)
cen: 1.79930413 +/- 0.000858 (0.05%) (init= 5)
wid: 0.50051059 +/- 0.000858 (0.17%) (init= 1)
[[Correlations]] (unreported correlations are < 0.100)
C(amp, wid) = 0.577
Just to be clear: this uses the asteval module ( https://newville.github.io/asteval/ ) to parse and evaluate the user input in a way that tries to be as safe as possible from malicious user input that would be exposed using a plain eval
. 只需说明一下:它使用asteval模块( https://newville.github.io/asteval/ )来解析和评估用户输入,以使其尽可能避免暴露于恶意用户输入的安全使用简单的eval
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.