8

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

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?

4

2 回答 2

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() 中有 2 个参数的原因。eval() 是一个接口,它将在具有相应值的给定符号输入上编译和执行 Theano 函数。

于 2014-05-14T16:58:56.603 回答
2

由于testxx使用sum()fromtheano.tensor而不是 from numpy,它可能期望 aTensorVariable作为输入,而不是 numpy 数组。

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

在你的最后一行之前,outxx将是一个TensorVariable取决于a. 所以你可以通过给出 的值来评估它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 关于添加标量的文档提供了其他类似的示例。

于 2015-08-07T17:22:07.730 回答