我试图在keras模型中创建一个常量变量。到目前为止,我一直在做的是将其作为输入传递。但是它始终是一个常量,因此我希望将其作为常量(输入[1,2,3...50]用于每个示例=>,因此我np.tile(np.array(range(50)),(len(X_input)))通常在每个示例中都进行重现)
所以现在我有了:
constant_input = Input(shape=(50,), dtype='int32', name="constant_input")
Run Code Online (Sandbox Code Playgroud)
给出张量: 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")
Run Code Online (Sandbox Code Playgroud)
给出张量: 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...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2807 次 |
| 最近记录: |