【问题标题】:What is iteration over placeholder in Tensorflow?什么是 Tensorflow 中占位符的迭代?
【发布时间】:2018-05-16 17:15:11
【问题描述】:

我得到了以下(伪)代码from doc

words_in_dataset = tf.placeholder(tf.float32, [time_steps, batch_size, num_features])
...
for current_batch_of_words in words_in_dataset:

但是我们如何迭代占位符呢?

【问题讨论】:

    标签: python tensorflow iterator


    【解决方案1】:

    你不能,除非你有eager execution,它本质上是动态评估事物。在您的情况下,这只是伪代码,尽管它只是一种误导性的伪代码,它只是暗示了算法如何遍历给定单词数据集中的批次。

    【讨论】:

      【解决方案2】:

      占位符仅适用于会话图模式。它们在 Eager 模式下不可用,这没有意义。占位符用于将张量提供给图形,因为您不构建图形,首先不需要占位符。

      就迭代占位符和伪代码而言,伪代码仅显示我们将实现的算法。

      要遍历占位符,您将执行以下操作:

      import tensorflow as tf
      X = tf.placeholder(dtype=tf.float32, shape=[5])
      with tf.Session() as sess:
          for i in range(5):
              print(sess.run(X[i], feed_dict={X : [1,2,3,4,5]}))
      

      那么输出将是:

      1.0

      2.0

      3.0

      4.0

      5.0

      切片规则与numpy数组相同。

      【讨论】:

        【解决方案3】:

        由于每个批次都必须在time steps 中拆分,您可以这样做:

        for current_batch_of_words in tf.unstack(words_in_dataset,axis=0):
        

        示例代码,

        # Set LSTM params
        
        time_steps = 3
        num_features = 5
        batch_size = 2
        
        #Input placeholder
        words_in_dataset = tf.placeholder(tf.float32, [time_steps, batch_size, num_features])
        
        lstm= tf.contrib.rnn.BasicLSTMCell(num_units=10)
        
        # Initial state of the LSTM memory.
        hidden_state, current_state = basic_cell.zero_state(batch_size, dtype=tf.float32)
        state = hidden_state, current_state
        
        # Create a loop of N LSTM cells, N = time_steps.
        outputs = []
        for current_batch_of_words in tf.unstack(words_in_dataset,axis=0):
        
            # The value of state is updated after processing each batch of words.
            output, state= lstm(current_batch_of_words, state)
            outputs.append(output) 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-10-12
          相关资源
          最近更新 更多