Skip to main content
 首页 » 编程设计

python之Theano 中的切片将矩阵转换为向量

2024年10月24日10cyq1162

考虑以下代码片段:

import theano.tensor as T 
import theano.tensor 
import numpy as np 
 
batch_shape = (50, 40, 30, 30) 
batch_size = batch_shape[0] 
ncols = batch_shape[1]*batch_shape[2]*batch_shape[3] 
minibatch = theano.tensor.tensor4(name='minibatch',  
                                  dtype=theano.config.floatX) 
xflat = minibatch.reshape((batch_size,ncols)) 
 
partition = np.array([1, 2, 3]) 
xsub1 = xflat[:,partition] 
 
partition = np.array([1]) 
xsub2 = xflat[:,partition] 
 
print "xsub1.type: ", xsub1.type 
print "xsub2.type: ", xsub2.type 

如果你运行它,你会得到以下输出:

xsub1.type: TensorType(float64, matrix) 
xsub2.type: TensorType(float64, col) 

显然,使用长度为 1 的数组进行索引会将 xsub2 变成 col 而不是矩阵。我怎样才能使 xsub2 成为矩阵?

请您参考如下方法:

col 或“列向量”是 Theano 用于表示它知道仅包含一列的符号矩阵的名称。应该可以像矩阵一样使用它。

Theano 通常不知道特定符号张量的形状,只知道它的维度。然而,在某些情况下,例如问题中给出的情况,Theano 能够推断出张量具有特定的形状特殊情况,并且有时可以使用此信息来优化计算。这就是为什么 col(和 row)作为 matrix 的特例存在。

如果你更多地考虑形状而不是类型,那么你会发现 Theano 的行为与 numpy 一样:

import theano 
import theano.tensor 
import numpy as np 
 
 
def compute(minibatch): 
    xflat = minibatch.reshape((minibatch.shape[0], -1)) 
    partition = np.array([1, 2, 3]) 
    xsub1 = xflat[:, partition] 
    partition = np.array([1]) 
    xsub2 = xflat[:, partition] 
    return xsub1, xsub2 
 
 
def compile_theano_version(): 
    minibatch = theano.tensor.tensor4(name='minibatch', dtype=theano.config.floatX) 
    xsub1, xsub2 = compute(minibatch) 
    print xsub1.type, xsub2.type 
    return theano.function([minibatch], [xsub1, xsub2]) 
 
 
def numpy_version(minibatch): 
    return compute(minibatch) 
 
 
def main(): 
    batch_shape = (50, 40, 30, 30) 
    minibatch = np.random.standard_normal(size=batch_shape).astype(theano.config.floatX) 
 
    xsub1, xsub2 = numpy_version(minibatch) 
    print xsub1.shape, xsub2.shape 
 
    theano_version = compile_theano_version() 
    xsub1, xsub2 = theano_version(minibatch) 
    print xsub1.shape, xsub2.shape 
 
 
main() 

这打印

(50L, 3L) (50L, 1L) 
TensorType(float64, matrix) TensorType(float64, col) 
(50L, 3L) (50L, 1L) 

所以 col 确实是一个只有一列的矩阵,不是向量。