tensorflow 1.X迁移至tensorflow2 代码写法
這里寫目錄標題
- 目標:代碼改寫成tf2格式
- tf1和tf2區(qū)別:
- 改寫內(nèi)容:
- tf.placeholder
- tf.Sess,sess.run
- 具體例子1:
- 結論:
目標:代碼改寫成tf2格式
把tensorflow 1.X中的代碼,遷移到tensorflow2中。一些常見的改寫經(jīng)驗。包括sess,tf.placeholder, tf.InteractiveSession(),tf.Session()
tensorflow2相比于tensorflow 1.x版本有較大的變化,且網(wǎng)上現(xiàn)在好多文章的代碼都是基于tf1.x版本的,學會簡單的轉換,幫助我們看代碼。
整體來說,tensorflow2更加簡潔了。
本文將持續(xù)更新中。
當然用tf.compat.v1也能解決部分問題。但是不推薦,畢竟tf2才是未來。
tf1和tf2區(qū)別:
- 1、tf1基于圖模式,tf2基于eager模式,tf2對程序員更友好,更像是函數(shù),更方便調(diào)試。
- 2、tf2更向keras靠攏,對分布式訓練的支持更好。
改寫內(nèi)容:
tf.placeholder
tensorflow 1.x版本中的placeholder,在tf2中已經(jīng)被取消,在tf2中,可以用tf.keras.Inputs代替。
示例:
tf1中
tf2中,改寫為:
input_ids = tf.keras.Input(dtype=tf.int32, shape=[None])tf.Sess,sess.run
-
tensorflow 1.x由于是基于靜態(tài)圖機制(Graph Execution),需要先構造圖,然后才真正運行,因此需要用顯示調(diào)用Session后,才會真正觸發(fā)計算。對調(diào)試代碼非常不利。
-
tensorflow 2.x默認是基于動態(tài)圖機制(Eager Execution),就像常規(guī)函數(shù)一樣,調(diào)用時就觸發(fā)計算。對調(diào)試代碼非常方便。
所以,tf1中session部分代碼,可以全部去掉。
示例:
tf1中
tf2中,改寫為:
直接不要具體例子1:
tf1的代碼:源自
import tensorflow as tf import numpy as np# 定義一個未知變量input_ids用于存儲索引 input_ids = tf.placeholder(dtype=tf.int32, shape=[None])# 定義一個已知變量embedding,是一個5*3的矩陣 embedding = a = np.asarray([[0.1, 0.2, 0.3], [1.1, 1.2, 1.3], [2.1, 2.2, 2.3], [3.1, 3.2, 3.3], [4.1, 4.2, 4.3]])# 根據(jù)input_ids中的id,查找embedding中對應的元素 input_embedding = tf.nn.embedding_lookup(embedding, input_ids)sess = tf.InteractiveSession() sess.run(tf.global_variables_initializer()) # print(embedding.eval()) print(sess.run(input_embedding, feed_dict={input_ids: [1, 2, 3, 0, 3, 2, 1]}))改寫tf2代碼:
import tensorflow as tf import numpy as np# 定義一個未知變量input_ids用于存儲索引 input_ids = tf.keras.Input(dtype=tf.int32, shape=[None])# 定義一個已知變量embedding,是一個5*3的矩陣 embedding = a = np.asarray([[0.1, 0.2, 0.3], [1.1, 1.2, 1.3], [2.1, 2.2, 2.3], [3.1, 3.2, 3.3], [4.1, 4.2, 4.3]])input_ids = np.array([1, 2, 3, 0, 3, 2, 1]) # 根據(jù)input_ids中的id,查找embedding中對應的元素 input_embedding = tf.nn.embedding_lookup(embedding, input_ids) print(input_embedding)可見,tf2代碼簡潔明了不少,多動手試試,就能體會。
結論:
深刻體會tf2帶來的變革。
1、體會靜態(tài)圖和動態(tài)圖的差別
2、體會對分布式訓練的優(yōu)化(未來寫)
3、體會模型訓練的便利性(直接用compile等,keras的便利性。)
總結
以上是生活随笔為你收集整理的tensorflow 1.X迁移至tensorflow2 代码写法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TensorFlow2快速模型构建及te
- 下一篇: tensorflow2 训练和预测使用不