Theano/Keras:将Tensor的K-first值设置为一个值 [英] Theano / Keras: Set the K-first values of Tensor to a value

查看:61
本文介绍了Theano/Keras:将Tensor的K-first值设置为一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的Keras层,我使用Theano作为后端,我想执行以下操作:

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

假设我们有一个张量为(N,)的张量.我想将K个第一个值设置为固定值x(3或其他...).我怎么做?我假设我必须使用argsort,但我不知道如何使用Theano来实现它.

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.

例如在简单的FF层中,如何将张量a的前N个值设置为值x?

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

例如,使用numpy,我可以将a的10个第一个值设置为1,如下所示:

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

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

我想使用Keras后端函数或Theano函数执行相同的操作.

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

推荐答案

对于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)

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

I am not sure if this is exactly what you need.

这篇关于Theano/Keras:将Tensor的K-first值设置为一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆