Tensorflow 2.0 入門及介紹

2021-02-15 金科優源匯
作者:李婧 | 編輯:餘濤Tensorflow2.0 比1.0 的改變非常多,其整個編程範式也變得和以前完全不一樣,其中2.0比1.0寫起來更加簡單直接,符合一般人的思維模式,採用了動態圖執行,這裡明顯借鑑了Pytorch的模式,比如,如下圖所示,tf2.0寫起來,明顯更加pythonic, tf1.0還需要在構建靜態圖後,通過session進行執行。

同時,tf2.0形成了一套完整的生態,用keras寫代碼,用serving部署,甚至可以用Tensorflow.js在瀏覽器裡面運行,或者用lite在手機等設備上運行,非常方便:


下面以圖片問答任務作為例子演示tf2.0的建模過程,所謂圖片問答,即VQA,是看圖片回答問題的一種任務,如下圖所示:

# A vision model.
# Encode an image into a vector.
vision_model = Sequential()
vision_model.add(Conv2D(64, (3, 3),
activation='relu',
input_shape=(224, 224, 3)))
vision_model.add(MaxPooling2D())
vision_model.add(Flatten())
# Get a tensor with the output of your vision model
image_input = Input(shape=(224, 224, 3))
encoded_image = vision_model(image_input)

# A language model.
# Encode the question into a vector.
question_input = Input(shape=(100,),
dtype='int32',
name="Question")
embedded = Embedding(input_dim=10000,
output_dim=256,
input_length=100)(question_input)
encoded_question = LSTM(256)(embedded_question)

# Concatenate the encoded image and question
merged = layers.concatenate([encoded_image,
encoded_question])

# Train a classifier on top.
output = Dense(1000,
activation='softmax')(merged)
# You can train w/ .fit, .train_on_batch,
# or with a GradientTape.
vqa_model = Model(inputs=[image_input,
question_input],
outputs=output)



model.compile(optimizer=Adam(),
loss=BinaryCrossentropy(),
metrics=[AUC(), Precision(), Recall()])
model.fit(data,
epochs=10,
validation_data=val_data,
callbacks=[EarlyStopping(),
TensorBoard(),
ModelCheckpoint()])


上面是訓練的代碼,tf2.0才用callback模式,讓訓練可以更加靈活的進行定製化操作。

不改變一行代碼轉換為分布式訓練(單機多卡和多機多卡)



tf2.0採用了一種MirroredStrategy技術將單GPU訓練模型非常快速的變成多卡訓練,此技術包括
1. 數據同步技術;
2. 多GPU變量鏡像技術;
3. 在鎖同步中運行副本;
4. All-reduce技術:將所有梯度進行集合約分更新計算的技術。

import tensorflow as tf
model = tf.keras.applications.ResNet50()
optimizer = tf.keras.optimizers.SGD(learning_rate=0.1)
model.compile(..., optimizer=optimizer)
model.fit(train_dataset, epochs=10)

如何將上面代碼變成多卡訓練,只需要加上MirroredStrategy並將模型集成就可以,如下:

import tensorflow as tf
strategy = tf.distribute.MirroredStrategy()
with strategy.scope():
model = tf.keras.applications.ResNet50()
optimizer = tf.keras.optimizers.SGD(learning_rate=0.1)
model.compile(..., optimizer=optimizer)
model.fit(train_dataset, epochs=10)

正真做到了模型代碼一個字不用改。



通過tf lite可以很方便的將模型部署到行動裝置上,這裡用Arduino舉例:

# Convert the model to the TFLite format without quantization
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Save the model to disk
open("gesture_model.tflite", "wb").write(tflite_model)
# Check the size
import os
basic_model_size = os.path.getsize("gesture_model.tflite")
print("Model is %d bytes" % basic_model_size)

部署到行動裝置效果如下:


tf.js可以讓model運行在瀏覽器裡面,也只需幾行代碼:

import tensorflowjs as tfjs
metadata = {
'word_index': tokenizer.word_index,
# …
}
# Save metadata
metadata_json_path = os.path.join(FLAGS.artifacts_dir, 'metadata.json')
json.dump(metadata, open(metadata_json_path, 'wt'))
# Convert your model to TF.js format
tfjs.converters.save_keras_model(model, FLAGS.artifacts_dir)

下圖是一個運行在瀏覽器中的人體姿態識別模型:


相關焦點

  • TensorFlow 2.0入門
    TensorFlow 2.0中的所有新增內容及其教程均可在YouTube頻道及其改版網站上找到。但是今天在本教程中,將介紹在TF 2.0中構建和部署圖像分類器的端到端管道。本教程將有助於匯總此alpha版本中的一些新增內容。
  • TensorFlow2.0學習筆記
    學習筆記地址https://blog.csdn.net/abc13526222160/article/details/101938410TensorFlow2.0筆記1: Tensorflow2.0正式版(2019-10-1)介紹以及安裝+Windows&Linux!
  • TensorFlow 2.0 正式版現已發布
    註:Distribution Strategy API 連結https://tensorflow.google.cn/guide/distributed_training多 GPU 支持 連結https://tensorflow.google.cn/guide/gpuTensorFlow 2.0 在 GPU 性能提升上也作出了很多努力
  • TensorFlow 2.0入門指南
    更進一步地,Google在最近推出了全新的版本TensorFlow 2.0,2.0版本相比1.0版本不是簡單地更新,而是一次重大升級(雖然目前只發布了preview版本)。簡單地來說,TensorFlow 2.0默認採用eager執行模式,而且重整了很多混亂的模塊。毫無疑問,2.0版本將會逐漸替換1.0版本,所以很有必要趁早入手TensorFlow 2.0。
  • tensorflow極速入門
    tensorflow。最後給出了在 tensorflow 中建立一個機器學習模型步驟,並用一個手寫數字識別的例子進行演示。1、 tensorflow是什麼?tensorflow 是 google 開源的機器學習工具,在2015年11月其實現正式開源,開源協議Apache 2.0。
  • TensorFlow 2.0入門指南(上篇)
    這篇文章將簡明扼要地介紹TensorFlow 2.0,以求快速入門。Eager執行AutoGraph性能優化:tf.functionEager執行TensorFlow的Eager執行時一種命令式編程(imperative programming),這和原生Python是一致的,當你執行某個操作時是立即返回結果的。
  • 如何簡單粗暴地上手 TensorFlow 2.0?
    此前,我們曾特邀專家回顧了 TensorFlow 2.0 從初版到最新版本的發展史。今天,我們將介紹一本全面詳解 TensorFlow 2.0 的手冊。這本手冊是 Google Summer of Code 2019 項目之一,從基礎安裝與環境配置、部署,到大規模訓練與加速、擴展,全方位講解 TensorFlow 2.0  的入門要點,並附錄相關資料供讀者參考。
  • C# TensorFlow 2 入門教程 - Eager Mode
    通過開啟會話Session,運行公式(靜態圖)中的節點 「 c 」,並複製 a = 2.0 , b = 3.0 來獲得 c 的數值計算結果。完整代碼如下:using System;using Tensorflow;using static Tensorflow.Binding;namespace TF_Test{    class Program    {        //Basic Operation 2.0
  • 一文上手Tensorflow2.0(四)
    【磐創AI導讀】:本系列文章介紹了與tensorflow的相關知識,
  • TensorFlow 2.0 安裝指南
    TensorFlow 2.0 beta1 已經發布。本文詳細介紹在個人電腦或伺服器上安裝 TensorFlow 2.0 beta1 的步驟和各種細節,讓你第一次安裝 TensorFlow 2.0 就上手!TensorFlow 的 Python 版本使用最為廣泛。
  • Tensorflow Eager Execution入門指南
    【導讀】本文介紹了最新版的Tensorflow 1.7的功能及其使用方法,重點介紹其中最有趣的功能之一eager_execution,它許用戶在不創建靜態圖的情況下運行
  • TensorFlow 2.0 部署:TensorFlow Serving
    使用以下命令即可:tensorflow_model_server \ --rest_api_port=埠號(如8501) \ --model_name=模型名 \ --model_base_path="SavedModel格式模型的文件夾絕對地址(不含版本號)"註解TensorFlow
  • TensorFlow框架簡單介紹
    以下代碼給出了計算定義階段的樣例import tensorflow as tfa = tf.constant([1.0,2.0],name = "a")b = tf.constant([2.0,3.0],name = "b")result = a + b在這個過程中,TensorFlow會自動將定義的計算轉化為計算圖上的節點,可以通過tf.get_default_graph
  • 《30天吃掉那隻 TensorFlow2.0 》全新TF2.0教程收穫1000 Star
    作者 | lyhue1991來源 | GitHub轉自 | Python與算法之美【導讀】本文對書籍《30天吃掉那隻 TensorFlow2.0 》作簡單的內容介紹。TensorFlow2.0 還是 Pytorch?
  • 北大學霸出品,TensorFlow 2.0快速入門指南來了!
    程式設計師書庫(ID:OpenSourceTop)綜合整理綜合自:https://tf.wiki/、https://github.com/snowkylin/tensorflow-handbook2019年10月份,全球用戶最多的深度學習框架的TensorFlow,正式放出了2.0版本,TensorFlow 2.0從簡單、強大、可擴展三個層面進行了重新設計。
  • tensorflow從入門到放棄
    說實話,我都不知道tensorflow是幹啥的,只知道大概和機器學習,AI這些的潮流技術有關。我好奇心比較重,禁不住公眾號宣傳的誘惑,趕緊組隊報名參加了,很快就拿到了帳號,開始在慕課上的學習之路。這個課程前面幾章比較簡單,很快就給我打開了tensorflow的大門。
  • TensorFlow入門
    那我們先跟TensorFlow打個招呼吧~正好測試下我們的TensorFlow環境有沒有搭好~(PS:本文使用的語言為Python2.7.13)import tensorflow as tfhello=tf.constant('hello TensorFlow')sess=tf.Session()print sess.run(hello)輸出:      hello
  • Tensorflow快速入門
    這裡我們介紹一個最流行的深度學習框架:Tensorflow。Tensorflow是谷歌公司在2015年9月開源的一個深度學習框架。雖然我們稱Tensorflow為一種深度學習框架,但是看看官網:圖1 Tensorflow官網界面可以看到,從功能上看,Tensorflow定義為專為機器智能打造的開源軟體庫。
  • Tensorflow 2.0到底好在哪裡?
    「活用 TensorFlow 2.0 指南」(https://www.tensorflow.org/beta/guide/effective_tf2)則使用了高級別的 tf.kerasAPI 取代了舊的底層 API;這將大大減少你需要編寫的代碼量。你只需要每層寫一行代碼就能構建 Keras 神經網絡,如果能善用循環結構的話需要的代碼就更少了。
  • Tensor Flow 2.0 快速掌握手冊
    import tensorflow as tffrom tensorflow.keras.callbacks import TensorBoardfrom tensorflow.keras.optimizers import SGDfrom tensorflow.keras.preprocessing.image import ImageDataGenerator