Casadi MX type softMax math operation

377 views
Skip to first unread message

Guang Yang

unread,
Oct 24, 2018, 11:12:25 AM10/24/18
to CasADi
Hello,

I am trying to apply a softmax function on a MX type matrix with (n x 1) dimension.

from casadi import *
import math

n
=10 #dimension
mx_vec
= MX.sym('mx_vec',n,1)

def softMax():
    sum
= 0
    C
= 5.0 #C is a constant for softmax function
   
for mx_element in mx_vec:
        sum
= sum + math.exp(mx_element*C)
    max
= math.log(sum)/C
   
return max


But I got a runtime error
RuntimeError:.../casadi/core/mx_node.cpp:373:'to_double' not defined for class N6casadi7UnaryMXE

The softMax() function works for a list of float type when I test it. But how can I implement it with MX type?

Joris Gillis

unread,
Oct 24, 2018, 4:24:52 PM10/24/18
to CasADi
Dear Guang,

No need to iterate over elements, and no need for 'math':

log(sum1(exp(mx_vec*C)))/C

Best,
 Joris
Reply all
Reply to author
Forward
0 new messages