在 Keras 中创造常量值 [英] Creating constant value in 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)
常量,然后在 TensorFlow 中使用 K.tile
.也更好地使用 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屋!