title: Iterating over a Dataset TF 2.0 with for loop
body: <p>This problem is about how to iterate over a TF Dataset given that <code>make_initializable_iterator()</code> is deprecated.</p>
  
  <p>I read a data set with the function below:</p>
  
  <pre><code>def read_dataset_new(filename, target='delay'):
      ds = tf.data.TFRecordDataset(filename)
      ds = ds.map(lambda buf: parse(buf, target=target))
      ds = ds.batch(1)
      return ds
  </code></pre>
  
  <p>Then I want to iterate over the data set. I have been using:
  <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset#make_initializable_iterator" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/data/Dataset#make_initializable_iterator</a></p>
  
  <pre><code>with tf.compat.v1.Session() as sess:
      data_set = tfr_utils.read_dataset_new(self.tf_rcrds_fl_nm)
      itrtr = data_set.make_initializable_iterator()
      sess.run(itrtr.initializer)
      features, label = itrtr.get_next()
      features_keys = features.keys()
  ...
  </code></pre>
  
  <p>But "Warning: THIS FUNCTION IS DEPRECATED. It will be removed in a future version. Instructions for updating: Use for ... in dataset:...."</p>
  
  <p>Apart from the deprecation warning, my code works as expected.</p>
  
  <p>Given the deprecation warning, though, I am now trying this:</p>
  
  <pre><code>with tf.compat.v1.Session() as sess:
      data_set = tfr_utils.read_dataset_new(self.tf_rcrds_fl_nm)
      for features, label in data_set:
          features_keys = features.keys()
          ...
  </code></pre>
  
  <p>But that does not work. I get:</p>
  
  <pre><code>self = &lt;tensorflow.python.client.session.Session object at 0x12f2e57d0&gt;
  fn = &lt;function BaseSession._do_run.&lt;locals&gt;._run_fn at 0x12f270440&gt;
  args = ({}, [&lt;tensorflow.python.pywrap_tensorflow_internal.TF_Output; proxy of &lt;Swig Object of type 'TF_Output *' at 0x12f3f75a0&gt; &gt;], [], None, None)
  message = 'Resource AnonymousIterator/AnonymousIterator0/N10tensorflow4data16IteratorResourceE does not exist.\n\t [[node Iterat...tNext_1 (defined at /demo-routenet/tests/unit/test_tfrecord_utils.py:376) ]]'
  m = &lt;re.Match object; span=(102, 130), match='[[{{node IteratorGetNext_1}}'&gt;
  </code></pre>
  
  <p>The code samples I have been able to find all explicitly create an iterator, which is apparently not what one is supposed to do. I can't find an example of what one is supposed to do though.</p>
  
  <p>I suspect that something has not been initialised. So, I also tried:</p>
  
  <pre><code>sess.run(data_set)
  </code></pre>
  
  <p>But that didn't work either (nor do I have any reason to suppose it should have, but just so you all know what I tried).</p>
  
  <p>So, how does one use a Dataset in a for loop as the deprecation comment suggests please?</p>