[英]Python - solving an equation with unknowns (a and b) MSE (Mean Square error)
I want solve this equation (in string) (mean square error):我想解决这个方程(在字符串中)(均方误差):
(2.5 - (2.0 * a + b ))**2 + (10.0 - (4.0 * a + b ))**2 + (32.0 - (6.0 * a + b ))**2 + (40.0 - (8.0 * a + b ))**2 + (60.0 - (10.0 * a + b ))**2
I want have 'a' and 'b', and final result should be :我想要'a'和'b',最终结果应该是:
a = 7,25 and b = -14,6
I tried do this in Pyhon but i can't, do you known a good library for do that or somethink other?我试过在 Pyhon 做这个,但我做不到,你知道一个很好的图书馆来做这个还是其他的?
a = symbols('a')
b = symbols('b')
results = solve("(2.5 - (2.0 * a + b ))**2 + (10.0 - (4.0 * a + b ))**2 + (32.0 - (6.0 * a + b ))**2 + (40.0 - (8.0 * a + b ))**2 + (60.0 - (10.0 * a + b ))**2",[a,b])
print(results)
# result below
#[(-0.136363636363636*b - 1.05632686526519*sqrt(-0.00370329222678962*b**2 - 0.108136133022257*b - 1) + 5.25909090909091, b), (-0.136363636363636*b + 1.05632686526519*sqrt(-0.00370329222678962*b**2 - 0.108136133022257*b - 1) + 5.25909090909091, b)]
First of all, you need to take derivatives of the equation S with respect to a and b , as shown in the book, and give them to function Eq() (which also should be imported from sympy ), and only then use the solve() function首先,您需要对方程S关于a和b求导,如书中所示,并将它们提供给函数Eq() (也应该从sympy导入),然后才使用求解()函数
The derivative of S wrt a will be: S wrt a的导数将是:
dS_da = Eq(2*(2.5 - (2.0*a + b))*(-2.0) + 2*(10.0-(4.0*a + b))*(-4) \
+ 2*(32.0 - (6.0*a + b))*(-6)+ 2*(40.0 - (8.0*a + b))*(-8) \
+ 2*(60.0 - (10.0*a + b))*(-10))
and the derivative of S wrt b will be: S wrt b的导数将是:
dS_db = Eq(2*(2.5 - (2.0*a + b))*(-1) + 2*(10.0-(4.0*a + b))*(-1) \
+ 2*(32.0 - (6.0*a + b))*(-1) + 2*(40.0 - (8.0*a + b))*(-1) \
+ 2*(60.0 - (10.0*a + b))*(-1))
After that, you pass the derivatives to the solve function in order to get the values of a and b :之后,将导数传递给求解函数以获得a和b的值:
results = solve((dS_da, dS_db), (a,b))
print(results)
# results below
# {a: 7.25000000000000, b: -14.6000000000000}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.