【问题标题】:Build a graph that works with variable batch size using Tensorflow使用 Tensorflow 构建一个适用于可变批量大小的图
【发布时间】:2016-02-26 09:09:56
【问题描述】:

我使用 tf.placeholders() 操作来提供可变批量大小的输入,它们是 2D 张量,并在我调用 run() 时使用馈送机制为这些张量提供不同的值。 我得到了

TypeError: 'Tensor' 对象不可迭代。

以下是我的代码:

with graph.as_default():
    train_index_input = tf.placeholder(tf.int32, shape=(None, window_size))
    train_embeddings = tf.Variable(tf.random_uniform([vocabulary_size, embedding_dimension], -1.0, 1.0))
    embedding_input = [tf.nn.embedding_lookup(train_embeddings, x) for x in train_index_input]
    ......
    ......

由于不运行图表我无法看到张量“train_index_input”的内容,因此代码会出现“'Tensor' object is not iterable”的错误:

embedding_input = [tf.nn.embedding_lookup(train_embeddings, x) for x in train_index_input]

我想要获得的是一个嵌入矩阵“embedding_input”,其形状为 [batch_size, embedding_dimension],其中 batch_size 不固定。我是否必须在 Tensorflow 中定义一个新操作来嵌入 2D 张量的查找?或者有其他方法吗?谢谢

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    您正在尝试在 Tensorflow 占位符上执行 python 级别的列表理解 (for x in train_index_input)。那是行不通的 - Python 不知道 tf 对象中的内容。

    要完成批量嵌入查找,您可以做的就是展平您的批次:

    train_indexes_flat = tf.reshape(train_index_input, [-1])
    

    通过嵌入查找运行它:

    looked_up_embeddings = tf.nn.embedding_lookup(train_embeddings, train_indexes_flat)
    

    然后将其重新塑造成正确的组:

    embedding_input = tf.reshape(looked_up_embeddings, [-1, window_size])
    

    【讨论】:

    • 我有一个类似的问题,输入的形状是[batch_size, maxstep, 50, 50],我想用某个cnn把它变成[batch_size, maxstep, 5 * 5 * 32],但是没有循环的图很难构建。有什么想法吗?非常感谢。
    猜你喜欢
    • 2017-12-22
    • 2017-09-26
    • 2020-02-26
    • 2016-10-07
    • 1970-01-01
    • 2018-02-07
    • 2018-02-21
    • 2018-11-11
    • 2017-08-05
    相关资源
    最近更新 更多