Python - solving an equation with unknowns (a and b) MSE (Mean Square error)

140 Views Asked by At

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

enter image description here

I want have 'a' and 'b', and final result should be :

a = 7,25 and b = -14,6

result in documentation (in Polish,but i marked most important things)

I tried do this in Pyhon but i can't, do you known a good library for do that or somethink other?

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)]
1

There are 1 best solutions below

0
On

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

The derivative of S w.r.t. a will be:

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 w.r.t. b will be:

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:

results = solve((dS_da, dS_db), (a,b))
print(results) 
# results below
# {a: 7.25000000000000, b: -14.6000000000000}