2017-02-02 11 views
2

私は、インデックスのリストに対してワンホットエンコーディングを計算するための簡単なコードを書いています。 例:[1,2,3] => [[0,1,0,0]、[0,0,1,0]、[0,0,0,1]]theanoのスキャン機能を使ってtheano行列の行を反復する方法は?

私は

n_val =4 
def encoding(x_t): 
    z = T.zeros((x_t.shape[0], n_val)) 
    one_hot = T.set_subtensor(z[T.arange(x_t.shape[0]), x_t], 1) 
    return one_hot 

行列の行の上に同じ機能を繰り返すには、私は次の操作を行い、

x = T.imatrix() 
[m],_ = theano.scan(fn = encoding, sequences = x) 

Y = T.stacklists(m) 
f= theano.function([x],Y) 

を、私は、各スライスと3Dテンソルを期待しています:単一のベクターのために同じことを行うための機能行列の行の1ホットエンコーディングに対応する。機能をコンパイル中

私は

/Library/Python/2.7/site-packages/theano/tensor/var.pyc in __iter__(self) 
594   except TypeError: 
595    # This prevents accidental iteration via builtin.sum(self) 
--> 596    raise TypeError(('TensorType does not support iteration. ' 
    597        'Maybe you are using builtin.sum instead of ' 
598        'theano.tensor.sum? (Maybe .max?)')) 

TypeError: TensorType does not support iteration. Maybe you are using builtin.sum instead of theano.tensor.sum? (Maybe .max?) 

は、誰かが私を理解する助けてくださいすることができ、次のエラーを取得していますどこが間違っていると私は私が必要なものを取得するためにコードを変更することができますか?

ありがとうございます。ここで

+0

'' scan'のfn'引数はリストを返す必要が働くのコードです – Kh40tiK

答えて

1

# input a matrix, expect scan to work with each row of matrix 
my_matrix = np.asarray([[1,2,3],[1,3,2],[1,1,1]]) 

x = T.imatrix() 

def encoding(idx): 
    z = theano.tensor.zeros((idx.shape[0], 4)) 
    one_hot = theano.tensor.set_subtensor(z[theano.tensor.arange(idx.shape[0]), idx], 1) 
    return one_hot 

m, update = theano.scan(fn=encoding, 
         sequences=x) 


f = theano.function([x], m) 

##########3 
result = f(my_matrix) 
print (result) 
関連する問題