2016-04-25 7 views
1

Ich möchte mit Theano eine zusammengesetzte Funktion f (x, g (x)) berechnen. Leider, wenn ich versuche, eine Funktionszusammensetzung zu programmieren, beschwert sich Python über einen TypeError. Betrachten wir zum Beispiel die folgende einfache Skript:Wie kann ich eine zusammengesetzte Funktion mit Theano bilden?

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) 

Beim Schreiben funComp = composition() Python gibt eine Typeerror:

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

Allerdings kann ich kompilieren und die Funktion fun = f() berechnen. Gibt es eine Möglichkeit, eine Funktionszusammensetzung erfolgreich einzurichten? Ich bin dankbar für jede Hilfe!

Antwort

1

Sie brauchen für diesen Fall keine Mehrfachfunktion. Das funktioniert gut.

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) 
+0

@maliobro: Vielen Dank für Ihre Antwort! Leider, wenn ich das Skript und mit f = composition() am Ende und dann versuchen, f (1.1) zu berechnen (zum Beispiel) sagt Python TypeError: 'TensorVariable' Objekt ist nicht aufrufbar. Hast du eine Vorstellung davon, was falsch sein könnte? – fabian

+1

@fabian Es tut mir leid für die späte Antwort, ich war mit Ihrer f() -Funktion verwechselt, aber diese Funktionen war eine funktionierende Kompositionsfunktion. Ich habe meinen Code bearbeiten, probieren Sie es aus. – malioboro

+0

Willkommen, ich bin froh, dass ich helfen konnte :) – malioboro