【问题标题】:Applying element wise conditional functions on Theano TensorVariable在 Theano TensorVariable 上应用逐元素条件函数
【发布时间】:2017-06-01 20:54:02
【问题描述】:

如果可能的话,对我来说最简单的事情可能是发布我尝试直接在 Theano 中执行的 numpy 代码:

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 个不同矩阵组成的张量的一个矩阵中的值,并将其应用于张量中的其他矩阵。

真的,我要解决的问题是在 Keras 中为完全卷积网络的目标函数执行条件语句。基本上,根据其中一个特征图中的一些值,某些特征图值的损失将与其他值不同地计算(并随后加权)。

【问题讨论】:

    标签: python deep-learning theano keras objective-function


    【解决方案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 操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      • 1970-01-01
      • 2016-07-20
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      相关资源
      最近更新 更多