切片在no中转换矩阵

2024-10-03 04:28:12 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下代码片段:

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

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

^{pr2}$

显然,使用长度为1的数组进行索引可以将xsub2转换为col而不是矩阵。如何使xsub2成为矩阵?在


Tags: importsizeastypenpbatchtheanotensor
1条回答
网友
1楼 · 发布于 2024-10-03 04:28:12

col或“column vector”是Theano知道只包含一列的符号矩阵的名称。应该可以像矩阵一样使用它。在

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

如果你考虑的是形状而不是类型,那么你会发现,阿诺的行为和纽比一样:

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()

这个指纹

^{pr2}$

因此col实际上是一个有一列的矩阵,而不是一个向量。在

相关问题 更多 >