10 個TensorFlow 2.x 使用技巧

2021-03-02 機器學習實驗室

TensorFlow 2.x在構建模型和TensorFlow的整體使用方面提供了很多簡單性。那麼TF2有什麼新變化呢?

在本文中,我們將探索TF 2.0的10個特性,這些特性使得使用TensorFlow更加順暢,減少了代碼行數並提高了效率。

1(a). tf.data 構建輸入管道

tf.data提供了數據管道和相關操作的功能。我們可以建立管道,映射預處理函數,洗牌或批處理數據集等等。

從tensors構建管道
>>> dataset = tf.data.Dataset.from_tensor_slices([8, 3, 0, 8, 2, 1])
>>> iter(dataset).next().numpy()
8

構建Batch並打亂
# Shuffle
>>> dataset = tf.data.Dataset.from_tensor_slices([8, 3, 0, 8, 2, 1]).shuffle(6)
>>> iter(dataset).next().numpy()
0

# Batch
>>> dataset = tf.data.Dataset.from_tensor_slices([8, 3, 0, 8, 2, 1]).batch(2)
>>> iter(dataset).next().numpy()
array([8, 3], dtype=int32)

# Shuffle and Batch
>>> dataset = tf.data.Dataset.from_tensor_slices([8, 3, 0, 8, 2, 1]).shuffle(6).batch(2)
>>> iter(dataset).next().numpy()
array([3, 0], dtype=int32)

把兩個Datsets壓縮成一個
>>> dataset0 = tf.data.Dataset.from_tensor_slices([8, 3, 0, 8, 2, 1])
>>> dataset1 = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5, 6])
>>> dataset = tf.data.Dataset.zip((dataset0, dataset1))
>>> iter(dataset).next()
(<tf.Tensor: shape=(), dtype=int32, numpy=8>, <tf.Tensor: shape=(), dtype=int32, numpy=1>)

映射外部函數
def into_2(num):
     return num * 2
    
>>> dataset = tf.data.Dataset.from_tensor_slices([8, 3, 0, 8, 2, 1]).map(into_2)
>>> iter(dataset).next().numpy()
16

1(b). ImageDataGenerator

這是tensorflow.keras API的最佳特性之一。ImageDataGenerator能夠在批處理和預處理以及數據增強的同時實時生成數據集切片。

生成器允許直接從目錄或數據目錄中生成數據流。

ImageDataGenerator中關於數據增強的一個誤解是,它向現有數據集添加了更多的數據。雖然這是數據增強的實際定義,但是在ImageDataGenerator中,數據集中的圖像在訓練的不同步驟被動態地變換,使模型可以在未見過的有噪數據上進行訓練。

train_datagen = ImageDataGenerator(
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True
)

在這裡,對所有樣本進行重新縮放(用於歸一化),而其他參數用於增強。

train_generator = train_datagen.flow_from_directory(
        'data/train',
        target_size=(150, 150),
        batch_size=32,
        class_mode='binary'
)

我們為實時數據流指定目錄。這也可以使用dataframes來完成。

train_generator = flow_from_dataframe(
    dataframe,
    x_col='filename',
    y_col='class',
    class_mode='categorical',
    batch_size=32
)

x_col參數定義圖像的完整路徑,而y_col參數定義用於分類的標籤列。

模型可直接用生成器來餵數據。需要指定steps_per_epoch參數,即number_of_samples // batch_size.

model.fit(
    train_generator,
    validation_data=val_generator,
    epochs=EPOCHS,
    steps_per_epoch=(num_samples // batch_size),
    validation_steps=(num_val_samples // batch_size)
)

2. 使用tf.image做數據增強

數據增強是必要的。在數據不足的情況下,對數據進行更改並將其作為單獨的數據點來處理,是在較少數據下進行訓練的一種非常有效的方式。

tf.image API中有用於轉換圖像的工具,然後可以使用tf.data進行數據增強。

flipped = tf.image.flip_left_right(image)
visualise(image, flipped)

上面的代碼的輸出
saturated = tf.image.adjust_saturation(image, 5)
visualise(image, saturated)

上面的代碼的輸出
rotated = tf.image.rot90(image)
visualise(image, rotated)

上面的代碼的輸出
cropped = tf.image.central_crop(image, central_fraction=0.5)
visualise(image, cropped)

上面的代碼的輸出
3. TensorFlow Datasets
pip install tensorflow-datasets

這是一個非常有用的庫,因為它包含了TensorFlow從各個領域收集的非常著名的數據集。

import tensorflow_datasets as tfds

mnist_data = tfds.load("mnist")
mnist_train, mnist_test = mnist_data["train"], mnist_data["test"]
assert isinstance(mnist_train, tf.data.Dataset)

tensorflow-datasets中可用的數據集的詳細列表可以在:https://www.tensorflow.org/datasets/catalog/overview中找到。

tfds提供的數據集類型包括:音頻,圖像,圖像分類,目標檢測,結構化數據,摘要,文本,翻譯,視頻。

4. 使用預訓練模型進行遷移學習

遷移學習是機器學習中的一項新技術,非常重要。如果一個基準模型已經被別人訓練過了,而且訓練它需要大量的資源(例如:多個昂貴的gpu,一個人可能負擔不起)。轉移學習,解決了這個問題。預先訓練好的模型可以在特定的場景中重用,也可以為不同的場景進行擴展。

TensorFlow提供了基準的預訓練模型,可以很容易地為所需的場景擴展。

base_model = tf.keras.applications.MobileNetV2(
    input_shape=IMG_SHAPE,
    include_top=False,
    weights='imagenet'
)

這個base_model可以很容易地通過額外的層或不同的模型進行擴展。如:

model = tf.keras.Sequential([
    base_model,
    global_average_layer,
    prediction_layer
])

5. Estimators

估計器是TensorFlow對完整模型的高級表示,它被設計用於易於擴展和異步訓練

預先制定的estimators提供了一個非常高級的模型抽象,因此你可以直接集中於訓練模型,而不用擔心底層的複雜性。例如:

linear_est = tf.estimator.LinearClassifier(
    feature_columns=feature_columns
)

linear_est.train(train_input_fn)
result = linear_est.evaluate(eval_input_fn)

這顯示了使用tf.estimator. Estimators構建和訓練estimator是多麼容易。estimator也可以定製。

TensorFlow有許多estimator ,包括LinearRegressor,BoostedTreesClassifier等。

6. 自定義層

神經網絡以許多層深網絡而聞名,其中層可以是不同的類型。TensorFlow包含許多預定義的層(如density, LSTM等)。但對於更複雜的體系結構,層的邏輯要比基礎的層複雜得多。對於這樣的情況,TensorFlow允許構建自定義層。這可以通過子類化tf.keras.layers來實現。

class CustomDense(tf.keras.layers.Layer):
    def __init__(self, num_outputs):
        super(CustomDense, self).__init__()
        self.num_outputs = num_outputs

    def build(self, input_shape):
        self.kernel = self.add_weight(
            "kernel",
            shape=[int(input_shape[-1]),
            self.num_outputs]
        )

    def call(self, input):
        return tf.matmul(input, self.kernel)

正如在文檔中所述,實現自己的層的最好方法是擴展 tf.keras.Layer類並實現:

_init_,你可以在這裡做所有與輸入無關的初始化。build,其中你知道輸入張量的形狀,然後可以做剩下的初始化工作。

雖然kernel的初始化可以在*_init_中完成,但是最好在build中進行初始化,否則你必須在創建新層的每個實例上顯式地指定input_shape*。

7. 自定義訓練

tf.keras Sequential 和Model API使得模型的訓練更加容易。然而,大多數時候在訓練複雜模型時,使用自定義損失函數。此外,模型訓練也可能不同於默認訓練(例如,分別對不同的模型組件求梯度)。

TensorFlow的自動微分有助於有效地計算梯度。這些原語用於定義自定義訓練循環。

def train(model, inputs, outputs, learning_rate):
    with tf.GradientTape() as t:
        # Computing Losses from Model Prediction
        current_loss = loss(outputs, model(inputs))
        
    # Gradients for Trainable Variables with Obtained Losses
    dW, db = t.gradient(current_loss, [model.W, model.b])
    
    # Applying Gradients to Weights
    model.W.assign_sub(learning_rate * dW)
    model.b.assign_sub(learning_rate * db)

這個循環可以在多個epoch中重複,並且根據用例使用更定製的設置。

8. Checkpoints

保存一個TensorFlow模型可以有兩種方式:

SavedModel:保存模型的完整狀態以及所有參數。這是獨立於原始碼的。model.save_weights('checkpoint')

Checkpoints 捕獲模型使用的所有參數的值。使用Sequential API或Model API構建的模型可以簡單地以SavedModel格式保存。

然而,對於自定義模型,checkpoints是必需的。

檢查點不包含模型定義的計算的任何描述,因此通常只有當原始碼可用時,保存的參數值才有用。

保存 Checkpoint
checkpoint_path = 「save_path」

# Defining a Checkpoint
ckpt = tf.train.Checkpoint(model=model, optimizer=optimizer)

# Creating a CheckpointManager Object
ckpt_manager = tf.train.CheckpointManager(ckpt, checkpoint_path, max_to_keep=5)

# Saving a Model
ckpt_manager.save()

從 Checkpoint 加載模型

TensorFlow從被加載的對象開始,通過遍歷帶有帶有名字的邊的有向圖來將變量與檢查點值匹配。

if ckpt_manager.latest_checkpoint:
    ckpt.restore(ckpt_manager.latest_checkpoint)

9. Keras Tuner

這是TensorFlow中的一個相當新的特性。

!pip install keras-tuner

超參數調優調優是對定義的ML模型配置的參數進行篩選的過程。在特徵工程和預處理之後,這些因素是模型性能的決定性因素。

# model_builder is a function that builds a model and returns it
tuner = kt.Hyperband(
    model_builder,
    objective='val_accuracy', 
    max_epochs=10,
    factor=3,
    directory='my_dir',
    project_name='intro_to_kt'
)

除了HyperBand之外,BayesianOptimization和RandomSearch 也可用於調優。

tuner.search(
    img_train, label_train, 
    epochs = 10, 
    validation_data=(img_test,label_test), 
    callbacks=[ClearTrainingOutput()]
)

# Get the optimal hyperparameters
best_hps = tuner.get_best_hyperparameters(num_trials=1)[0]

然後,我們使用最優超參數訓練模型:

model = tuner.hypermodel.build(best_hps)
model.fit(
    img_train, 
    label_train, 
    epochs=10, 
    validation_data=(img_test, label_test)
)

10. 分布式訓練

如果你有多個GPU,並且希望通過分散訓練循環在多個GPU上優化訓練,TensorFlow的各種分布式訓練策略能夠優化GPU的使用,並為你操縱GPU上的訓練。

tf.distribute.MirroredStrategy是最常用的策略。它是如何工作的呢?

strategy = tf.distribute.MirroredStrategy()with strategy.scope():
    model = tf.keras.Sequential([
        tf.keras.layers.Conv2D(
            32, 3, activation='relu',  input_shape=(28, 28, 1)
        ),
        tf.keras.layers.MaxPooling2D(),
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dense(64, activation='relu'),
        tf.keras.layers.Dense(10)
    ])

    model.compile(
        loss="sparse_categorical_crossentropy",
        optimizer="adam",
        metrics=['accuracy']
    )

相關焦點

  • 帶你入門機器學習與TensorFlow2.x
    TensorFlow 1.5 到 1.10 版本使用的是 cuDNN 7.0 版本(安裝包為 cudnn-9.0- windows10-x64-v7.rar)。TensorFlow 1.11 和 1.12 版本使用的是 cuDNN 7.2 版本(安裝包為 cudnn-9.0- windows10-x64-v7.2.1.38.zip)。4.
  • tensorflow2.x入門(二)
    空間複雜度:    上圖為兩層    左圖3*4+4 + 4*2+2 =26    (輸入層3個單元,所以三行,隱藏層4個單元,所以4列)時間複雜度        有幾條乘加曲線,就有幾次乘加運算注意:只統計具有運算能力的層,所以不統計輸入層。
  • TensorFlow應用實戰 | TensorFlow基礎知識
    # -*- coding: UTF-8 -*-# 引入tensorflowimport tensorflow as tf# 設置了gpu加速提示信息太多了,設置日誌等級屏蔽一些import osos.environ['TF_CPP_MIN_LOG_LEVEL']='2'# 創建兩個常量 Tensor.第一個為
  • tensorflow2.x入門(一)
    數據類型tf.convert_to_tensor(數據名, dtype=數據類型)b = np.arange(0, 5)將b轉換為tensorc = tf.convert_to_tensor(b, dtype=tf.int64)創建一個tensortf.zeros(維度)tf.ones(維度)
  • TensorFlow極速入門
    二、 tensorflow基礎實際上編寫tensorflow可以總結為兩步.(1)組裝一個graph;(2)使用session去執行graph中的operation。這種有向無環圖就叫做計算圖,因為對於圖中的每一個節點其微分都很容易得出,因此應用鏈式法則求得一個複雜的表達式的導數就成為可能,所以它會應用在類似tensorflow這種需要應用反向傳播算法的框架中。(2)概念說明下面是 graph , session , operation , tensor 四個概念的簡介。
  • TensorFlow學習
    TensorFlow學習0.導語1.Session會話控制(兩種打開模式)2.Tensorflow使用Variable3.Placeholder 傳入值4.激勵函數(activate function)5.定義添加神經層的函數6.建造神經網絡7.matplotlib 可視化8.學習文章TensorFlow學習0.導語本周將會陸續更新莫凡python配套視頻的自己學習筆記
  • tensorflow極速入門
    tensorflow 是 google 開源的機器學習工具,在2015年11月其實現正式開源,開源協議Apache 2.0。下圖是 query 詞頻時序圖,從中可以看出 tensorflow 的火爆程度。2、 why tensorflow?
  • tensorflow機器學習模型的跨平臺上線
    ,這個方法當然也適用於tensorflow生成的模型,但是由於tensorflow模型往往較大,使用無法優化的PMML文件大多數時候很笨拙,因此本文我們專門討論下tensorflow機器學習模型的跨平臺上線的方法。
  • 教程 | 維度、廣播操作與可視化:如何高效使用TensorFlow
    結果如下:import tensorflow as tfx = tf.random_normal([10, 10])y = tf.random_normal([10, 10])z = tf.matmul(x, y)sess = tf.Session()z_val = sess.run(z)print(z_val)與 numpy 直接執行計算並將結果複製到變量
  • 深度學習基礎(十):TensorFlow 2.x模型的驗證、正則化和回調
    否則,如果您無法使用機器學習模型來訓練模型所依據的數據,而無法成功地進行預測,那麼該方法又有什麼用呢?通過模型選擇和正則化來實現泛化和避免過度擬合。Tensorflow 2.x提供了 回調 函數的功能,工程師可以通過該 功能在培訓進行時根據保留的驗證集監視模型的性能。
  • 【工具】Tensorflow2.x(一)建立模型的三種模式
    前言最近做實驗比較焦慮,因此準備結合推薦算法梳理下Tensorflow2.x的知識。介紹Tensorflow2.x的文章有很多,但本文(系列)是按照作者構建模型的思路來展開的,因此不會從Eager Execution開始。另外,儘量擺脫小白文,加入自己的理解。本文約2.7k字,預計閱讀10分鐘。
  • 使用tensorflow和Keras的初級教程
    假設f(x)=2x+5和g(x)=3x-1。兩個輸入項的權重是不同的。在連結這些函數時,我們得到的是,f(g(x))=2(3x-1)+5=6x+3,這又是一個線性方程。非線性的缺失表現為深層神經網絡中等價於一個線性方程。這種情況下的複雜問題空間無法處理。損失函數在處理回歸問題時,我們不需要為輸出層使用任何激活函數。
  • tensorflow源碼解析之seq2seq.py文件(上)
    一、前言自從接觸並學習tensorflow框架之後,總是會遇到很多莫名奇妙的報錯信息。而網上又很少有相似的問題的解決方案。因此很久之前就想學一下tendorflow的源碼,能夠深層次的理解tensorflow這個框架。但是由於一些原因耽擱了。
  • TensorFlowSharp入門使用C#編寫TensorFlow人工智慧應用
    TensorFlow簡單介紹TensorFlow 是谷歌的第二代機器學習系統,按照谷歌所說,在某些基準測試中,TensorFlow的表現比第一代的DistBelief快了2倍。TensorFlow 內建深度學習的擴展支持,任何能夠用計算流圖形來表達的計算,都可以使用TensorFlow。
  • TensorFlow 2.1指南:keras模式、渴望模式和圖形模式(附代碼)
    Keras模式import numpy as npimport tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras.layers import Input, Dense, Flatten, Conv2Dfrom tensorflow.keras
  • TensorFlow開發者證書 中文手冊
    如果您通過了考試,但在10個工作日內沒有收到證書,或者如果您想選擇不接受您的證書,請在tensorflow-certificate-team@google.com與我們聯繫。2.0.0 和 tensorflow-datasets,conda install tensorflow==2.0.0,conda install tensorflow-datasets==1.3.2
  • TensorFlow 安裝詳解
    性能最優化三、安裝 TensorFlow環境:Mac OS 10.xTensorFlow 支持多種安裝,比如 Pip, Docker, Virtualenv, Anaconda 或源碼編譯的方法安裝 TensorFlow。我自己推薦當然是 Pip 安裝。什麼是 Pip ?
  • 人工智慧學習入門之TensorFlow2.2版本安裝(Windows10)
    conda 4.8.2創建虛擬環境並安裝Tensorflow使用Anaconda最大的特點是可以創建虛擬環境,這個虛擬環境是Python的執行環境。多個虛擬環境之間實現了隔離。這就好像在一個物理機上安裝虛擬機一樣。
  • TensorFlow 2.0 基礎:張量、自動求導與優化器
    時的導數:1import tensorflow as tf23x = tf.Variable(initial_value=3.)用自然語言描述這個函數的功能很繞口,但如果舉個例子就很容易理解了:如果a = [1, 3, 5],b = [2, 4, 6],那麼zip(a, b) = [(1, 2), (3, 4), ..., (5, 6)]。即 「將可迭代的對象作為參數,將對象中對應的元素打包成一個個元組,然後返回由這些元組組成的列表」。
  • 從Fashion-Mnist開始,入門Tensorflow與深度學習
    從今天開始,我們進行機器學習領域的最後一塊拼圖——深度學習的學習之旅,以及Tensorflow這個工具的使用。    好了,本次我們就用一個小案例帶著大家入門Tensorflow的使用。通過這個案例,大家可以初步感受到使用在Python中使用Tensorflow搭建神經算法的便利性。