How to swich theano.tensor to numpy.array?

丶灬走出姿态 提交于 2020-08-04 04:32:53

问题


I have simple codes as shown below:

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)

However, I get the following error information:

ValueError: setting an array element with a sequence.

Furthermore, when I use the function of theano.tensor, it seems that what it returns is called "tensor", and I can't simply switch it to the type numpy.array, even though what the result should shape like a matrix.

So that's my question:how can I switch outxx to type numpy.array?


回答1:


Theano "tensor" variable are symbolic variable. What you build with them are like a programme that you write. You need to compile a Theano function to execute what this program do. There is 2 ways to compile a Theano function:

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

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

When you compile a Theano function, your must tell what the input are and what the output are. That is why there is 2 parameter in the call to theano.function(). eval() is a interface that will compile and execute a Theano function on a given symbolic inputs with corresponding values.




回答2:


Since testxx uses sum() from theano.tensor and not from numpy, it probably expects a TensorVariable as input, and not a numpy array.

=> Replace a = np.array(...) with a = T.matrix(dtype=theano.config.floatX).

Before your last line, outxx will then be a TensorVariable that depends on a. So you can evaluate it by giving the value of a.

=> Replace your last line outxx = np.asarray(...) with the following two lines.

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

The following code runs without errors.

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 documentation on adding scalars gives other similar examples.



来源:https://stackoverflow.com/questions/23643850/how-to-swich-theano-tensor-to-numpy-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!