gpt4 book ai didi

theano - 为什么我们需要 Theano reshape ?

转载 作者:行者123 更新时间:2023-12-01 23:15:31 26 4
gpt4 key购买 nike

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

Returns a view of this tensor that has been reshaped as in numpy.reshape.

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

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,但它可以完美地计算元素方 block 。

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

最佳答案

尽管 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]

请注意,此编译执行图中没有 reshape 操作。

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

ValueError: total size of new array must be unchanged Apply node that caused the error: Reshape{2}(X, TensorConstant{(2L,) of 3})

这是意料之中的,因为不能将形状为 (2, 2)(即 4 个元素)的张量 reshape 为形状为 (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

关于theano - 为什么我们需要 Theano reshape ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34361769/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com