Python 如何在给定数据类型和形状的情况下创建任意theano张量?

Python 如何在给定数据类型和形状的情况下创建任意theano张量?,python,theano,Python,Theano,如何在给定数据类型和形状的情况下创建任意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.int1

如何在给定数据类型和形状的情况下创建任意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)

使用编号tensor.TensorType(数据类型,可广播)

数据类型是一个numpy数据类型字符串,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'
的字符串,而不是类似
np.float32
的numpy对象。如果绝对必须使用numpy对象,那么必须将它们映射到字符串