Theano 矩阵由 theano 标量组成

Theano matrix composed of theano scalars

如何创建由 theano 个标量组成的 theano 矩阵? 以下代码创建一个由 theano 个标量组成的 numpy 数组。但我想要一个 theano 矩阵。

C = T.cos
S = T.sin
q = T.fscalar(name="q%d"%self.i)

names = ['x','y','z']
Sx,Sy,Sz = map(lambda name: T.fscalar(name=name),names)

self.mat = np.array([[C(q),-S(q)*C(alpha),S(q)*S(alpha),a*C(q)+Sx],
                    [S(q),C(q)*C(alpha),-C(q)*S(alpha),a*S(q)+Sy],
                    [0,S(alpha),C(alpha),d+Sz],
                    [0,0,0,1]])

您可以使用 theano.tensor.stacklists 的方式与使用 np.array 构造普通 numpy 数组的方式大致相同:

import numpy as np
import theano
from theano import tensor as te

a = te.fscalar("a")
b = te.fscalar("b")
M = te.stacklists([[a, b], [b, a]])

f = theano.function([a, b], M)

print(f(1.0, 2.0))
# [[ 1.  2.]
#  [ 2.  1.]]

您可以通过使用 theano.tensor.stack or theano.tensor.concatenate 从标量构造一维向量,然后使用其 reshape 方法将其重塑为具有所需尺寸的 matrix/tensor 来获得相同的结果.