在Keras中创建恒定值
我试图在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
。
有可能这样做吗?
-
您不能有大小可变的常数。常数始终具有相同的值。您可以做的就是获取
(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...