如何将theano.tensor转换为numpy.array?

8 投票
2 回答
14278 浏览
提问于 2025-04-18 06:28

我有一些简单的代码,如下所示:

class testxx(object):
    def __init__(self, input):
        self.input = input
        self.output = T.sum(input)
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype = np.float32)
classfier = testxx(a)
outxx = classfier.output
outxx = np.asarray(outxx, dtype = np.float32)

但是,我遇到了以下错误信息:

ValueError: setting an array element with a sequence.

此外,当我使用theano.tensor的功能时,它返回的结果叫做“张量”,而我不能简单地把它转换成numpy.array类型,尽管结果看起来应该像一个矩阵。

所以我的问题是:我该如何把outxx转换成numpy.array类型呢?

2 个回答

2

因为 testxx 使用的是来自 theano.tensorsum() 函数,而不是来自 numpy 的,所以它可能需要一个 TensorVariable 作为输入,而不是一个 numpy 数组。

=> 把 a = np.array(...) 替换成 a = T.matrix(dtype=theano.config.floatX)

在你最后一行代码之前,outxx 将会是一个依赖于 aTensorVariable。所以你可以通过给 a 赋值来计算它。

=> 把你最后一行 outxx = np.asarray(...) 替换成下面的两行。

f = theano.function([a], outxx)
outxx = f(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype = np.float32))

以下代码可以正常运行,没有错误。

import theano
import theano.tensor as T
import numpy as np

class testxx(object):
    def __init__(self, input):
        self.input = input
        self.output = T.sum(input)
a = T.matrix(dtype=theano.config.floatX)
classfier = testxx(a)
outxx = classfier.output
f = theano.function([a], outxx)
outxx = f(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype = np.float32))

Theano 的文档中关于 添加标量 的部分提供了其他类似的例子。

3

Theano中的“张量”变量是符号变量。用它们构建的东西就像你写的程序。你需要编译一个Theano函数来执行这个程序的操作。编译Theano函数有两种方法:

f = theano.function([testxx.input], [outxx])
f_a1 = f(a)

# Or the combined computation/execution
f_a2 = outxx.eval({testxx.input: a})

当你编译一个Theano函数时,必须告诉它输入是什么,输出是什么。这就是为什么在调用theano.function()时需要两个参数。eval()是一个接口,它会在给定的符号输入和相应的值上编译并执行一个Theano函数。

撰写回答