如何解决属性错误:模块'tensorflow.compat.v2'没有属性'py_func'



defaurocc (y_true, y_pred):返回tf.py_func(roc_auc_score, (y_true, y_pred))

adam = keras.optimizers.Adam(lr=0.0001)model.compile(优化器=亚当,损失= categorical_crossentropy,指标= [aurocc])model.fit(输入、标签validation_split = 0.33,时代= 10,verbose = 1,回调=回调)

AttributeError: in user code:

/usr/local/lib/python3.7/dist-packages/keras/engine/training.py:830 train_function  *
return step_function(self, iterator)
/usr/local/lib/python3.7/dist-packages/keras/engine/training.py:813 run_step  *
outputs = model.train_step(data)
/usr/local/lib/python3.7/dist-packages/keras/engine/training.py:775 train_step  *
self.compiled_metrics.update_state(y, y_pred, sample_weight)
/usr/local/lib/python3.7/dist-packages/keras/engine/compile_utils.py:457 update_state  *
metric_obj.update_state(y_t, y_p, sample_weight=mask)
/usr/local/lib/python3.7/dist-packages/keras/metrics.py:169 decorated  *
update_op = update_state_fn(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/keras/metrics.py:155 update_state_fn  *
return ag_update_state(*args, **kwargs)
/usr/local/lib/python3.7/dist-packages/keras/metrics.py:641 update_state  *
matches = ag_fn(y_true, y_pred, **self._fn_kwargs)
<ipython-input-46-e104431197fe>:2 aurocc  *
return tf.py_func(roc_auc_score, (y_true, y_pred))
AttributeError: module 'tensorflow.compat.v2' has no attribute 'py_func'

这个名字tf.compat.v1.py_func在TF2中已被弃用并删除,但您可以使用tf.numpy_function代替。

Before:(在Tensorflow 2.x中显示警告)

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)

输出:

WARNING:tensorflow:From <ipython-input-4-2c02087a506a>:5: py_func (from tensorflow.python.ops.script_ops) is deprecated and will be removed in a future version.
Instructions for updating:
tf.py_func is deprecated in TF V2. Instead, there are two
options available in V2.
- tf.py_function takes a python function which manipulates tf eager
tensors instead of numpy arrays. It's easy to convert a tf eager tensor to
an ndarray (just call tensor.numpy()) but having access to eager tensors
means `tf.py_function`s can use accelerators such as GPUs as well as
being differentiable using a gradient tape.
- tf.numpy_function maintains the semantics of the deprecated tf.py_func
(it is not differentiable, and manipulates numpy arrays). It drops the
stateful argument making all functions stateful.

<tf.Tensor: shape=(2,), dtype=float32, numpy=array([0., 2.], dtype=float32)>

:

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

输出:

<tf.Tensor: shape=(2,), dtype=float32, numpy=array([0., 2.], dtype=float32)>

详情请参考此链接

相关内容

最新更新