简体   繁体   English

在 TensorFlow 中禁用急切执行时如何计算均方误差?

[英]How to calculate mean square error when eager execution is disabled in TensorFlow?

When calculating MSE using tensorflow, I get the error AttributeError: 'Tensor' object has no attribute 'numpy' The reason is that I need to disable eager execution ( tf.disable_eager_execution() ).使用 tensorflow 计算 MSE 时,出现错误AttributeError: 'Tensor' object has no attribute 'numpy' The reason is that I need to disable eager execution ( tf.disable_eager_execution() )。 Question: How to calculate mean square error when eager execution is disabled in TensorFlow?问题:在 TensorFlow 中禁用急切执行时如何计算均方误差? The code looks something like this (I'm using the latest version of tenorflow):代码看起来像这样(我使用的是最新版本的 tenorflow):

tf.disable_eager_execution()

mse = tf.keras.losses.MeanSquaredError()
MSE = mse(y_true, y_prediction).numpy()

You can't and shouldn't.你不能也不应该。 When eager execution is disabled, the calculations and objects are leaving Python. The goal of this is to train a model with an optimized backend rather than "slow" Python. As a side effect, the objects and values aren't accessible to Python. This is fine when you train a model, which you would be able to run in Python. However, this doesn't work if you want to monitor every operation.当 Eager Execution 被禁用时,计算和对象将离开 Python。这样做的目的是训练一个具有优化后端的 model 而不是“慢”Python。作为副作用,Python 无法访问对象和值。当你训练一个 model 时,这很好,你可以在 Python 中运行它。但是,如果你想监控每个操作,这就不起作用了。

If you want to access tensor values, just enable eager execution.如果你想访问张量值,只需启用 eager execution。

You need to create a session. This should work (tested on TF 2.5):您需要创建一个 session。这应该有效(在 TF 2.5 上测试):

tf.compat.v1.disable_eager_execution()

mse = tf.keras.losses.MeanSquaredError()
MSE = mse(y_true, y_prediction)

with tf.compat.v1.Session().as_default():
    MSE.eval()

Though I concur with Nicolas that debugging is better (and more easily) done in eager mode.尽管我同意 Nicolas 的观点,即在 eager 模式下调试会更好(也更容易)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM