Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python sympy, how do I apply an external python funtion to each element of the sympy matrix?

To be more specific, I want to apply the following sigmoid function:

def sigmoid(x):
  return 1 / (1 + m.exp(-x))

to each element of the following 2x2 Sympy Matrix:

Matrix([[1,3],[2,4]])
Matrix([
[1, 3],
[2, 4]])

Such that on applying the sigmoid function onto the matrix I'll get a new 2x2 Matrix where each individual element of the Matrix had the sigmoid applied to it. Like the following :

Matrix([[ sigmoid(1), sigmoid(3) ],[ sigmoid(2), sigmoid(4) ]])

How can this be done?

like image 699
random_x_y_z Avatar asked Sep 18 '25 04:09

random_x_y_z


1 Answers

>>> M.applyfunc(sigmoid)

Matrix([
[1/(exp(-1) + 1), 1/(exp(-3) + 1)],
[1/(exp(-2) + 1), 1/(exp(-4) + 1)]])

This is using SymPy's exp in the sigmoid function. If m.exp means you are importing exp from math, then the result won't look nice, and will error out if the matrix contains symbols.


If you literally want sigmoid(1) and so on inside the function, then sigmoid needs to be a SymPy function that does not evaluate anything.

class sigmoid(Function):
    pass

With this,

>>> M.applyfunc(sigmoid)
Matrix([
[sigmoid(1), sigmoid(3)],
[sigmoid(2), sigmoid(4)]])

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!