如何将ano.tensor切换到numpy.array?

2024-04-29 21:35:56 发布

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

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

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.

此外,当我使用ano.tensor函数时,它返回的似乎是“tensor”,而且我不能简单地将它切换到numpy.array类型,即使结果的形状应该像矩阵一样。

所以这就是我的问题:如何将outxx切换到numpy.array类型?


Tags: 代码selfnumpy类型inputoutputnparray
2条回答

因为testxx使用sum()from theano.tensor,而不是numpy,所以它可能需要TensorVariable作为输入,而不是numpy数组。

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

在最后一行之前,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))

关于adding scalars的no文档提供了其他类似的示例。

无“张量”变量是符号变量。你用它们构建的东西就像你编写的程序。您需要编译一个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函数并对其执行。

相关问题 更多 >