如何从Google机器学习崩溃课程中替换make_one_shot_iterator()

问题描述 投票:0回答:1

我正在学习Google机器学习强化课程。但是它使用TensorFlow的1.x版本,因此我打算更改这些练习以使其能够在TensorFlow 2.0中运行。但我被困在该练习中:

https://colab.research.google.com/notebooks/mlcc/first_steps_with_tensor_flow.ipynb?utm_source=mlcc&utm_campaign=colab-external&utm_medium=referral&utm_content=firststeps-colab&hl=es#scrollTo=7UwqGbbxP53O

特别是代码:

    def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):
    """Trains a linear regression model of one feature.

    Args:
      features: pandas DataFrame of features
      targets: pandas DataFrame of targets
      batch_size: Size of batches to be passed to the model
      shuffle: True or False. Whether to shuffle the data.
      num_epochs: Number of epochs for which data should be repeated. None = repeat indefinitely
    Returns:
      Tuple of (features, labels) for next data batch
    """

    # Convert pandas data into a dict of np arrays.
    features = {key:np.array(value) for key,value in dict(features).items()}                                           

    # Construct a dataset, and configure batching/repeating.
    ds = Dataset.from_tensor_slices((features,targets)) # warning: 2GB limit
    ds = ds.batch(batch_size).repeat(num_epochs)

    # Shuffle the data, if specified.
    if shuffle:
      ds = ds.shuffle(buffer_size=10000)

    # Return the next batch of data.
    features, labels = ds.make_one_shot_iterator().get_next()
    return features, labels

我已将features, labels = ds.make_one_shot_iterator().get_next()替换为features, labels = tf.compat.v1.data.make_one_shot_iterator(ds).get_next()

它似乎可以工作,但是make_one_shot_iterator()已弃用,所以,我该如何替换它?

也根据https://github.com/tensorflow/tensorflow/issues/29252,我已经尝试过

 features, labels = ds.__iter__()
    next(ds.__iter__())
    return features, labels

但返回错误__iter __ () is only supported inside of tf.function or when eager execution is enabled.

我对python缺乏经验,并以业余爱好者的身份学习课程。关于如何解决的任何想法?谢谢。

tensorflow iterator tensorflow-datasets
1个回答
0
投票

经过几次测试,python挂起是一个本地问题。为了替换features, labels = ds.make_one_shot_iterator (). Get_next (),我尝试了以下几种方法:

features, labels = ds.__iter__().get_next()

iterator = ds.__iter__()
features, labels = iterator.get_next()

it = iter(ds)
features, labels = next(it)

所有三种情况都返回__iter__() is only supported inside of tf.function or when eager execution is enabled.,所以我尝试了:

features, labels = ds
return ds

也是:

return features, labels

并且都返回相同的错误,最后我尝试了:

return ds

而且它神秘地起作用了,我不知道为什么,但是它起作用了。

© www.soinside.com 2019 - 2024. All rights reserved.