【问题标题】:Why do we need Theano reshape?为什么我们需要 Theano 重塑?
【发布时间】:2015-12-20 19:17:02
【问题描述】:

我不明白为什么我们需要 Theano 中的tensor.reshape() 函数。文档中说:

返回该张量的视图,该视图已被重新整形,如 numpy.reshape.

据我了解,theano.tensor.var.TensorVariable 是一些用于创建计算图的实体。它完全独立于形状。例如,当您创建函数时,您可以传递矩阵 2x2 或矩阵 100x200。正如我认为重塑以某种方式限制了这种多样性。但事实并非如此。假设如下示例:

X = tensor.matrix('X')
X_resh = X.reshape((3, 3))
Y = X_resh ** 2
f = theano.function([X_resh], Y)

print(f(numpy.array([[1, 2], [3, 4]])))

据我了解,它应该会出错,因为我传递了矩阵 2x2 而不是 3x3,但它可以完美地计算元素平方。

那么theano张量变量的shape是什么,我们应该在哪里使用呢?

【问题讨论】:

    标签: theano


    【解决方案1】:

    提供的代码中存在错误,但 Theano 未能指出这一点。

    代替

    f = theano.function([X_resh], Y)
    

    你真的应该使用

    f = theano.function([X], Y)
    

    使用原始代码,您实际上是在 reshape 之后提供张量,因此 reshape 命令永远不会被执行。这可以通过添加来看到

    theano.printing.debugprint(f)
    

    打印出来的

    Elemwise{sqr,no_inplace} [id A] ''   0
     |<TensorType(float64, matrix)> [id B]
    

    请注意,在这个编译后的执行图中没有重塑操作。

    如果更改代码以使用 X 而不是 X_resh 作为输入,那么 Theano 会抛出包含消息的错误

    ValueError: 新数组的总大小必须保持不变 导致错误:Reshape{2}(X, TensorConstant{(2L,) of 3})

    这是意料之中的,因为无法将形状为 (2, 2)(即 4 个元素)的张量重塑为形状为 (3, 3)(即 9 个元素)的张量。

    为了解决更广泛的问题,我们可以在目标形状中使用符号表达式,这些表达式可以是输入张量符号形状的函数。下面是一些例子:

    import numpy
    import theano
    import theano.tensor
    
    X = theano.tensor.matrix('X')
    X_vector = X.reshape((X.shape[0] * X.shape[1],))
    X_row = X.reshape((1, X.shape[0] * X.shape[1]))
    X_column = X.reshape((X.shape[0] * X.shape[1], 1))
    X_3d = X.reshape((-1, X.shape[0], X.shape[1]))
    f = theano.function([X], [X_vector, X_row, X_column, X_3d])
    
    for output in f(numpy.array([[1, 2], [3, 4]])):
        print output.shape, output
    

    【讨论】:

      猜你喜欢
      • 2020-10-05
      • 1970-01-01
      • 2019-06-09
      • 2013-12-17
      • 2011-12-12
      • 1970-01-01
      • 2015-10-26
      • 2014-06-18
      • 2017-02-26
      相关资源
      最近更新 更多