Concatenate input with constant vector in keras. how one define the batch_size

微笑、不失礼 提交于 2019-12-24 17:17:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!