亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 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 關注
  • 363 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號