[英]How to swich theano.tensor to numpy.array?
我有如下所示的簡單代碼:
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類型?
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函數。
由於testxx
使用theano.tensor
而不是numpy
sum()
,因此它可能期望使用TensorVariable
作為輸入,而不是numpy數組。
=>將a = np.array(...)
替換為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有關添加標量的文檔提供了其他類似示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.