2016-04-27 4 views
0

Wie erstelle ich einen beliebigen theano Tensor mit einem dtype und einer Form? Ich würde lieber keinen großen Schalter für die Länge der Form und Art des Dtypes machen.Wie erstelle ich einen beliebigen theano tensor mit einem dtype und einer Form?

import numpy as np 
from theano import tensor 


def arbitrary_tensor(dtype, shape, name=None): 
    function = { 
     np.float32: 'f', 
     np.float64: 'd', 
     np.int8: 'b', 
     np.int16: 'w', 
     np.int32: 'i', 
     np.int64: 'l', 
     np.complex64: 'c', 
     np.complex128: 'z', 
    }[dtype] 

    function += { 
     0: 'scalar', 
     1: 'vector', 
     2: 'matrix', 
     3: 'tensor3', 
     4: 'tensor4'}[len(shape)] 

    return getattr(tensor, function)(name=name) 

Antwort

1

Verwenden theano.tensor.TensorType(dtype, broadcastable)

Die dtype ist ein numpy dtype String und broadcast ist eine Liste der Boolesche Werte angibt, ob die Dimension broadcast ist oder nicht.

wäre ein Beispiel für Ihre Funktion sein:

def arbitrary_tensor(dtype, shape, name=None): 
    # create the type. 
    var_type = theano.tensor.TensorType(
     dtype=dtype, 
     broadcastable=[False]*len(shape)) 

    # create the variable from the type. 
    return var_type(name) 

Außer dass dtype hier sollte wie 'float32' eine Zeichenfolge sein, kein numpy Objekt wie np.float32. Wenn Sie unbedingt numpige Objekte verwenden müssen, müssen Sie sie auf Zeichenfolgen abbilden.