问题
As a follow-up from this question:
Concatenate input with constant vector in keras
I am trying to use the suggested solution:
constant=K.variable(np.ones((1,10, 5)))
constant = K.repeat_elements(constant,rep=batch_size,axis=0)
And got the following Error:
NameError: name 'batch_size' is not defined
I do not see how one define within the keras model the batch_size [not explicitly] so that one can concatenate a symbolic layer and a constant layer in order to use them as an input layer.
回答1:
To get the dynamic batch size:
batch_size = K.shape(your_tensor)[0]
But K.repeat_elements()
doesn't accept Tensor
values for rep
. You can however produce the same result using K.tile():
from keras.models import *
from keras import backend as K
import numpy as np
a = Input(shape=(10, 5))
batch_size = K.shape(a)[0]
constant = K.variable(np.ones((1,10, 5)))
constant = K.tile(constant, (batch_size, 1, 1))
print(constant)
# Tensor("Tile:0", shape=(?, 10, 5), dtype=float32)
来源:https://stackoverflow.com/questions/50254513/concatenate-input-with-constant-vector-in-keras-how-one-define-the-batch-size