将 TensorFlow 1.5 转换为 TensorFlow 2

你会如何将此 TensorFlow 1.5 代码转换为 Tensorflow 2?


import tensorflow as tf

try:

    Session = tf.Session

except AttributeError:

    Session = tf.compat.v1.Session

A = random_normal([10000,10000])

B = random_normal([10000,10000])

with Session() as sess:

    print(sess.run(tf.reduce_sum(tf.matmul(A,B))))

主要问题是Session该类已在 Tensorflow 2 中删除,并且该compat.v1层中暴露的版本实际上似乎并不兼容。当我使用 Tensorflow 2 运行此代码时,它现在会引发异常:


RuntimeError: Attempting to capture an EagerTensor without building a function.

如果我完全放弃使用Session,那在功能上是否仍然等效?如果我运行:


import tensorflow as tf

A = random_normal([10000,10000])

B = random_normal([10000,10000])

with Session() as sess:

    print(tf.reduce_sum(tf.matmul(A,B)))

它在支持 AVX2 的 Tensoflow 1.16 中运行速度明显更快(0.005 秒对 30 秒),而从 pip 安装的库存 Tensorflow 2(不支持 AVX2)也运行得更快一些(30 秒对 60 秒)。


为什么使用SessionTensorflow 1.16 会减慢 6000 倍?


拉莫斯之舞
浏览 402回答 2
2回答

Cats萌萌

您当然应该利用 TF 2.x 的优势,包括 Eager Execution。它不仅非常方便,而且效率更高。import tensorflow as tfdef get_values():  A = tf.random.normal([10_000,10_000])  B = tf.random.normal([10_000,10_000])  return A,B@tf.functiondef compute():  A,B = get_values()  return tf.reduce_sum(tf.matmul(A,B))print(compute())您(大部分)在 TF 2.x 中不再需要任何会话,Auto Graph 会自动为您完成。只需使用注释“主要”功能@tf.function(无需注释其他功能,例如get_values,这也会自动发生)。

largeQ

关于您的第一个问题,我能够让它在 Colab 中运行,并添加了“disable_eager_execution()”调用 - 似乎 TF 2.0 中默认启用了“eager execution”模式:# Install TensorFlowtry:  # %tensorflow_version only exists in Colab.    %tensorflow_version 2.xexcept Exception:    passimport numpy as npimport tensorflow as tffrom tensorflow.python.framework.ops import disable_eager_executiondisable_eager_execution()print(tf.executing_eagerly())print(tf.__version__)matdim = 1000try:    Session = tf.Sessionexcept AttributeError:    Session = tf.compat.v1.SessionA = tf.random.normal([matdim,matdim])B = tf.random.normal([matdim,matdim])with Session() as sess:    print(sess.run(tf.reduce_sum(tf.matmul(A,B))))我希望这有帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python