Smart rewrite of expressions in sympy

It seemed to me that this is difficult to explain, but I will do my best using an example.

Consider the expression assigned to the variable gradbelow

 from sympy import *

 a, x, b = symbols("a x b")    
 y_pred = a * x    
 loss = log(1 + exp(- b * y_pred))
 grad = diff(loss, x, 1)

grad has the following expression:

-a*b*exp(-a*b*x)/(1 + exp(-a*b*x))

Now I want to manipulate in gradtwo ways.

1) I want to sympytry to rewrite the expression gradso that none of its expressions looks like

exp(-a*b*x)/(1 + exp(-a*b*x)).

2) I also want him to try to rewrite the expression so that it has at least one expression like this 1./(1 + exp(a*b*x)).

So at the end gradit becomes:

-a*b/(1 + exp(a*b*x)

Note that it is 1./(1 + exp(a*b*x))equivalent exp(-a*b*x)/(1 + exp(-a*b*x)), but I do not want to explicitly point to sympy:).

, , , .

+4
2

cancel

In [16]: cancel(grad)
Out[16]:
  -ab
──────────
 abx
ℯ      + 1

, -a*b*(1/A)/(1 + 1/A), A = exp(a*b*x) cancel p/q (. cancel SymPy ).

, , A = exp(a*b*x) A = exp(-a*b*x). , , cancel

In [17]: cancel(-a*b*exp(a*b*x)/(1 + exp(a*b*x)))
Out[17]:
      a⋅b⋅x
-a⋅b⋅ℯ
────────────
  a⋅b⋅x
 ℯ      + 1
+1

simplify?

>>> grad
-a*b*exp(-a*b*x)/(1 + exp(-a*b*x))
>>> simplify(grad)
-a*b/(exp(a*b*x) + 1)
+1

Source: https://habr.com/ru/post/1628224/


All Articles