为了账号安全,请及时绑定邮箱和手机立即绑定

将 TensorFlow 1.5 转换为 TensorFlow 2

将 TensorFlow 1.5 转换为 TensorFlow 2

拉莫斯之舞 2022-06-28 17:40:03
你会如何将此 TensorFlow 1.5 代码转换为 Tensorflow 2?import tensorflow as tftry:    Session = tf.Sessionexcept AttributeError:    Session = tf.compat.v1.SessionA = 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 tfA = 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 倍?
查看完整描述

2 回答

?
Cats萌萌

TA贡献1805条经验 获得超9个赞

您当然应该利用 TF 2.x 的优势,包括 Eager Execution。它不仅非常方便,而且效率更高。


import tensorflow as tf


def get_values():

  A = tf.random.normal([10_000,10_000])

  B = tf.random.normal([10_000,10_000])

  return A,B


@tf.function

def compute():

  A,B = get_values()

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


print(compute())

您(大部分)在 TF 2.x 中不再需要任何会话,Auto Graph 会自动为您完成。


只需使用注释“主要”功能@tf.function(无需注释其他功能,例如get_values,这也会自动发生)。


查看完整回答
反对 回复 2022-06-28
?
largeQ

TA贡献2039条经验 获得超8个赞

关于您的第一个问题,我能够让它在 Colab 中运行,并添加了“disable_eager_execution()”调用 - 似乎 TF 2.0 中默认启用了“eager execution”模式:


# Install TensorFlow

try:

  # %tensorflow_version only exists in Colab.

    %tensorflow_version 2.x

except Exception:

    pass


import numpy as np

import tensorflow as tf

from tensorflow.python.framework.ops import disable_eager_execution

disable_eager_execution()

print(tf.executing_eagerly())

print(tf.__version__)

matdim = 1000

try:

    Session = tf.Session

except AttributeError:

    Session = tf.compat.v1.Session

A = 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))))

我希望这有帮助。


查看完整回答
反对 回复 2022-06-28
  • 2 回答
  • 0 关注
  • 401 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号