在Keras中创建恒定值

发布于 2021-01-29 16:52:09

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

所以现在我有了:

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

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

现在尝试将其作为常量:

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

有可能这样做吗?

关注者
0
被浏览
44
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您不能有大小可变的常数。常数始终具有相同的值。您可以做的就是获取(1, 50)常量,然后使用将该常量平铺在TensorFlow中K.tile。也可以np.arange代替更好地使用np.array(list(range(50))。就像是:

    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...
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看