Search code examples
theano

How to add two shared variables in theano?


A=theano.shared(np.random.randn(2,3))
B=theano.shared(np.random.randn(3,4))
C=A+B

print C gives Elemwise{add,no_inplace}.0

I want the value of C. How do I get it?


Solution

  • Your code as it is will not work since the shapes of your shared variables do not align.

    Correcting your example, you can do

    import theano
    import numpy as np
    
    A = theano.shared(np.random.randn(3, 4))
    B = theano.shared(np.random.randn(3, 4))
    C = A + B
    

    Then this is correctly evaluable. If you are working in command line, then C.eval() will do the trick. However, the more general and comprehensive approach to this is to create a theano function.

    f = theano.function([], C)
    

    Then you can call f() and get the value of C. If your computation depended on other (non-shared) symbolic variables, you would provide the necessary values as arguments to the function (this also works with eval by specifying a dictionary with the relevant entries).