简体   繁体   中英

How can I form a composite Function with Theano?

I would like to compute a composite function f(x, g(x)) with Theano. Unfortunately, when I try to code a function composition, Python complains about a TypeError. For example, consider the following simple script:

import theano
import theano.tensor as T

x = T.dscalar('x')

def g():
    y1 = T.sqr(x)
    return theano.function([x], y1)

def composition():
    input = g()
    yComp = x * input
    return  theano.function([x], yComp)

def f():
    y1 = T.sqr(x)
    yMult = x * y1
    return theano.function([x], yMult)

When writing funComp = composition() Python returns a TypeError:

TypeError: unsupported operand type(s) for *: 'TensorVariable' and 'Function' 

However, I can compile and calculate the function fun = f() . Is there a way to successfully establish a function composition? I am grateful for any help!

You don't need multiple function actually for this case. This one works well.

import theano
import theano.tensor as T

x = T.dscalar('x')


def g():
    y1 = T.sqr(x)
    return y1

def composition():
    input = g()
    yComp = x * input
    return  theano.function([x], yComp)

tfunc = composition()
print tfunc(4)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM