2017-01-17 5 views
0

最も簡単な方法は次のようになります。Theano TensorVariableに要素賢明な条件付きの関数を適用

tensor = shared(np.random.randn(7, 16, 16)).eval() 

tensor2 = tensor[0,:,:].eval() 
tensor2[tensor2 < 1] = 0.0 
tensor2[tensor2 > 0] = 1.0 

new_tensor = [tensor2] 
for i in range(1, tensor.shape[0]): 
    new_tensor.append(np.multiply(tensor2, tensor[i,:,:].eval())) 

output = np.array(new_tensor).reshape(7,16,16) 

それはすぐに明らかではない場合は、私がしようとしているのは、7つの異なる行列からなるテンソルの1つの行列の値を使用し、それをテンソルの他の行列に適用することです。

本当に、私が解決している問題は、Kerasの完全寛容ネットワークの目的関数で条件文を実行することです。基本的に、一部のフィーチャマップ値の損失は、フィーチャマップの1つの値の一部に応じて、他とは異なる方法で計算されます(その後、重み付けされます)。

答えて

1

switchステートメントで簡単に条件文を実装できます。

import theano 
from theano import tensor as T 
import numpy as np 


def _check_new(var): 
    shape = var.shape[0] 
    t_1, t_2 = T.split(var, [1, shape-1], 2, axis=0) 
    ones = T.ones_like(t_1) 
    cond = T.gt(t_1, ones) 
    mask = T.repeat(cond, t_2.shape[0], axis=0) 
    out = T.switch(mask, t_2, T.zeros_like(t_2)) 
    output = T.join(0, cond, out) 
    return output 

def _check_old(var): 
    tensor = var.eval() 

    tensor2 = tensor[0,:,:] 
    tensor2[tensor2 < 1] = 0.0 
    tensor2[tensor2 > 0] = 1.0 
    new_tensor = [tensor2] 

    for i in range(1, tensor.shape[0]): 
     new_tensor.append(np.multiply(tensor2, tensor[i,:,:])) 

    output = theano.shared(np.array(new_tensor).reshape(7,16,16)) 
    return output 


tensor = theano.shared(np.random.randn(7, 16, 16)) 
out1 = _check_new(tensor).eval() 
out2 = _check_old(tensor).eval() 
print out1 
print '----------------' 
print ((out1-out2) ** 2).mean() 

注:最初のフィルタであなたのマスキング以来、私はsplitjoin操作を使用するために必要なここ

は同等のコードになります。

関連する問題