在Keras中创建恒定值 [英] Creating constant value in Keras

查看:83
本文介绍了在Keras中创建恒定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在keras模型中创建一个常量变量.到目前为止,我一直在做的是将其作为输入传递.但这始终是一个常量,因此我希望将其作为常量.(每个示例的输入为[1,2,3...50] =>,因此每个示例都使用np.tile(np.array(range(50)),(len(X_input)))进行重现)

I am trying to create a constant variable inside a keras model. What I was doing till now is to pass it as Input. But it is always a constant so I want it as a constant.(The input is [1,2,3...50] for each example => so I use np.tile(np.array(range(50)),(len(X_input))) to reproduce it for each example)

所以我现在有:

constant_input = Input(shape=(50,), dtype='int32', name="constant_input")

哪个给出张量:Tensor("constant_input", shape(?,50), dtype=int32)

现在尝试将其作为常量:

Now trying to do it as a constant:

np_constant = np.array(list(range(50))).reshape(1, 50)
tf_constant = K.constant(np_constant)
tensor_constant = Input(tensor=tf_constant, shape=(50,), dtype='int32', name="constant_input")

给出张量:Tensor("constant_input", shape(50,1),dtype=float32)

但是我想要的是每批中要缩放的常数,这意味着张量的形状应该为(?, 50),与使用Input的方式相同.

But What I want is the constant to be scaled in each batch, meaning that the shape of the tensor should be (?, 50), the same as the way of using Input.

有可能这样做吗?

推荐答案

您不能拥有大小可变的常量.常数始终具有相同的值.您可以做的是拥有(1, 50)常量,然后使用 K.tile 将其平铺在TensorFlow中.也最好使用 np.arange 而不是np.array(list(range(50)).像这样:

You cannot have a constant with variable size. A constant always has the same value. What you can do is have the (1, 50) constant and then tile it within TensorFlow with K.tile. Also better use np.arange instead of np.array(list(range(50)). Something like:

from keras.layers.core import Lambda
import keras.backend as K

def operateWithConstant(input_batch):
    tf_constant = K.constant(np.arange(50).reshape((1, 50)))
    batch_size = K.shape(input_batch)[0]
    tiled_constant = K.tile(tf_constant, (batch_size, 1))
    # Do some operation with tiled_constant and input_batch
    result = ...
    return result

input_batch = Input(...)
input_operated = Lambda(operateWithConstant)(input_batch)
# continue...

这篇关于在Keras中创建恒定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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