2016-04-27 39 views
0

如何創建一個給定dtype和shape的任意theano張量?我寧願不爲dtype的形狀和種類做長時間的轉換。如何根據dtype和形狀創建任意theano張量?

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) 

回答

1

使用theano.tensor.TensorType(dtype, broadcastable)

的D型是一個numpy的D型字符串,broadcastable是布爾值,指定如果維度是broadcastable與否的列表。

你的函數的一個例子是:

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) 

dtype這裏應該像'float32'一個字符串,而不是numpy的對象像np.float32。如果你絕對必須使用numpy對象,那麼你必須將它們映射到字符串。