1

I have a custom Keras layer and i use Theano as the backend and i want to do the following operation:

Suppose we have a tensor with shape (N,). I want to set the K first values to a fixed value x (3 or whatever...). How do i do that? I assume i have to use argsort but i don't know how to implement it using Theano.

For example in a simple FF layer, how can i set the first N values of the tensor a to a value x?

def call(self, x, mask=None):
    a = K.dot(x, self.W)

    if self.bias:
        a += self.b

    return a

For example using numpy i can set the 10 first values of a to 1 like this:

a[a.argsort() <= 10] = 1

I want to do the same using Keras backend functions or Theano functions.

4

1 回答 1

1

对于a[a.argsort() <= 10] = 1等效代码将是:

import numpy as np
from keras import backend as K

a = np.asarray([[3,4,2,44,22,4,5,6,77,86,3,2,3,23,44,21],
                [3,4,22,44,2,4,54,6,77,8,3,2,36,23,4,2]], dtype=np.float)
a_t = K.variable(a)

a[a.argsort() <= 10] = 1
print a

arg_sort = K.T.argsort(a_t)
_cond = K.lesser_equal(arg_sort,10)
a_new = K.switch(_cond, 1, a_t)
print K.eval(a_new)

在一个单一的声明中,它将是:

a_new = K.switch(K.lesser_equal(K.T.argsort(a_t),10), 1, a_t)
print K.eval(a_new)

我不确定这是否正是您所需要的。

于 2017-01-29T01:31:21.710 回答