如何在给定 dtype 和形状的情况下创建任意 theano 张量?
How do I create an arbitrary theano tensor given a dtype and a shape?
如何在给定数据类型和形状的情况下创建任意 theano 张量?我宁愿不对形状的长度和 dtype 的种类进行大的切换。
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)
使用theano.tensor.TensorType(dtype, broadcastable)
dtype 是一个 numpy dtype 字符串,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 对象,那么您必须将它们映射到字符串。
如何在给定数据类型和形状的情况下创建任意 theano 张量?我宁愿不对形状的长度和 dtype 的种类进行大的切换。
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)
使用theano.tensor.TensorType(dtype, broadcastable)
dtype 是一个 numpy dtype 字符串,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 对象,那么您必须将它们映射到字符串。