‘XXX‘ object has no attribute ‘xxx‘ tensorflow版本间函数变动 踩坑记录

1.AttributeError: module ‘tensorflow’ has no attribute ‘py_func’

官方文档: https://www.tensorflow.org/api_docs/python/tf/compat/v1/py_func
我将py_func换成tf.compat.v1.py_func通过。

tf.compat.v1.py_func(
    func, inp, Tout, stateful=True, name=None
)

Caution: This API was designed for TensorFlow v1.

This name was deprecated and removed in TF2, but tf.numpy_function is a near-exact replacement, just drop the stateful argument (all tf.numpy_function calls are considered stateful). It is compatible with eager execution and tf.function.

tf.py_function is a close but not an exact replacement, passing TensorFlow tensors to the wrapped function instead of NumPy arrays, which provides gradients and can take advantage of accelerators.

Before:

def fn_using_numpy(x):
  x[0] = 0.
  return x
tf.compat.v1.py_func(fn_using_numpy, inp=[tf.constant([1., 2.])],
    Tout=tf.float32, stateful=False)

After:

tf.numpy_function(fn_using_numpy, inp=[tf.constant([1., 2.])],
    Tout=tf.float32)

2.AttributeError: ‘PrefetchDataset’ object has no attribute ‘make_one_shot_iterator’

切换为tf.compat.v1.data.make_one_shot_iterator

这是用于使用数据集元素的旧 API,仅应在从 TF 1 过渡到 TF 2 期间使用。请注意,使用此 API 应该是代码库的临时状态,因为通常不能保证 TF 1 的互操作性 和 TF 2 代码。

Last code :

    if params['is_conditional']:
        train_x, train_y = dataset.make_one_shot_iterator().get_next()
    else:
        train_x, train_y = dataset.make_one_shot_iterator().get_next(), None

New code :

    if params['is_conditional']:
        train_x, train_y = tf.compat.v1.data.make_one_shot_iterator(dataset).get_next()
    else:
        train_x, train_y = tf.compat.v1.data.make_one_shot_iterator(dataset).get_next(), None

3.此类问题解决方案

(1) 用conda创建另一环境安装TF1;

(2)参考官方文档对自己的代码进行自动化改造。

链接:https://www.tensorflow.org/guide/migrate

你可能感兴趣的:(tensorflow,python,深度学习)