Theano 从 TensorType col 转换为 TensorType 矩阵

Theano converting from TensorType col to TensorType matrix

由于检查 Theano 的扫描函数内部检查是否在多个地方使用了相同类型的变量,我收到了一个错误。此函数不允许将 col TensorType 的 (N, 1)(N, 1) 矩阵交换(请参阅下面的错误)。

如何 cast/convert col TensorType 的 (N, 1) Tensor 到 matrix TensorType?

TypeError: ('The following error happened while compiling the node', forall_inplace,cpu,scan_fn}(TensorConstant{20}, InplaceDimShuffle{1,0,2}.0, IncSubtensor{InplaceSet;:int64:}.0, IncSubtensor{InplaceSet;:int64:}.0, IncSubtensor{InplaceSet;:int64:}.0, TensorConstant{20}, condpred_1_W_ih, condpred_1_W_ho, embedding_1_W, InplaceDimShuffle{x,0}.0, InplaceDimShuffle{x,0}.0, AdvancedIncSubtensor{inplace=False, set_instead_of_inc=True}.0), '\n', "Inconsistency in the inner graph of scan 'scan_fn' : an input and an output are associated with the same recurrent state and should have the same type but have type 'TensorType(int32, matrix)' and 'TensorType(int32, col)' respectively.")

您需要使用theano.tensor.patternbroadcast

如果看到herefmatrix的形状是(?, ?)fcol的形状是(?, 1)?的意思是维度可以取任意值。所以形状不是区分 fmatrixfcol 的好方法。现在,请参阅可广播列。 fmatrix 的最后一个维度不可广播,而 fcol 的最后一个维度是。所以下面的代码应该在这些类型之间进行转换。

让我们将矩阵转换为列,然后反之亦然。

from theano import tensor as T

x = T.fmatrix('x')
x_to_col = T.patternbroadcast(x, (False, True))
x.type
x_to_col.type

y = T.fcol('y')
y_to_matrix = T.patternbroadcast(y, (False, False))
y.type
y_to_matrix.type

运行在控制台执行以上命令,发现数据类型确实发生了变化。因此,您要么更改 fmatrix 变量,要么更改 fcol 变量。