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

2024-10-04 05:23:23 发布

您现在位置:Python中文网/ 问答频道 /正文

def aurocc(y_正确,y_预测): 返回tf.py_func(roc_auc_分数,(y_真,y_pred))

adam=keras.optimizers.adam(lr=0.0001) compile(优化器=adam,loss='classifical\u crossentropy',metrics=[aurocc]) model.fit(输入、标签、验证\u split=0.33、epochs=10、verbose=1、callbacks=callbacks)

AttributeError:在用户代码中:

/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'

Tags: pylibpackagesusrlocaldiststepupdate
1条回答
网友
1楼 · 发布于 2024-10-04 05:23:23

TF2中已弃用并删除了此名称tf.compat.v1.py_func,但您可以改用tf.numpy_function

之前:(在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)>

有关更多详细信息,请参阅此link

相关问题 更多 >