10 個TensorFlow 2.x 使用技巧
作者 | Rohan Jagtap?
編譯 | ronghuaiyang
轉(zhuǎn)自 | AI公園
TensorFlow 2.x在構(gòu)建模型和TensorFlow的整體使用方面提供了很多簡單性。在本文中,我們將探索TF 2.0的10個特性,這些特性使得使用TensorFlow更加順暢,減少了代碼行數(shù)并提高了效率。

TensorFlow 2.x在構(gòu)建模型和TensorFlow的整體使用方面提供了很多簡單性。那么TF2有什么新變化呢?
使用Keras輕松構(gòu)建模型,立即執(zhí)行。 可在任何平臺上進行強大的模型部署。 強大的研究實驗。 通過清理過時的API和減少重復來簡化API。
在本文中,我們將探索TF 2.0的10個特性,這些特性使得使用TensorFlow更加順暢,減少了代碼行數(shù)并提高了效率。
1(a). tf.data 構(gòu)建輸入管道
tf.data提供了數(shù)據(jù)管道和相關(guān)操作的功能。我們可以建立管道,映射預處理函數(shù),洗牌或批處理數(shù)據(jù)集等等。
從tensors構(gòu)建管道
>>>?dataset?=?tf.data.Dataset.from_tensor_slices([8,?3,?0,?8,?2,?1])
>>>?iter(dataset).next().numpy()
8
構(gòu)建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()
(8 >,?1>)
映射外部函數(shù)
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能夠在批處理和預處理以及數(shù)據(jù)增強的同時實時生成數(shù)據(jù)集切片。
生成器允許直接從目錄或數(shù)據(jù)目錄中生成數(shù)據(jù)流。
ImageDataGenerator中關(guān)于數(shù)據(jù)增強的一個誤解是,它向現(xiàn)有數(shù)據(jù)集添加了更多的數(shù)據(jù)。雖然這是數(shù)據(jù)增強的實際定義,但是在ImageDataGenerator中,數(shù)據(jù)集中的圖像在訓練的不同步驟被動態(tài)地變換,使模型可以在未見過的有噪數(shù)據(jù)上進行訓練。
train_datagen?=?ImageDataGenerator(
????????rescale=1./255,
????????shear_range=0.2,
????????zoom_range=0.2,
????????horizontal_flip=True
)
在這里,對所有樣本進行重新縮放(用于歸一化),而其他參數(shù)用于增強。
train_generator?=?train_datagen.flow_from_directory(
????????'data/train',
????????target_size=(150,?150),
????????batch_size=32,
????????class_mode='binary'
)
我們?yōu)閷崟r數(shù)據(jù)流指定目錄。這也可以使用dataframes來完成。
train_generator?=?flow_from_dataframe(
????dataframe,
????x_col='filename',
????y_col='class',
????class_mode='categorical',
????batch_size=32
)
x_col參數(shù)定義圖像的完整路徑,而y_col參數(shù)定義用于分類的標簽列。
模型可直接用生成器來喂數(shù)據(jù)。需要指定steps_per_epoch參數(shù),即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做數(shù)據(jù)增強
數(shù)據(jù)增強是必要的。在數(shù)據(jù)不足的情況下,對數(shù)據(jù)進行更改并將其作為單獨的數(shù)據(jù)點來處理,是在較少數(shù)據(jù)下進行訓練的一種非常有效的方式。
tf.image API中有用于轉(zhuǎn)換圖像的工具,然后可以使用tf.data進行數(shù)據(jù)增強。
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從各個領域收集的非常著名的數(shù)據(jù)集。
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中可用的數(shù)據(jù)集的詳細列表可以在:https://www.tensorflow.org/datasets/catalog/overview中找到。
tfds提供的數(shù)據(jù)集類型包括:音頻,圖像,圖像分類,目標檢測,結(jié)構(gòu)化數(shù)據(jù),摘要,文本,翻譯,視頻。
4. 使用預訓練模型進行遷移學習
遷移學習是機器學習中的一項新技術(shù),非常重要。如果一個基準模型已經(jīng)被別人訓練過了,而且訓練它需要大量的資源(例如:多個昂貴的gpu,一個人可能負擔不起)。轉(zhuǎn)移學習,解決了這個問題。預先訓練好的模型可以在特定的場景中重用,也可以為不同的場景進行擴展。
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構(gòu)建和訓練estimator是多么容易。estimator也可以定制。
TensorFlow有許多estimator ,包括LinearRegressor,BoostedTreesClassifier等。
6. 自定義層
神經(jīng)網(wǎng)絡以許多層深網(wǎng)絡而聞名,其中層可以是不同的類型。TensorFlow包含許多預定義的層(如density, LSTM等)。但對于更復雜的體系結(jié)構(gòu),層的邏輯要比基礎的層復雜得多。對于這樣的情況,TensorFlow允許構(gòu)建自定義層。這可以通過子類化tf.keras.layers來實現(xiàn)。
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)
正如在文檔中所述,實現(xiàn)自己的層的最好方法是擴展 tf.keras.Layer類并實現(xiàn):
_init_,你可以在這里做所有與輸入無關(guān)的初始化。 build,其中你知道輸入張量的形狀,然后可以做剩下的初始化工作。 call,在這里進行前向計算。
雖然kernel的初始化可以在*_init_中完成,但是最好在build中進行初始化,否則你必須在創(chuàng)建新層的每個實例上顯式地指定input_shape*。
7. 自定義訓練
tf.keras Sequential 和Model API使得模型的訓練更加容易。然而,大多數(shù)時候在訓練復雜模型時,使用自定義損失函數(shù)。此外,模型訓練也可能不同于默認訓練(例如,分別對不同的模型組件求梯度)。
TensorFlow的自動微分有助于有效地計算梯度。這些原語用于定義自定義訓練循環(huán)。
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)
這個循環(huán)可以在多個epoch中重復,并且根據(jù)用例使用更定制的設置。
8. Checkpoints
保存一個TensorFlow模型可以有兩種方式:
SavedModel:保存模型的完整狀態(tài)以及所有參數(shù)。這是獨立于源代碼的。 model.save_weights('checkpoint')Checkpoints
Checkpoints 捕獲模型使用的所有參數(shù)的值。使用Sequential API或Model API構(gòu)建的模型可以簡單地以SavedModel格式保存。
然而,對于自定義模型,checkpoints是必需的。
檢查點不包含模型定義的計算的任何描述,因此通常只有當源代碼可用時,保存的參數(shù)值才有用。
保存 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
超參數(shù)調(diào)優(yōu)調(diào)優(yōu)是對定義的ML模型配置的參數(shù)進行篩選的過程。在特征工程和預處理之后,這些因素是模型性能的決定性因素。
#?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 也可用于調(diào)優(yōu)。
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]
然后,我們使用最優(yōu)超參數(shù)訓練模型:
model?=?tuner.hypermodel.build(best_hps)
model.fit(
????img_train,?
????label_train,?
????epochs=10,?
????validation_data=(img_test,?label_test)
)
10. 分布式訓練
如果你有多個GPU,并且希望通過分散訓練循環(huán)在多個GPU上優(yōu)化訓練,TensorFlow的各種分布式訓練策略能夠優(yōu)化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']
????)
英文原文:https://towardsdatascience.com/10-tensorflow-tricks-every-ml-practitioner-must-know-96b860e53c1
往期精彩:
【原創(chuàng)首發(fā)】機器學習公式推導與代碼實現(xiàn)30講.pdf
【原創(chuàng)首發(fā)】深度學習語義分割理論與實戰(zhàn)指南.pdf
