如何从张量中随机采样k个条目获取输出

时间:2019-09-21 17:42:06

标签: python tensorflow keras

我使用张量值的二次采样来解决keras / tf问题。我的模型如下:

x_input = Input((input_size,))
enc1 = Dense(encoder_size[0], activation='relu')(x_input)
drop = Dropout(keep_prob)(enc1)
enc2 = Dense(encoder_size[1], activation='relu')(drop)
drop = Dropout(keep_prob)(enc2)
mu = Dense(latent_dim, activation='linear', name='encoder_mean')(drop)
encoder = Model(x_input,mu)

我想从输入中随机采样,然后获取输入的编码值。我收到的错误是

ValueError: When feeding symbolic tensors to a model, we expect the tensors to have a static batch size. Got tensor with shape: (None, 13)

我可以理解的

是因为“预测”不适用于占位符,但是我不确定传递给占位符输出的内容。

# sample input randomly
sample_num = 500
idxs = tf.range(tf.shape(x_input)[0])
ridxs = tf.random_shuffle(idxs)[:sample_num]
sample_input = tf.gather(x_input, ridxs)
# get sample shape
sample_shape = K.shape(sample_input)
# sample from encoded value
sample_encoded = encoder.predict(sample_input) <----- Error

1 个答案:

答案 0 :(得分:2)

如果您看到predict函数文档,它不希望将占位符或张量节点作为期望的输入集。您必须直接传递Numpy数组(在您的情况下)。

如果您希望执行某些常规数据不包含的特殊数据预处理,则必须在Numpy中进行,并避免使用Tensor计算。